Path: blob/master/modules/lightmapper_rd/lightmapper_rd.cpp
10277 views
/**************************************************************************/1/* lightmapper_rd.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "lightmapper_rd.h"3132#include "core/string/print_string.h"33#include "lm_blendseams.glsl.gen.h"34#include "lm_compute.glsl.gen.h"35#include "lm_raster.glsl.gen.h"3637#include "core/config/project_settings.h"38#include "core/io/dir_access.h"39#include "core/math/geometry_2d.h"40#include "editor/file_system/editor_paths.h"41#include "editor/settings/editor_settings.h"42#include "servers/rendering/rendering_device_binds.h"43#include "servers/rendering/rendering_server_globals.h"4445#if defined(VULKAN_ENABLED)46#include "drivers/vulkan/rendering_context_driver_vulkan.h"47#endif48#if defined(METAL_ENABLED)49#include "drivers/metal/rendering_context_driver_metal.h"50#endif5152//uncomment this if you want to see textures from all the process saved53//#define DEBUG_TEXTURES5455void LightmapperRD::add_mesh(const MeshData &p_mesh) {56ERR_FAIL_COND(p_mesh.albedo_on_uv2.is_null() || p_mesh.albedo_on_uv2->is_empty());57ERR_FAIL_COND(p_mesh.emission_on_uv2.is_null() || p_mesh.emission_on_uv2->is_empty());58ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_width() != p_mesh.emission_on_uv2->get_width());59ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_height() != p_mesh.emission_on_uv2->get_height());60ERR_FAIL_COND(p_mesh.points.is_empty());61MeshInstance mi;62mi.data = p_mesh;63mesh_instances.push_back(mi);64}6566void LightmapperRD::add_directional_light(const String &p_name, bool p_static, const Vector3 &p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_angular_distance, float p_shadow_blur) {67Light l;68l.type = LIGHT_TYPE_DIRECTIONAL;69l.direction[0] = p_direction.x;70l.direction[1] = p_direction.y;71l.direction[2] = p_direction.z;72l.color[0] = p_color.r;73l.color[1] = p_color.g;74l.color[2] = p_color.b;75l.energy = p_energy;76l.indirect_energy = p_indirect_energy;77l.static_bake = p_static;78l.size = Math::tan(Math::deg_to_rad(p_angular_distance));79l.shadow_blur = p_shadow_blur;80lights.push_back(l);8182LightMetadata md;83md.name = p_name;84md.type = LIGHT_TYPE_DIRECTIONAL;85light_metadata.push_back(md);86}8788void LightmapperRD::add_omni_light(const String &p_name, bool p_static, const Vector3 &p_position, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_size, float p_shadow_blur) {89Light l;90l.type = LIGHT_TYPE_OMNI;91l.position[0] = p_position.x;92l.position[1] = p_position.y;93l.position[2] = p_position.z;94l.range = p_range;95l.attenuation = p_attenuation;96l.color[0] = p_color.r;97l.color[1] = p_color.g;98l.color[2] = p_color.b;99l.energy = p_energy;100l.indirect_energy = p_indirect_energy;101l.static_bake = p_static;102l.size = p_size;103l.shadow_blur = p_shadow_blur;104lights.push_back(l);105106LightMetadata md;107md.name = p_name;108md.type = LIGHT_TYPE_OMNI;109light_metadata.push_back(md);110}111112void LightmapperRD::add_spot_light(const String &p_name, bool p_static, const Vector3 &p_position, const Vector3 p_direction, const Color &p_color, float p_energy, float p_indirect_energy, float p_range, float p_attenuation, float p_spot_angle, float p_spot_attenuation, float p_size, float p_shadow_blur) {113Light l;114l.type = LIGHT_TYPE_SPOT;115l.position[0] = p_position.x;116l.position[1] = p_position.y;117l.position[2] = p_position.z;118l.direction[0] = p_direction.x;119l.direction[1] = p_direction.y;120l.direction[2] = p_direction.z;121l.range = p_range;122l.attenuation = p_attenuation;123l.cos_spot_angle = Math::cos(Math::deg_to_rad(p_spot_angle));124l.inv_spot_attenuation = 1.0f / p_spot_attenuation;125l.color[0] = p_color.r;126l.color[1] = p_color.g;127l.color[2] = p_color.b;128l.energy = p_energy;129l.indirect_energy = p_indirect_energy;130l.static_bake = p_static;131l.size = p_size;132l.shadow_blur = p_shadow_blur;133lights.push_back(l);134135LightMetadata md;136md.name = p_name;137md.type = LIGHT_TYPE_SPOT;138light_metadata.push_back(md);139}140141void LightmapperRD::add_probe(const Vector3 &p_position) {142Probe probe;143probe.position[0] = p_position.x;144probe.position[1] = p_position.y;145probe.position[2] = p_position.z;146probe.position[3] = 0;147probe_positions.push_back(probe);148}149150void LightmapperRD::_plot_triangle_into_triangle_index_list(int p_size, const Vector3i &p_ofs, const AABB &p_bounds, const Vector3 p_points[3], uint32_t p_triangle_index, LocalVector<TriangleSort> &p_triangles_sort, uint32_t p_grid_size) {151int half_size = p_size / 2;152153for (int i = 0; i < 8; i++) {154AABB aabb = p_bounds;155aabb.size *= 0.5;156Vector3i n = p_ofs;157158if (i & 1) {159aabb.position.x += aabb.size.x;160n.x += half_size;161}162if (i & 2) {163aabb.position.y += aabb.size.y;164n.y += half_size;165}166if (i & 4) {167aabb.position.z += aabb.size.z;168n.z += half_size;169}170171{172Vector3 qsize = aabb.size * 0.5; //quarter size, for fast aabb test173174if (!Geometry3D::triangle_box_overlap(aabb.position + qsize, qsize, p_points)) {175//does not fit in child, go on176continue;177}178}179180if (half_size == 1) {181//got to the end182TriangleSort ts;183ts.cell_index = n.x + (n.y * p_grid_size) + (n.z * p_grid_size * p_grid_size);184ts.triangle_index = p_triangle_index;185ts.triangle_aabb.position = p_points[0];186ts.triangle_aabb.size = Vector3();187ts.triangle_aabb.expand_to(p_points[1]);188ts.triangle_aabb.expand_to(p_points[2]);189p_triangles_sort.push_back(ts);190} else {191_plot_triangle_into_triangle_index_list(half_size, n, aabb, p_points, p_triangle_index, p_triangles_sort, p_grid_size);192}193}194}195196void LightmapperRD::_sort_triangle_clusters(uint32_t p_cluster_size, uint32_t p_cluster_index, uint32_t p_index_start, uint32_t p_count, LocalVector<TriangleSort> &p_triangle_sort, LocalVector<ClusterAABB> &p_cluster_aabb) {197if (p_count == 0) {198return;199}200201// Compute AABB for all triangles in the range.202SortArray<TriangleSort, TriangleSortAxis<0>> triangle_sorter_x;203SortArray<TriangleSort, TriangleSortAxis<1>> triangle_sorter_y;204SortArray<TriangleSort, TriangleSortAxis<2>> triangle_sorter_z;205AABB cluster_aabb = p_triangle_sort[p_index_start].triangle_aabb;206for (uint32_t i = 1; i < p_count; i++) {207cluster_aabb.merge_with(p_triangle_sort[p_index_start + i].triangle_aabb);208}209210if (p_count > p_cluster_size) {211int longest_axis_index = cluster_aabb.get_longest_axis_index();212switch (longest_axis_index) {213case 0:214triangle_sorter_x.sort(&p_triangle_sort[p_index_start], p_count);215break;216case 1:217triangle_sorter_y.sort(&p_triangle_sort[p_index_start], p_count);218break;219case 2:220triangle_sorter_z.sort(&p_triangle_sort[p_index_start], p_count);221break;222default:223DEV_ASSERT(false && "Invalid axis returned by AABB.");224break;225}226227uint32_t left_cluster_count = next_power_of_2(p_count / 2);228left_cluster_count = MAX(left_cluster_count, p_cluster_size);229left_cluster_count = MIN(left_cluster_count, p_count);230_sort_triangle_clusters(p_cluster_size, p_cluster_index, p_index_start, left_cluster_count, p_triangle_sort, p_cluster_aabb);231232if (left_cluster_count < p_count) {233uint32_t cluster_index_right = p_cluster_index + (left_cluster_count / p_cluster_size);234_sort_triangle_clusters(p_cluster_size, cluster_index_right, p_index_start + left_cluster_count, p_count - left_cluster_count, p_triangle_sort, p_cluster_aabb);235}236} else {237ClusterAABB &aabb = p_cluster_aabb[p_cluster_index];238Vector3 aabb_end = cluster_aabb.get_end();239aabb.min_bounds[0] = cluster_aabb.position.x;240aabb.min_bounds[1] = cluster_aabb.position.y;241aabb.min_bounds[2] = cluster_aabb.position.z;242aabb.max_bounds[0] = aabb_end.x;243aabb.max_bounds[1] = aabb_end.y;244aabb.max_bounds[2] = aabb_end.z;245}246}247248Lightmapper::BakeError LightmapperRD::_blit_meshes_into_atlas(int p_max_texture_size, int p_denoiser_range, Vector<Ref<Image>> &albedo_images, Vector<Ref<Image>> &emission_images, AABB &bounds, Size2i &atlas_size, int &atlas_slices, float p_supersampling_factor, BakeStepFunc p_step_function, void *p_bake_userdata) {249Vector<Size2i> sizes;250251for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {252MeshInstance &mi = mesh_instances.write[m_i];253Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height());254sizes.push_back(s);255atlas_size = atlas_size.max(s + Size2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor);256}257258int max = nearest_power_of_2_templated(atlas_size.width);259max = MAX(max, nearest_power_of_2_templated(atlas_size.height));260261if (max > p_max_texture_size) {262return BAKE_ERROR_TEXTURE_EXCEEDS_MAX_SIZE;263}264265if (p_step_function) {266if (p_step_function(0.1, RTR("Determining optimal atlas size"), p_bake_userdata, true)) {267return BAKE_ERROR_USER_ABORTED;268}269}270271atlas_size = Size2i(max, max);272273Size2i best_atlas_size;274int best_atlas_slices = 0;275int best_atlas_memory = 0x7FFFFFFF;276Vector<Vector3i> best_atlas_offsets;277278// Determine best texture array atlas size by bruteforce fitting.279while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) {280Vector<Vector2i> source_sizes;281Vector<int> source_indices;282source_sizes.resize(sizes.size());283source_indices.resize(sizes.size());284for (int i = 0; i < source_indices.size(); i++) {285// Add padding between lightmaps.286// Scale the padding if the lightmap will be downsampled at the end of the baking process287// Otherwise the padding would be insufficient.288source_sizes.write[i] = sizes[i] + Vector2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor;289source_indices.write[i] = i;290}291Vector<Vector3i> atlas_offsets;292atlas_offsets.resize(source_sizes.size());293294// Ensure the sizes can all fit into a single atlas layer.295// This should always happen, and this check is only in place to prevent an infinite loop.296for (int i = 0; i < source_sizes.size(); i++) {297if (source_sizes[i] > atlas_size) {298return BAKE_ERROR_ATLAS_TOO_SMALL;299}300}301302int slices = 0;303304while (source_sizes.size() > 0) {305Vector<Vector3i> offsets = Geometry2D::partial_pack_rects(source_sizes, atlas_size);306Vector<int> new_indices;307Vector<Vector2i> new_sources;308for (int i = 0; i < offsets.size(); i++) {309Vector3i ofs = offsets[i];310int sidx = source_indices[i];311if (ofs.z > 0) {312//valid313ofs.z = slices;314atlas_offsets.write[sidx] = ofs + Vector3i(1, 1, 0); // Center lightmap in the reserved oversized region315} else {316new_indices.push_back(sidx);317new_sources.push_back(source_sizes[i]);318}319}320321source_sizes = new_sources;322source_indices = new_indices;323slices++;324}325326int mem_used = atlas_size.x * atlas_size.y * slices;327if (mem_used < best_atlas_memory) {328best_atlas_size = atlas_size;329best_atlas_offsets = atlas_offsets;330best_atlas_slices = slices;331best_atlas_memory = mem_used;332}333334if (atlas_size.width == atlas_size.height) {335atlas_size.width *= 2;336} else {337atlas_size.height *= 2;338}339}340atlas_size = best_atlas_size;341atlas_slices = best_atlas_slices;342343// apply the offsets and slice to all images, and also blit albedo and emission344albedo_images.resize(atlas_slices);345emission_images.resize(atlas_slices);346347if (p_step_function) {348if (p_step_function(0.2, RTR("Blitting albedo and emission"), p_bake_userdata, true)) {349return BAKE_ERROR_USER_ABORTED;350}351}352353for (int i = 0; i < atlas_slices; i++) {354Ref<Image> albedo = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);355albedo->set_as_black();356albedo_images.write[i] = albedo;357358Ref<Image> emission = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);359emission->set_as_black();360emission_images.write[i] = emission;361}362363//assign uv positions364365for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {366MeshInstance &mi = mesh_instances.write[m_i];367mi.offset.x = best_atlas_offsets[m_i].x;368mi.offset.y = best_atlas_offsets[m_i].y;369mi.slice = best_atlas_offsets[m_i].z;370albedo_images.write[mi.slice]->blit_rect(mi.data.albedo_on_uv2, Rect2i(Vector2i(), mi.data.albedo_on_uv2->get_size()), mi.offset);371emission_images.write[mi.slice]->blit_rect(mi.data.emission_on_uv2, Rect2(Vector2i(), mi.data.emission_on_uv2->get_size()), mi.offset);372}373374return BAKE_OK;375}376377void LightmapperRD::_create_acceleration_structures(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, AABB &bounds, int grid_size, uint32_t p_cluster_size, Vector<Probe> &p_probe_positions, GenerateProbes p_generate_probes, Vector<int> &slice_triangle_count, Vector<int> &slice_seam_count, RID &vertex_buffer, RID &triangle_buffer, RID &lights_buffer, RID &r_triangle_indices_buffer, RID &r_cluster_indices_buffer, RID &r_cluster_aabbs_buffer, RID &probe_positions_buffer, RID &grid_texture, RID &seams_buffer, BakeStepFunc p_step_function, void *p_bake_userdata) {378HashMap<Vertex, uint32_t, VertexHash> vertex_map;379380//fill triangles array and vertex array381LocalVector<Triangle> triangles;382LocalVector<Vertex> vertex_array;383LocalVector<Seam> seams;384385slice_triangle_count.resize(atlas_slices);386slice_seam_count.resize(atlas_slices);387388for (int i = 0; i < atlas_slices; i++) {389slice_triangle_count.write[i] = 0;390slice_seam_count.write[i] = 0;391}392393bounds = AABB();394395for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {396if (p_step_function) {397float p = float(m_i + 1) / MAX(1, mesh_instances.size()) * 0.1;398p_step_function(0.3 + p, vformat(RTR("Plotting mesh into acceleration structure %d/%d"), m_i + 1, mesh_instances.size()), p_bake_userdata, false);399}400401HashMap<Edge, EdgeUV2, EdgeHash> edges;402403MeshInstance &mi = mesh_instances.write[m_i];404405Vector2 uv_scale = Vector2(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()) / Vector2(atlas_size);406Vector2 uv_offset = Vector2(mi.offset) / Vector2(atlas_size);407if (m_i == 0) {408bounds.position = mi.data.points[0];409}410411for (int i = 0; i < mi.data.points.size(); i += 3) {412Vector3 vtxs[3] = { mi.data.points[i + 0], mi.data.points[i + 1], mi.data.points[i + 2] };413Vector2 uvs[3] = { mi.data.uv2[i + 0] * uv_scale + uv_offset, mi.data.uv2[i + 1] * uv_scale + uv_offset, mi.data.uv2[i + 2] * uv_scale + uv_offset };414Vector3 normal[3] = { mi.data.normal[i + 0], mi.data.normal[i + 1], mi.data.normal[i + 2] };415416AABB taabb;417Triangle t;418t.slice = mi.slice;419for (int k = 0; k < 3; k++) {420bounds.expand_to(vtxs[k]);421422Vertex v;423v.position[0] = vtxs[k].x;424v.position[1] = vtxs[k].y;425v.position[2] = vtxs[k].z;426v.uv[0] = uvs[k].x;427v.uv[1] = uvs[k].y;428v.normal_xy[0] = normal[k].x;429v.normal_xy[1] = normal[k].y;430v.normal_z = normal[k].z;431432uint32_t *indexptr = vertex_map.getptr(v);433434if (indexptr) {435t.indices[k] = *indexptr;436} else {437uint32_t new_index = vertex_map.size();438t.indices[k] = new_index;439vertex_map[v] = new_index;440vertex_array.push_back(v);441}442443if (k == 0) {444taabb.position = vtxs[k];445} else {446taabb.expand_to(vtxs[k]);447}448}449450//compute seams that will need to be blended later451for (int k = 0; k < 3; k++) {452int n = (k + 1) % 3;453454Edge edge(vtxs[k], vtxs[n], normal[k], normal[n]);455Vector2i edge_indices(t.indices[k], t.indices[n]);456EdgeUV2 uv2(uvs[k], uvs[n], edge_indices);457458if (edge.b == edge.a) {459continue; //degenerate, somehow460}461if (edge.b < edge.a) {462SWAP(edge.a, edge.b);463SWAP(edge.na, edge.nb);464SWAP(uv2.a, uv2.b);465SWAP(uv2.indices.x, uv2.indices.y);466SWAP(edge_indices.x, edge_indices.y);467}468469EdgeUV2 *euv2 = edges.getptr(edge);470if (!euv2) {471edges[edge] = uv2;472} else {473if (*euv2 == uv2) {474continue; // seam shared UV space, no need to blend475}476if (euv2->seam_found) {477continue; //bad geometry478}479480Seam seam;481seam.a = edge_indices;482seam.b = euv2->indices;483seam.slice = mi.slice;484seams.push_back(seam);485slice_seam_count.write[mi.slice]++;486euv2->seam_found = true;487}488}489490t.min_bounds[0] = taabb.position.x;491t.min_bounds[1] = taabb.position.y;492t.min_bounds[2] = taabb.position.z;493t.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);494t.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);495t.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);496497t.cull_mode = RS::CULL_MODE_BACK;498499RID material = mi.data.material[i];500if (material.is_valid()) {501t.cull_mode = RSG::material_storage->material_get_cull_mode(material);502}503t.pad1 = 0; //make valgrind not complain504triangles.push_back(t);505slice_triangle_count.write[t.slice]++;506}507}508509//also consider probe positions for bounds510for (int i = 0; i < p_probe_positions.size(); i++) {511Vector3 pp(p_probe_positions[i].position[0], p_probe_positions[i].position[1], p_probe_positions[i].position[2]);512bounds.expand_to(pp);513}514bounds.grow_by(0.1); //grow a bit to avoid numerical error515516triangles.sort(); //sort by slice517seams.sort();518519if (p_step_function) {520p_step_function(0.4, RTR("Optimizing acceleration structure"), p_bake_userdata, true);521}522523//fill list of triangles in grid524LocalVector<TriangleSort> triangle_sort;525for (uint32_t i = 0; i < triangles.size(); i++) {526const Triangle &t = triangles[i];527Vector3 face[3] = {528Vector3(vertex_array[t.indices[0]].position[0], vertex_array[t.indices[0]].position[1], vertex_array[t.indices[0]].position[2]),529Vector3(vertex_array[t.indices[1]].position[0], vertex_array[t.indices[1]].position[1], vertex_array[t.indices[1]].position[2]),530Vector3(vertex_array[t.indices[2]].position[0], vertex_array[t.indices[2]].position[1], vertex_array[t.indices[2]].position[2])531};532_plot_triangle_into_triangle_index_list(grid_size, Vector3i(), bounds, face, i, triangle_sort, grid_size);533}534//sort it535triangle_sort.sort();536537LocalVector<uint32_t> cluster_indices;538LocalVector<ClusterAABB> cluster_aabbs;539Vector<uint32_t> triangle_indices;540triangle_indices.resize(triangle_sort.size());541Vector<uint32_t> grid_indices;542grid_indices.resize(grid_size * grid_size * grid_size * 2);543memset(grid_indices.ptrw(), 0, grid_indices.size() * sizeof(uint32_t));544545{546// Fill grid with cell indices.547uint32_t last_cell = 0xFFFFFFFF;548uint32_t *giw = grid_indices.ptrw();549uint32_t cluster_count = 0;550uint32_t solid_cell_count = 0;551for (uint32_t i = 0; i < triangle_sort.size(); i++) {552uint32_t cell = triangle_sort[i].cell_index;553if (cell != last_cell) {554giw[cell * 2 + 1] = solid_cell_count;555solid_cell_count++;556}557558if ((giw[cell * 2] % p_cluster_size) == 0) {559// Add an extra cluster every time the triangle counter reaches a multiple of the cluster size.560cluster_count++;561}562563giw[cell * 2]++;564last_cell = cell;565}566567// Build fixed-size triangle clusters for all the cells to speed up the traversal. A cell can hold multiple clusters that each contain a fixed568// amount of triangles and an AABB. The tracer will check against the AABBs first to know whether it needs to visit the cell's triangles.569//570// The building algorithm will divide the triangles recursively contained inside each cell, sorting by the longest axis of the AABB on each step.571//572// - If the amount of triangles is less or equal to the cluster size, the AABB will be stored and the algorithm stops.573//574// - The division by two is increased to the next power of two of half the amount of triangles (with cluster size as the minimum value) to575// ensure the first half always fills the cluster.576577cluster_indices.resize(solid_cell_count * 2);578cluster_aabbs.resize(cluster_count);579580uint32_t i = 0;581uint32_t cluster_index = 0;582uint32_t solid_cell_index = 0;583uint32_t *tiw = triangle_indices.ptrw();584while (i < triangle_sort.size()) {585cluster_indices[solid_cell_index * 2] = cluster_index;586cluster_indices[solid_cell_index * 2 + 1] = i;587588uint32_t cell = triangle_sort[i].cell_index;589uint32_t triangle_count = giw[cell * 2];590uint32_t cell_cluster_count = (triangle_count + p_cluster_size - 1) / p_cluster_size;591_sort_triangle_clusters(p_cluster_size, cluster_index, i, triangle_count, triangle_sort, cluster_aabbs);592593for (uint32_t j = 0; j < triangle_count; j++) {594tiw[i + j] = triangle_sort[i + j].triangle_index;595}596597i += triangle_count;598cluster_index += cell_cluster_count;599solid_cell_index++;600}601}602#if 0603for (int i = 0; i < grid_size; i++) {604for (int j = 0; j < grid_size; j++) {605for (int k = 0; k < grid_size; k++) {606uint32_t index = i * (grid_size * grid_size) + j * grid_size + k;607grid_indices.write[index * 2] = float(i) / grid_size * 255;608grid_indices.write[index * 2 + 1] = float(j) / grid_size * 255;609}610}611}612#endif613614#if 0615for (int i = 0; i < grid_size; i++) {616Vector<uint8_t> grid_usage;617grid_usage.resize(grid_size * grid_size);618for (int j = 0; j < grid_usage.size(); j++) {619uint32_t ofs = i * grid_size * grid_size + j;620uint32_t count = grid_indices[ofs * 2];621grid_usage.write[j] = count > 0 ? 255 : 0;622}623624Ref<Image> img = Image::create_from_data(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);625img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png");626}627#endif628629/*****************************/630/*** CREATE GPU STRUCTURES ***/631/*****************************/632633lights.sort();634light_metadata.sort();635636Vector<Vector2i> seam_buffer_vec;637seam_buffer_vec.resize(seams.size() * 2);638for (uint32_t i = 0; i < seams.size(); i++) {639seam_buffer_vec.write[i * 2 + 0] = seams[i].a;640seam_buffer_vec.write[i * 2 + 1] = seams[i].b;641}642643{ //buffers644vertex_buffer = rd->storage_buffer_create(vertex_array.size() * sizeof(Vertex), vertex_array.span().reinterpret<uint8_t>());645646triangle_buffer = rd->storage_buffer_create(triangles.size() * sizeof(Triangle), triangles.span().reinterpret<uint8_t>());647648r_triangle_indices_buffer = rd->storage_buffer_create(triangle_indices.size() * sizeof(uint32_t), triangle_indices.span().reinterpret<uint8_t>());649650r_cluster_indices_buffer = rd->storage_buffer_create(cluster_indices.size() * sizeof(uint32_t), cluster_indices.span().reinterpret<uint8_t>());651652r_cluster_aabbs_buffer = rd->storage_buffer_create(cluster_aabbs.size() * sizeof(ClusterAABB), cluster_aabbs.span().reinterpret<uint8_t>());653654// Even when there are no lights, the buffer must exist.655static const Light empty_lights[1];656Span<uint8_t> lb = (lights.is_empty() ? Span(empty_lights) : lights.span()).reinterpret<uint8_t>();657lights_buffer = rd->storage_buffer_create(lb.size(), lb);658659// Even when there are no seams, the buffer must exist.660static const Vector2i empty_seams[2];661Span<uint8_t> sb = (seam_buffer_vec.is_empty() ? Span(empty_seams) : seam_buffer_vec.span()).reinterpret<uint8_t>();662seams_buffer = rd->storage_buffer_create(sb.size(), sb);663664// Even when there are no probes, the buffer must exist.665static const Probe empty_probes[1];666Span<uint8_t> pb = (p_probe_positions.is_empty() ? Span(empty_probes) : p_probe_positions.span()).reinterpret<uint8_t>();667probe_positions_buffer = rd->storage_buffer_create(pb.size(), pb);668}669670{ //grid671672RD::TextureFormat tf;673tf.width = grid_size;674tf.height = grid_size;675tf.depth = grid_size;676tf.texture_type = RD::TEXTURE_TYPE_3D;677tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;678679Vector<Vector<uint8_t>> texdata;680texdata.resize(1);681//grid and indices682tf.format = RD::DATA_FORMAT_R32G32_UINT;683texdata.write[0] = grid_indices.to_byte_array();684grid_texture = rd->texture_create(tf, RD::TextureView(), texdata);685}686}687688void LightmapperRD::_raster_geometry(RenderingDevice *rd, Size2i atlas_size, int atlas_slices, int grid_size, AABB bounds, float p_bias, Vector<int> slice_triangle_count, RID position_tex, RID unocclude_tex, RID normal_tex, RID raster_depth_buffer, RID rasterize_shader, RID raster_base_uniform) {689Vector<RID> framebuffers;690691for (int i = 0; i < atlas_slices; i++) {692RID slice_pos_tex = rd->texture_create_shared_from_slice(RD::TextureView(), position_tex, i, 0);693RID slice_unoc_tex = rd->texture_create_shared_from_slice(RD::TextureView(), unocclude_tex, i, 0);694RID slice_norm_tex = rd->texture_create_shared_from_slice(RD::TextureView(), normal_tex, i, 0);695Vector<RID> fb;696fb.push_back(slice_pos_tex);697fb.push_back(slice_norm_tex);698fb.push_back(slice_unoc_tex);699fb.push_back(raster_depth_buffer);700framebuffers.push_back(rd->framebuffer_create(fb));701}702703RD::PipelineDepthStencilState ds;704ds.enable_depth_test = true;705ds.enable_depth_write = true;706ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does render same pixel twice707708RID raster_pipeline = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0);709RID raster_pipeline_wire;710{711RD::PipelineRasterizationState rw;712rw.wireframe = true;713raster_pipeline_wire = rd->render_pipeline_create(rasterize_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, rw, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(3), 0);714}715716uint32_t triangle_offset = 0;717Vector<Color> clear_colors;718clear_colors.push_back(Color(0, 0, 0, 0));719clear_colors.push_back(Color(0, 0, 0, 0));720clear_colors.push_back(Color(0, 0, 0, 0));721722for (int i = 0; i < atlas_slices; i++) {723RasterPushConstant raster_push_constant;724raster_push_constant.atlas_size[0] = atlas_size.x;725raster_push_constant.atlas_size[1] = atlas_size.y;726raster_push_constant.base_triangle = triangle_offset;727raster_push_constant.to_cell_offset[0] = bounds.position.x;728raster_push_constant.to_cell_offset[1] = bounds.position.y;729raster_push_constant.to_cell_offset[2] = bounds.position.z;730raster_push_constant.bias = p_bias;731raster_push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);732raster_push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);733raster_push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);734raster_push_constant.grid_size[0] = grid_size;735raster_push_constant.grid_size[1] = grid_size;736raster_push_constant.grid_size[2] = grid_size;737738// Half pixel offset is required so the rasterizer doesn't output face edges directly aligned into pixels.739// This fixes artifacts where the pixel would be traced from the edge of a face, causing half the rays to740// be outside of the boundaries of the geometry. See <https://github.com/godotengine/godot/issues/69126>.741raster_push_constant.uv_offset[0] = -0.5f / float(atlas_size.x);742raster_push_constant.uv_offset[1] = -0.5f / float(atlas_size.y);743744RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::DRAW_CLEAR_ALL, clear_colors, 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::LIGHTMAPPER_PASS);745//draw opaque746rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline);747rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);748rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));749rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);750//draw wire751rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline_wire);752rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);753rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));754rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);755756rd->draw_list_end();757758triangle_offset += slice_triangle_count[i];759}760}761762static Vector<RD::Uniform> dilate_or_denoise_common_uniforms(RID &p_source_light_tex, RID &p_dest_light_tex) {763Vector<RD::Uniform> uniforms;764{765RD::Uniform u;766u.uniform_type = RD::UNIFORM_TYPE_IMAGE;767u.binding = 0;768u.append_id(p_dest_light_tex);769uniforms.push_back(u);770}771{772RD::Uniform u;773u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;774u.binding = 1;775u.append_id(p_source_light_tex);776uniforms.push_back(u);777}778779return uniforms;780}781782LightmapperRD::BakeError LightmapperRD::_dilate(RenderingDevice *rd, Ref<RDShaderFile> &compute_shader, RID &compute_base_uniform_set, PushConstant &push_constant, RID &source_light_tex, RID &dest_light_tex, const Size2i &atlas_size, int atlas_slices) {783Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex);784785RID compute_shader_dilate = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("dilate"));786ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen787RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate);788789RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_dilate, 1);790791RD::ComputeListID compute_list = rd->compute_list_begin();792rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_dilate_pipeline);793rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);794rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);795push_constant.region_ofs[0] = 0;796push_constant.region_ofs[1] = 0;797Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size798799for (int i = 0; i < atlas_slices; i++) {800push_constant.atlas_slice = i;801rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));802rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);803//no barrier, let them run all together804}805rd->compute_list_end();806rd->free(compute_shader_dilate);807808#ifdef DEBUG_TEXTURES809for (int i = 0; i < atlas_slices; i++) {810Vector<uint8_t> s = rd->texture_get_data(source_light_tex, i);811Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);812img->convert(Image::FORMAT_RGBA8);813img->save_png("res://5_dilated_" + itos(i) + ".png");814}815#endif816return BAKE_OK;817}818819LightmapperRD::BakeError LightmapperRD::_pack_l1(RenderingDevice *rd, Ref<RDShaderFile> &compute_shader, RID &compute_base_uniform_set, PushConstant &push_constant, RID &source_light_tex, RID &dest_light_tex, const Size2i &atlas_size, int atlas_slices) {820Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex);821822RID compute_shader_pack = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("pack_coeffs"));823ERR_FAIL_COND_V(compute_shader_pack.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen824RID compute_shader_pack_pipeline = rd->compute_pipeline_create(compute_shader_pack);825826RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_pack, 1);827828RD::ComputeListID compute_list = rd->compute_list_begin();829rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_pack_pipeline);830rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);831rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);832push_constant.region_ofs[0] = 0;833push_constant.region_ofs[1] = 0;834Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size835836for (int i = 0; i < atlas_slices; i++) {837push_constant.atlas_slice = i;838rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));839rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);840//no barrier, let them run all together841}842rd->compute_list_end();843rd->free(compute_shader_pack);844845return BAKE_OK;846}847848Error LightmapperRD::_store_pfm(RenderingDevice *p_rd, RID p_atlas_tex, int p_index, const Size2i &p_atlas_size, const String &p_name, bool p_shadowmask) {849Vector<uint8_t> data = p_rd->texture_get_data(p_atlas_tex, p_index);850Ref<Image> img = Image::create_from_data(p_atlas_size.width, p_atlas_size.height, false, p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH, data);851img->convert(Image::FORMAT_RGBF);852Vector<uint8_t> data_float = img->get_data();853854Error err = OK;855Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::WRITE, &err);856ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save PFN at path: '%s'.", p_name));857file->store_line("PF");858file->store_line(vformat("%d %d", img->get_width(), img->get_height()));859#ifdef BIG_ENDIAN_ENABLED860file->store_line("1.0");861#else862file->store_line("-1.0");863#endif864file->store_buffer(data_float);865file->close();866867return OK;868}869870Ref<Image> LightmapperRD::_read_pfm(const String &p_name, bool p_shadowmask) {871Error err = OK;872Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::READ, &err);873ERR_FAIL_COND_V_MSG(err, Ref<Image>(), vformat("Can't load PFM at path: '%s'.", p_name));874ERR_FAIL_COND_V(file->get_line() != "PF", Ref<Image>());875876Vector<String> new_size = file->get_line().split(" ");877ERR_FAIL_COND_V(new_size.size() != 2, Ref<Image>());878int new_width = new_size[0].to_int();879int new_height = new_size[1].to_int();880881float endian = file->get_line().to_float();882Vector<uint8_t> new_data = file->get_buffer(file->get_length() - file->get_position());883file->close();884885#ifdef BIG_ENDIAN_ENABLED886if (unlikely(endian < 0.0)) {887uint32_t count = new_data.size() / 4;888uint16_t *dst = (uint16_t *)new_data.ptrw();889for (uint32_t j = 0; j < count; j++) {890dst[j * 4] = BSWAP32(dst[j * 4]);891}892}893#else894if (unlikely(endian > 0.0)) {895uint32_t count = new_data.size() / 4;896uint16_t *dst = (uint16_t *)new_data.ptrw();897for (uint32_t j = 0; j < count; j++) {898dst[j * 4] = BSWAP32(dst[j * 4]);899}900}901#endif902Ref<Image> img = Image::create_from_data(new_width, new_height, false, Image::FORMAT_RGBF, new_data);903img->convert(p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH);904return img;905}906907LightmapperRD::BakeError LightmapperRD::_denoise_oidn(RenderingDevice *p_rd, RID p_source_light_tex, RID p_source_normal_tex, RID p_dest_light_tex, const Size2i &p_atlas_size, int p_atlas_slices, bool p_bake_sh, bool p_shadowmask, const String &p_exe) {908Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);909910for (int i = 0; i < p_atlas_slices; i++) {911String fname_norm_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_norm_%d.pfm", i));912_store_pfm(p_rd, p_source_normal_tex, i, p_atlas_size, fname_norm_in, false);913914for (int j = 0; j < (p_bake_sh ? 4 : 1); j++) {915int index = i * (p_bake_sh ? 4 : 1) + j;916String fname_light_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_light_%d.pfm", index));917String fname_out = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_denoised_%d.pfm", index));918919_store_pfm(p_rd, p_source_light_tex, index, p_atlas_size, fname_light_in, p_shadowmask);920921List<String> args;922args.push_back("--device");923args.push_back("default");924925args.push_back("--filter");926args.push_back("RTLightmap");927928args.push_back(p_shadowmask ? "--ldr" : "--hdr");929args.push_back(fname_light_in);930931args.push_back("--nrm");932args.push_back(fname_norm_in);933934args.push_back("--output");935args.push_back(fname_out);936937String str;938int exitcode = 0;939940Error err = OS::get_singleton()->execute(p_exe, args, &str, &exitcode, true);941942da->remove(fname_light_in);943944if (err != OK || exitcode != 0) {945da->remove(fname_out);946print_verbose(str);947ERR_FAIL_V_MSG(BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, vformat("OIDN denoiser failed, return code: %d", exitcode));948}949950Ref<Image> img = _read_pfm(fname_out, p_shadowmask);951da->remove(fname_out);952953ERR_FAIL_COND_V(img.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);954955Vector<uint8_t> old_data = p_rd->texture_get_data(p_source_light_tex, index);956Vector<uint8_t> new_data = img->get_data();957img.unref(); // Avoid copy on write.958959uint32_t count = old_data.size() / 2;960const uint16_t *src = (const uint16_t *)old_data.ptr();961uint16_t *dst = (uint16_t *)new_data.ptrw();962for (uint32_t k = 0; k < count; k += 4) {963dst[k + 3] = src[k + 3];964}965966p_rd->texture_update(p_dest_light_tex, index, new_data);967}968da->remove(fname_norm_in);969}970return BAKE_OK;971}972973LightmapperRD::BakeError LightmapperRD::_denoise(RenderingDevice *p_rd, Ref<RDShaderFile> &p_compute_shader, const RID &p_compute_base_uniform_set, PushConstant &p_push_constant, RID p_source_light_tex, RID p_source_normal_tex, RID p_dest_light_tex, RID p_unocclude_tex, float p_denoiser_strength, int p_denoiser_range, const Size2i &p_atlas_size, int p_atlas_slices, bool p_bake_sh, BakeStepFunc p_step_function, void *p_bake_userdata) {974RID denoise_params_buffer = p_rd->uniform_buffer_create(sizeof(DenoiseParams));975DenoiseParams denoise_params;976denoise_params.spatial_bandwidth = 5.0f;977denoise_params.light_bandwidth = p_denoiser_strength;978denoise_params.albedo_bandwidth = 1.0f;979denoise_params.normal_bandwidth = 0.1f;980denoise_params.filter_strength = 10.0f;981denoise_params.half_search_window = p_denoiser_range;982p_rd->buffer_update(denoise_params_buffer, 0, sizeof(DenoiseParams), &denoise_params);983984Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(p_source_light_tex, p_dest_light_tex);985{986RD::Uniform u;987u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;988u.binding = 2;989u.append_id(p_source_normal_tex);990uniforms.push_back(u);991}992{993RD::Uniform u;994u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;995u.binding = 3;996u.append_id(p_unocclude_tex);997uniforms.push_back(u);998}999{1000RD::Uniform u;1001u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;1002u.binding = 4;1003u.append_id(denoise_params_buffer);1004uniforms.push_back(u);1005}10061007RID compute_shader_denoise = p_rd->shader_create_from_spirv(p_compute_shader->get_spirv_stages("denoise"));1008ERR_FAIL_COND_V(compute_shader_denoise.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);10091010RID compute_shader_denoise_pipeline = p_rd->compute_pipeline_create(compute_shader_denoise);1011RID denoise_uniform_set = p_rd->uniform_set_create(uniforms, compute_shader_denoise, 1);10121013// We denoise in fixed size regions and synchronize execution to avoid GPU timeouts.1014// We use a region with 1/4 the amount of pixels if we're denoising SH lightmaps, as1015// all four of them are denoised in the shader in one dispatch.1016const int user_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));1017const int max_region_size = p_bake_sh ? user_region_size / 2 : user_region_size;1018int x_regions = Math::division_round_up(p_atlas_size.width, max_region_size);1019int y_regions = Math::division_round_up(p_atlas_size.height, max_region_size);1020for (int s = 0; s < p_atlas_slices; s++) {1021p_push_constant.atlas_slice = s;10221023for (int i = 0; i < x_regions; i++) {1024for (int j = 0; j < y_regions; j++) {1025int x = i * max_region_size;1026int y = j * max_region_size;1027int w = MIN((i + 1) * max_region_size, p_atlas_size.width) - x;1028int h = MIN((j + 1) * max_region_size, p_atlas_size.height) - y;1029p_push_constant.region_ofs[0] = x;1030p_push_constant.region_ofs[1] = y;10311032RD::ComputeListID compute_list = p_rd->compute_list_begin();1033p_rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_denoise_pipeline);1034p_rd->compute_list_bind_uniform_set(compute_list, p_compute_base_uniform_set, 0);1035p_rd->compute_list_bind_uniform_set(compute_list, denoise_uniform_set, 1);1036p_rd->compute_list_set_push_constant(compute_list, &p_push_constant, sizeof(PushConstant));1037p_rd->compute_list_dispatch(compute_list, Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);1038p_rd->compute_list_end();10391040p_rd->submit();1041p_rd->sync();1042}1043}1044if (p_step_function) {1045int percent = (s + 1) * 100 / p_atlas_slices;1046float p = float(s) / p_atlas_slices * 0.1;1047if (p_step_function(0.8 + p, vformat(RTR("Denoising %d%%"), percent), p_bake_userdata, false)) {1048return BAKE_ERROR_USER_ABORTED;1049}1050}1051}10521053p_rd->free(compute_shader_denoise);1054p_rd->free(denoise_params_buffer);10551056return BAKE_OK;1057}10581059LightmapperRD::BakeError LightmapperRD::bake(BakeQuality p_quality, bool p_use_denoiser, float p_denoiser_strength, int p_denoiser_range, int p_bounces, float p_bounce_indirect_energy, float p_bias, int p_max_texture_size, bool p_bake_sh, bool p_bake_shadowmask, bool p_texture_for_bounces, GenerateProbes p_generate_probes, const Ref<Image> &p_environment_panorama, const Basis &p_environment_transform, BakeStepFunc p_step_function, void *p_bake_userdata, float p_exposure_normalization, float p_supersampling_factor) {1060int denoiser = GLOBAL_GET("rendering/lightmapping/denoising/denoiser");1061String oidn_path = EDITOR_GET("filesystem/tools/oidn/oidn_denoise_path");10621063if (p_use_denoiser && denoiser == 1) {1064// OIDN (external).1065Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);10661067if (da->dir_exists(oidn_path)) {1068if (OS::get_singleton()->get_name() == "Windows") {1069oidn_path = oidn_path.path_join("oidnDenoise.exe");1070} else {1071oidn_path = oidn_path.path_join("oidnDenoise");1072}1073}1074ERR_FAIL_COND_V_MSG(oidn_path.is_empty() || !da->file_exists(oidn_path), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, "OIDN denoiser is selected in the project settings, but no or invalid OIDN executable path is configured in the editor settings.");1075}10761077if (p_step_function) {1078p_step_function(0.0, RTR("Begin Bake"), p_bake_userdata, true);1079}1080lightmap_textures.clear();1081shadowmask_textures.clear();1082int grid_size = 128;10831084/* STEP 1: Fetch material textures and compute the bounds */10851086AABB bounds;1087Size2i atlas_size;1088int atlas_slices;1089Vector<Ref<Image>> albedo_images;1090Vector<Ref<Image>> emission_images;10911092BakeError bake_error = _blit_meshes_into_atlas(p_max_texture_size, p_denoiser_range, albedo_images, emission_images, bounds, atlas_size, atlas_slices, p_supersampling_factor, p_step_function, p_bake_userdata);1093if (bake_error != BAKE_OK) {1094return bake_error;1095}10961097// Find any directional light suitable for shadowmasking.1098if (p_bake_shadowmask) {1099bool found = false;1100for (int i = 0; i < lights.size(); i++) {1101if (lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL && !lights[i].static_bake) {1102found = true;1103break;1104}1105}11061107if (!found) {1108p_bake_shadowmask = false;1109WARN_PRINT("Shadowmask disabled: no directional light with their bake mode set to dynamic exists.");1110}1111}11121113#ifdef DEBUG_TEXTURES1114for (int i = 0; i < atlas_slices; i++) {1115albedo_images[i]->save_png("res://0_albedo_" + itos(i) + ".png");1116emission_images[i]->save_png("res://0_emission_" + itos(i) + ".png");1117}1118#endif11191120// Attempt to create a local device by requesting it from rendering server first.1121// If that fails because the current renderer is not implemented on top of RD, we fall back to creating1122// a local rendering device manually depending on the current platform.1123Error err;1124RenderingContextDriver *rcd = nullptr;1125RenderingDevice *rd = RenderingServer::get_singleton()->create_local_rendering_device();1126if (rd == nullptr) {1127#if defined(RD_ENABLED)1128#if defined(METAL_ENABLED)1129rcd = memnew(RenderingContextDriverMetal);1130rd = memnew(RenderingDevice);1131#endif1132#if defined(VULKAN_ENABLED)1133if (rcd == nullptr) {1134rcd = memnew(RenderingContextDriverVulkan);1135rd = memnew(RenderingDevice);1136}1137#endif1138#endif1139if (rcd != nullptr && rd != nullptr) {1140err = rcd->initialize();1141if (err == OK) {1142err = rd->initialize(rcd);1143}11441145if (err != OK) {1146memdelete(rd);1147memdelete(rcd);1148rd = nullptr;1149rcd = nullptr;1150}1151}1152}11531154ERR_FAIL_NULL_V(rd, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);11551156RID albedo_array_tex;1157RID emission_array_tex;1158RID normal_tex;1159RID position_tex;1160RID unocclude_tex;1161RID light_source_tex;1162RID light_dest_tex;1163RID light_accum_tex;1164RID light_accum_tex2;1165RID light_environment_tex;1166RID shadowmask_tex;1167RID shadowmask_tex2;11681169#define FREE_TEXTURES \1170rd->free(albedo_array_tex); \1171rd->free(emission_array_tex); \1172rd->free(normal_tex); \1173rd->free(position_tex); \1174rd->free(unocclude_tex); \1175rd->free(light_source_tex); \1176rd->free(light_accum_tex2); \1177rd->free(light_accum_tex); \1178rd->free(light_environment_tex); \1179if (p_bake_shadowmask) { \1180rd->free(shadowmask_tex); \1181rd->free(shadowmask_tex2); \1182}11831184{ // create all textures11851186Vector<Vector<uint8_t>> albedo_data;1187Vector<Vector<uint8_t>> emission_data;1188for (int i = 0; i < atlas_slices; i++) {1189albedo_data.push_back(albedo_images[i]->get_data());1190emission_data.push_back(emission_images[i]->get_data());1191}11921193RD::TextureFormat tf;1194tf.width = atlas_size.width;1195tf.height = atlas_size.height;1196tf.array_layers = atlas_slices;1197tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;1198tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;1199tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;12001201albedo_array_tex = rd->texture_create(tf, RD::TextureView(), albedo_data);12021203tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;12041205emission_array_tex = rd->texture_create(tf, RD::TextureView(), emission_data);12061207//this will be rastered to1208tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_STORAGE_BIT;1209normal_tex = rd->texture_create(tf, RD::TextureView());1210tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;1211position_tex = rd->texture_create(tf, RD::TextureView());1212unocclude_tex = rd->texture_create(tf, RD::TextureView());12131214tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_CAN_COPY_FROM_BIT | RD::TEXTURE_USAGE_CAN_COPY_TO_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;12151216// shadowmask1217if (p_bake_shadowmask) {1218tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;12191220shadowmask_tex = rd->texture_create(tf, RD::TextureView());1221rd->texture_clear(shadowmask_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);12221223shadowmask_tex2 = rd->texture_create(tf, RD::TextureView());1224rd->texture_clear(shadowmask_tex2, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);1225}12261227// lightmap1228tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;12291230light_source_tex = rd->texture_create(tf, RD::TextureView());1231rd->texture_clear(light_source_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);12321233if (p_bake_sh) {1234tf.array_layers *= 4;1235}1236light_accum_tex = rd->texture_create(tf, RD::TextureView());1237rd->texture_clear(light_accum_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);1238light_dest_tex = rd->texture_create(tf, RD::TextureView());1239rd->texture_clear(light_dest_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);1240light_accum_tex2 = light_dest_tex;12411242//env1243{1244Ref<Image> panorama_tex;1245if (p_environment_panorama.is_valid()) {1246panorama_tex = p_environment_panorama;1247panorama_tex->convert(Image::FORMAT_RGBAF);1248} else {1249panorama_tex.instantiate();1250panorama_tex->initialize_data(8, 8, false, Image::FORMAT_RGBAF);1251panorama_tex->fill(Color(0, 0, 0, 1));1252}12531254RD::TextureFormat tfp;1255tfp.width = panorama_tex->get_width();1256tfp.height = panorama_tex->get_height();1257tfp.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;1258tfp.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;12591260Vector<Vector<uint8_t>> tdata;1261tdata.push_back(panorama_tex->get_data());1262light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata);12631264#ifdef DEBUG_TEXTURES1265panorama_tex->save_exr("res://0_panorama.exr", false);1266#endif1267}1268}12691270/* STEP 2: create the acceleration structure for the GPU*/12711272Vector<int> slice_triangle_count;1273RID bake_parameters_buffer;1274RID vertex_buffer;1275RID triangle_buffer;1276RID lights_buffer;1277RID triangle_indices_buffer;1278RID cluster_indices_buffer;1279RID cluster_aabbs_buffer;1280RID grid_texture;1281RID seams_buffer;1282RID probe_positions_buffer;12831284Vector<int> slice_seam_count;12851286#define FREE_BUFFERS \1287rd->free(bake_parameters_buffer); \1288rd->free(vertex_buffer); \1289rd->free(triangle_buffer); \1290rd->free(lights_buffer); \1291rd->free(triangle_indices_buffer); \1292rd->free(cluster_indices_buffer); \1293rd->free(cluster_aabbs_buffer); \1294rd->free(grid_texture); \1295rd->free(seams_buffer); \1296rd->free(probe_positions_buffer);12971298const uint32_t cluster_size = 16;1299_create_acceleration_structures(rd, atlas_size, atlas_slices, bounds, grid_size, cluster_size, probe_positions, p_generate_probes, slice_triangle_count, slice_seam_count, vertex_buffer, triangle_buffer, lights_buffer, triangle_indices_buffer, cluster_indices_buffer, cluster_aabbs_buffer, probe_positions_buffer, grid_texture, seams_buffer, p_step_function, p_bake_userdata);13001301// The index of the directional light used for shadowmasking.1302int shadowmask_light_idx = -1;13031304// Find the directional light index in the sorted lights array.1305if (p_bake_shadowmask) {1306int shadowmask_lights_count = 0;13071308for (int i = 0; i < lights.size(); i++) {1309if (lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL && !lights[i].static_bake) {1310if (shadowmask_light_idx < 0) {1311shadowmask_light_idx = i;1312}1313shadowmask_lights_count += 1;1314}1315}13161317if (shadowmask_lights_count > 1) {1318WARN_PRINT(1319vformat("%d directional lights detected for shadowmask baking. Only %s will be used.",1320shadowmask_lights_count, light_metadata[shadowmask_light_idx].name));1321}1322}13231324// Create global bake parameters buffer.1325BakeParameters bake_parameters;1326bake_parameters.world_size[0] = bounds.size.x;1327bake_parameters.world_size[1] = bounds.size.y;1328bake_parameters.world_size[2] = bounds.size.z;1329bake_parameters.bias = p_bias;1330bake_parameters.to_cell_offset[0] = bounds.position.x;1331bake_parameters.to_cell_offset[1] = bounds.position.y;1332bake_parameters.to_cell_offset[2] = bounds.position.z;1333bake_parameters.grid_size = grid_size;1334bake_parameters.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);1335bake_parameters.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);1336bake_parameters.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);1337bake_parameters.light_count = lights.size();1338bake_parameters.env_transform[0] = p_environment_transform.rows[0][0];1339bake_parameters.env_transform[1] = p_environment_transform.rows[1][0];1340bake_parameters.env_transform[2] = p_environment_transform.rows[2][0];1341bake_parameters.env_transform[3] = 0.0f;1342bake_parameters.env_transform[4] = p_environment_transform.rows[0][1];1343bake_parameters.env_transform[5] = p_environment_transform.rows[1][1];1344bake_parameters.env_transform[6] = p_environment_transform.rows[2][1];1345bake_parameters.env_transform[7] = 0.0f;1346bake_parameters.env_transform[8] = p_environment_transform.rows[0][2];1347bake_parameters.env_transform[9] = p_environment_transform.rows[1][2];1348bake_parameters.env_transform[10] = p_environment_transform.rows[2][2];1349bake_parameters.env_transform[11] = 0.0f;1350bake_parameters.atlas_size[0] = atlas_size.width;1351bake_parameters.atlas_size[1] = atlas_size.height;1352bake_parameters.exposure_normalization = p_exposure_normalization;1353bake_parameters.bounces = p_bounces;1354bake_parameters.bounce_indirect_energy = p_bounce_indirect_energy;1355bake_parameters.shadowmask_light_idx = shadowmask_light_idx;1356// Same number of rays for transparency regardless of quality (it's more of a retry rather than shooting new ones).1357bake_parameters.transparency_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_transparency_rays");1358bake_parameters.supersampling_factor = p_supersampling_factor;13591360bake_parameters_buffer = rd->uniform_buffer_create(sizeof(BakeParameters));1361rd->buffer_update(bake_parameters_buffer, 0, sizeof(BakeParameters), &bake_parameters);13621363if (p_step_function) {1364if (p_step_function(0.47, RTR("Preparing shaders"), p_bake_userdata, true)) {1365FREE_TEXTURES1366FREE_BUFFERS1367memdelete(rd);1368if (rcd != nullptr) {1369memdelete(rcd);1370}1371return BAKE_ERROR_USER_ABORTED;1372}1373}13741375//shaders1376Ref<RDShaderFile> raster_shader;1377raster_shader.instantiate();1378err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl);1379if (err != OK) {1380raster_shader->print_errors("raster_shader");13811382FREE_TEXTURES1383FREE_BUFFERS13841385memdelete(rd);13861387if (rcd != nullptr) {1388memdelete(rcd);1389}1390}1391ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);13921393RID rasterize_shader = rd->shader_create_from_spirv(raster_shader->get_spirv_stages());13941395ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen13961397RID sampler;1398{1399RD::SamplerState s;1400s.mag_filter = RD::SAMPLER_FILTER_LINEAR;1401s.min_filter = RD::SAMPLER_FILTER_LINEAR;1402s.max_lod = 0;14031404sampler = rd->sampler_create(s);1405}14061407Vector<RD::Uniform> base_uniforms;1408{1409{1410RD::Uniform u;1411u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;1412u.binding = 0;1413u.append_id(bake_parameters_buffer);1414base_uniforms.push_back(u);1415}1416{1417RD::Uniform u;1418u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1419u.binding = 1;1420u.append_id(vertex_buffer);1421base_uniforms.push_back(u);1422}1423{1424RD::Uniform u;1425u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1426u.binding = 2;1427u.append_id(triangle_buffer);1428base_uniforms.push_back(u);1429}1430{1431RD::Uniform u;1432u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1433u.binding = 3;1434u.append_id(triangle_indices_buffer);1435base_uniforms.push_back(u);1436}1437{1438RD::Uniform u;1439u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1440u.binding = 4;1441u.append_id(lights_buffer);1442base_uniforms.push_back(u);1443}1444{1445RD::Uniform u;1446u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1447u.binding = 5;1448u.append_id(seams_buffer);1449base_uniforms.push_back(u);1450}1451{1452RD::Uniform u;1453u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1454u.binding = 6;1455u.append_id(probe_positions_buffer);1456base_uniforms.push_back(u);1457}1458{1459RD::Uniform u;1460u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1461u.binding = 7;1462u.append_id(grid_texture);1463base_uniforms.push_back(u);1464}1465{1466RD::Uniform u;1467u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1468u.binding = 8;1469u.append_id(albedo_array_tex);1470base_uniforms.push_back(u);1471}1472{1473RD::Uniform u;1474u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1475u.binding = 9;1476u.append_id(emission_array_tex);1477base_uniforms.push_back(u);1478}1479{1480RD::Uniform u;1481u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;1482u.binding = 10;1483u.append_id(sampler);1484base_uniforms.push_back(u);1485}1486{1487RD::Uniform u;1488u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1489u.binding = 11;1490u.append_id(cluster_indices_buffer);1491base_uniforms.push_back(u);1492}1493{1494RD::Uniform u;1495u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1496u.binding = 12;1497u.append_id(cluster_aabbs_buffer);1498base_uniforms.push_back(u);1499}1500}15011502RID raster_base_uniform = rd->uniform_set_create(base_uniforms, rasterize_shader, 0);1503RID raster_depth_buffer;1504{1505RD::TextureFormat tf;1506tf.width = atlas_size.width;1507tf.height = atlas_size.height;1508tf.depth = 1;1509tf.texture_type = RD::TEXTURE_TYPE_2D;1510tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;1511tf.format = RD::DATA_FORMAT_D32_SFLOAT;1512tf.is_discardable = true;15131514raster_depth_buffer = rd->texture_create(tf, RD::TextureView());1515}15161517rd->submit();1518rd->sync();15191520/* STEP 3: Raster the geometry to UV2 coords in the atlas textures GPU*/15211522_raster_geometry(rd, atlas_size, atlas_slices, grid_size, bounds, p_bias, slice_triangle_count, position_tex, unocclude_tex, normal_tex, raster_depth_buffer, rasterize_shader, raster_base_uniform);15231524#ifdef DEBUG_TEXTURES15251526for (int i = 0; i < atlas_slices; i++) {1527Vector<uint8_t> s = rd->texture_get_data(position_tex, i);1528Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);1529img->save_exr("res://1_position_" + itos(i) + ".exr", false);15301531s = rd->texture_get_data(normal_tex, i);1532img->set_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);1533img->save_exr("res://1_normal_" + itos(i) + ".exr", false);1534}1535#endif15361537#define FREE_RASTER_RESOURCES \1538rd->free(rasterize_shader); \1539rd->free(sampler); \1540rd->free(raster_depth_buffer);15411542/* Plot direct light */15431544Ref<RDShaderFile> compute_shader;1545String defines = "";1546defines += "\n#define CLUSTER_SIZE " + uitos(cluster_size) + "\n";15471548if (p_bake_sh) {1549defines += "\n#define USE_SH_LIGHTMAPS\n";1550}15511552if (p_texture_for_bounces) {1553defines += "\n#define USE_LIGHT_TEXTURE_FOR_BOUNCES\n";1554}15551556if (p_bake_shadowmask) {1557defines += "\n#define USE_SHADOWMASK\n";1558}15591560compute_shader.instantiate();1561err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, defines);1562if (err != OK) {1563FREE_TEXTURES1564FREE_BUFFERS1565FREE_RASTER_RESOURCES1566memdelete(rd);15671568if (rcd != nullptr) {1569memdelete(rcd);1570}15711572compute_shader->print_errors("compute_shader");1573}1574ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);15751576// Unoccluder1577RID compute_shader_unocclude = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("unocclude"));1578ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen1579RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude);15801581// Direct light1582RID compute_shader_primary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("primary"));1583ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen1584RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary);15851586// Indirect light1587RID compute_shader_secondary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("secondary"));1588ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen1589RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary);15901591// Light probes1592RID compute_shader_light_probes = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("light_probes"));1593ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen1594RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes);15951596RID compute_base_uniform_set = rd->uniform_set_create(base_uniforms, compute_shader_primary, 0);15971598#define FREE_COMPUTE_RESOURCES \1599rd->free(compute_shader_unocclude); \1600rd->free(compute_shader_primary); \1601rd->free(compute_shader_secondary); \1602rd->free(compute_shader_light_probes);16031604Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1);1605rd->submit();1606rd->sync();16071608if (p_step_function) {1609if (p_step_function(0.49, RTR("Un-occluding geometry"), p_bake_userdata, true)) {1610FREE_TEXTURES1611FREE_BUFFERS1612FREE_RASTER_RESOURCES1613FREE_COMPUTE_RESOURCES1614memdelete(rd);1615if (rcd != nullptr) {1616memdelete(rcd);1617}1618return BAKE_ERROR_USER_ABORTED;1619}1620}16211622PushConstant push_constant;1623push_constant.denoiser_range = p_use_denoiser ? p_denoiser_range : 1.0;16241625/* UNOCCLUDE */1626{1627Vector<RD::Uniform> uniforms;1628{1629{1630RD::Uniform u;1631u.uniform_type = RD::UNIFORM_TYPE_IMAGE;1632u.binding = 0;1633u.append_id(position_tex);1634uniforms.push_back(u);1635}1636{1637RD::Uniform u;1638u.uniform_type = RD::UNIFORM_TYPE_IMAGE;1639u.binding = 1;1640u.append_id(unocclude_tex);1641uniforms.push_back(u);1642}1643}16441645RID unocclude_uniform_set = rd->uniform_set_create(uniforms, compute_shader_unocclude, 1);16461647RD::ComputeListID compute_list = rd->compute_list_begin();1648rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_unocclude_pipeline);1649rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);1650rd->compute_list_bind_uniform_set(compute_list, unocclude_uniform_set, 1);16511652for (int i = 0; i < atlas_slices; i++) {1653push_constant.atlas_slice = i;1654rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));1655rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);1656//no barrier, let them run all together1657}1658rd->compute_list_end(); //done1659}16601661#ifdef DEBUG_TEXTURES1662for (int i = 0; i < atlas_slices; i++) {1663Vector<uint8_t> s = rd->texture_get_data(unocclude_tex, i);1664Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);1665img->save_exr("res://1_unocclude_" + itos(i) + ".exr", false);1666}1667#endif16681669if (p_step_function) {1670if (p_step_function(0.5, RTR("Plot direct lighting"), p_bake_userdata, true)) {1671FREE_TEXTURES1672FREE_BUFFERS1673FREE_RASTER_RESOURCES1674FREE_COMPUTE_RESOURCES1675memdelete(rd);1676if (rcd != nullptr) {1677memdelete(rcd);1678}1679return BAKE_ERROR_USER_ABORTED;1680}1681}16821683const int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));1684const int x_regions = Math::division_round_up(atlas_size.width, max_region_size);1685const int y_regions = Math::division_round_up(atlas_size.height, max_region_size);16861687// Set ray count to the quality used for direct light and bounces.1688switch (p_quality) {1689case BAKE_QUALITY_LOW: {1690push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_ray_count");1691} break;1692case BAKE_QUALITY_MEDIUM: {1693push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_ray_count");1694} break;1695case BAKE_QUALITY_HIGH: {1696push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_ray_count");1697} break;1698case BAKE_QUALITY_ULTRA: {1699push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_ray_count");1700} break;1701}17021703push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);17041705/* PRIMARY (direct) LIGHT PASS */1706{1707Vector<RD::Uniform> uniforms;1708{1709{1710RD::Uniform u;1711u.uniform_type = RD::UNIFORM_TYPE_IMAGE;1712u.binding = 0;1713u.append_id(light_source_tex);1714uniforms.push_back(u);1715}1716{1717RD::Uniform u;1718u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1719u.binding = 1;1720u.append_id(light_dest_tex); //will be unused1721uniforms.push_back(u);1722}1723{1724RD::Uniform u;1725u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1726u.binding = 2;1727u.append_id(position_tex);1728uniforms.push_back(u);1729}1730{1731RD::Uniform u;1732u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1733u.binding = 3;1734u.append_id(normal_tex);1735uniforms.push_back(u);1736}1737{1738RD::Uniform u;1739u.uniform_type = RD::UNIFORM_TYPE_IMAGE;1740u.binding = 4;1741u.append_id(light_accum_tex);1742uniforms.push_back(u);1743}17441745if (p_bake_shadowmask) {1746RD::Uniform u;1747u.uniform_type = RD::UNIFORM_TYPE_IMAGE;1748u.binding = 5;1749u.append_id(shadowmask_tex);1750uniforms.push_back(u);1751}1752}17531754RID light_uniform_set = rd->uniform_set_create(uniforms, compute_shader_primary, 1);17551756int count = 0;1757for (int s = 0; s < atlas_slices; s++) {1758push_constant.atlas_slice = s;17591760for (int i = 0; i < x_regions; i++) {1761for (int j = 0; j < y_regions; j++) {1762int x = i * max_region_size;1763int y = j * max_region_size;1764int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;1765int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;17661767push_constant.region_ofs[0] = x;1768push_constant.region_ofs[1] = y;17691770group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);1771RD::ComputeListID compute_list = rd->compute_list_begin();1772rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_primary_pipeline);1773rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);1774rd->compute_list_bind_uniform_set(compute_list, light_uniform_set, 1);1775rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));1776rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);1777rd->compute_list_end();17781779rd->submit();1780rd->sync();17811782count++;1783if (p_step_function) {1784int total = (atlas_slices * x_regions * y_regions);1785int percent = count * 100 / total;1786float p = float(count) / total * 0.1;1787if (p_step_function(0.5 + p, vformat(RTR("Plot direct lighting %d%%"), percent), p_bake_userdata, false)) {1788FREE_TEXTURES1789FREE_BUFFERS1790FREE_RASTER_RESOURCES1791FREE_COMPUTE_RESOURCES1792memdelete(rd);1793if (rcd != nullptr) {1794memdelete(rcd);1795}1796return BAKE_ERROR_USER_ABORTED;1797}1798}1799}1800}1801}1802}18031804#ifdef DEBUG_TEXTURES18051806for (int i = 0; i < atlas_slices; i++) {1807Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);1808Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);1809img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false);1810}18111812if (p_bake_sh) {1813for (int i = 0; i < atlas_slices * 4; i++) {1814Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);1815Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);1816img->save_exr("res://2_light_primary_accum_" + itos(i) + ".exr", false);1817}1818}1819#endif18201821/* SECONDARY (indirect) LIGHT PASS(ES) */18221823if (p_bounces > 0) {1824Vector<RD::Uniform> uniforms;1825{1826{1827// Unused.1828RD::Uniform u;1829u.uniform_type = RD::UNIFORM_TYPE_IMAGE;1830u.binding = 0;1831u.append_id(light_dest_tex);1832uniforms.push_back(u);1833}1834{1835RD::Uniform u;1836u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1837u.binding = 1;1838u.append_id(light_source_tex);1839uniforms.push_back(u);1840}1841{1842RD::Uniform u;1843u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1844u.binding = 2;1845u.append_id(position_tex);1846uniforms.push_back(u);1847}1848{1849RD::Uniform u;1850u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1851u.binding = 3;1852u.append_id(normal_tex);1853uniforms.push_back(u);1854}1855{1856RD::Uniform u;1857u.uniform_type = RD::UNIFORM_TYPE_IMAGE;1858u.binding = 4;1859u.append_id(light_accum_tex);1860uniforms.push_back(u);1861}1862{1863RD::Uniform u;1864u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1865u.binding = 5;1866u.append_id(light_environment_tex);1867uniforms.push_back(u);1868}1869}18701871RID secondary_uniform_set;1872secondary_uniform_set = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);18731874const int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass");1875int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);18761877if (p_step_function) {1878if (p_step_function(0.6, RTR("Integrate indirect lighting"), p_bake_userdata, true)) {1879FREE_TEXTURES1880FREE_BUFFERS1881FREE_RASTER_RESOURCES1882FREE_COMPUTE_RESOURCES1883memdelete(rd);1884if (rcd != nullptr) {1885memdelete(rcd);1886}1887return BAKE_ERROR_USER_ABORTED;1888}1889}18901891int count = 0;1892for (int s = 0; s < atlas_slices; s++) {1893push_constant.atlas_slice = s;18941895for (int i = 0; i < x_regions; i++) {1896for (int j = 0; j < y_regions; j++) {1897int x = i * max_region_size;1898int y = j * max_region_size;1899int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;1900int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;19011902push_constant.region_ofs[0] = x;1903push_constant.region_ofs[1] = y;19041905group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);19061907for (int k = 0; k < ray_iterations; k++) {1908RD::ComputeListID compute_list = rd->compute_list_begin();1909rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline);1910rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);1911rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set, 1);19121913push_constant.ray_from = k * max_rays;1914push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count));1915rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));1916rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);19171918rd->compute_list_end();1919rd->submit();1920rd->sync();19211922count++;1923if (p_step_function) {1924int total = (atlas_slices * x_regions * y_regions * ray_iterations);1925int percent = count * 100 / total;1926float p = float(count) / total * 0.1;1927if (p_step_function(0.6 + p, vformat(RTR("Integrate indirect lighting %d%%"), percent), p_bake_userdata, false)) {1928FREE_TEXTURES1929FREE_BUFFERS1930FREE_RASTER_RESOURCES1931FREE_COMPUTE_RESOURCES1932memdelete(rd);1933if (rcd != nullptr) {1934memdelete(rcd);1935}1936return BAKE_ERROR_USER_ABORTED;1937}1938}1939}1940}1941}1942}1943}19441945/* LIGHTPROBES */19461947RID light_probe_buffer;19481949if (probe_positions.size()) {1950light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size());19511952if (p_step_function) {1953if (p_step_function(0.7, RTR("Baking light probes"), p_bake_userdata, true)) {1954FREE_TEXTURES1955FREE_BUFFERS1956FREE_RASTER_RESOURCES1957FREE_COMPUTE_RESOURCES1958if (probe_positions.size() > 0) {1959rd->free(light_probe_buffer);1960}1961memdelete(rd);1962if (rcd != nullptr) {1963memdelete(rcd);1964}1965return BAKE_ERROR_USER_ABORTED;1966}1967}19681969Vector<RD::Uniform> uniforms;1970{1971{1972RD::Uniform u;1973u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;1974u.binding = 0;1975u.append_id(light_probe_buffer);1976uniforms.push_back(u);1977}1978{1979RD::Uniform u;1980u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1981u.binding = 1;1982u.append_id(light_source_tex);1983uniforms.push_back(u);1984}1985{1986RD::Uniform u;1987u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;1988u.binding = 2;1989u.append_id(light_environment_tex);1990uniforms.push_back(u);1991}1992}1993RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1);19941995switch (p_quality) {1996case BAKE_QUALITY_LOW: {1997push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_probe_ray_count");1998} break;1999case BAKE_QUALITY_MEDIUM: {2000push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_probe_ray_count");2001} break;2002case BAKE_QUALITY_HIGH: {2003push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_probe_ray_count");2004} break;2005case BAKE_QUALITY_ULTRA: {2006push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count");2007} break;2008}20092010push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);2011push_constant.probe_count = probe_positions.size();20122013int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass");2014int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);20152016for (int i = 0; i < ray_iterations; i++) {2017RD::ComputeListID compute_list = rd->compute_list_begin();2018rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline);2019rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);2020rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1);20212022push_constant.ray_from = i * max_rays;2023push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count));2024rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));2025rd->compute_list_dispatch(compute_list, Math::division_round_up((int)probe_positions.size(), 64), 1, 1);20262027rd->compute_list_end(); //done2028rd->submit();2029rd->sync();20302031if (p_step_function) {2032int percent = i * 100 / ray_iterations;2033float p = float(i) / ray_iterations * 0.1;2034if (p_step_function(0.7 + p, vformat(RTR("Integrating light probes %d%%"), percent), p_bake_userdata, false)) {2035FREE_TEXTURES2036FREE_BUFFERS2037FREE_RASTER_RESOURCES2038FREE_COMPUTE_RESOURCES2039if (probe_positions.size() > 0) {2040rd->free(light_probe_buffer);2041}2042memdelete(rd);2043if (rcd != nullptr) {2044memdelete(rcd);2045}2046return BAKE_ERROR_USER_ABORTED;2047}2048}2049}2050}20512052#if 02053for (int i = 0; i < probe_positions.size(); i++) {2054Ref<Image> img = Image::create_empty(6, 4, false, Image::FORMAT_RGB8);2055for (int j = 0; j < 6; j++) {2056Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);2057Ref<Image> img2 = Image::create_from_data(2, 2, false, Image::FORMAT_RGBAF, s);2058img2->convert(Image::FORMAT_RGB8);2059img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2));2060}2061img->save_png("res://3_light_probe_" + itos(i) + ".png");2062}2063#endif20642065/* DENOISE */20662067if (p_use_denoiser) {2068if (p_step_function) {2069if (p_step_function(0.8, RTR("Denoising"), p_bake_userdata, true)) {2070FREE_TEXTURES2071FREE_BUFFERS2072FREE_RASTER_RESOURCES2073FREE_COMPUTE_RESOURCES2074if (probe_positions.size() > 0) {2075rd->free(light_probe_buffer);2076}2077memdelete(rd);2078if (rcd != nullptr) {2079memdelete(rcd);2080}2081return BAKE_ERROR_USER_ABORTED;2082}2083}20842085{2086BakeError error;2087if (denoiser == 1) {2088// OIDN (external).2089error = _denoise_oidn(rd, light_accum_tex, normal_tex, light_accum_tex, atlas_size, atlas_slices, p_bake_sh, false, oidn_path);2090} else {2091// JNLM (built-in).2092SWAP(light_accum_tex, light_accum_tex2);2093error = _denoise(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, normal_tex, light_accum_tex, unocclude_tex, p_denoiser_strength, p_denoiser_range, atlas_size, atlas_slices, p_bake_sh, p_step_function, p_bake_userdata);2094}2095if (unlikely(error != BAKE_OK)) {2096return error;2097}2098}20992100if (p_bake_shadowmask) {2101BakeError error;2102if (denoiser == 1) {2103// OIDN (external).2104error = _denoise_oidn(rd, shadowmask_tex, normal_tex, shadowmask_tex, atlas_size, atlas_slices, false, true, oidn_path);2105} else {2106// JNLM (built-in).2107SWAP(shadowmask_tex, shadowmask_tex2);2108error = _denoise(rd, compute_shader, compute_base_uniform_set, push_constant, shadowmask_tex2, normal_tex, shadowmask_tex, unocclude_tex, p_denoiser_strength, p_denoiser_range, atlas_size, atlas_slices, false, p_step_function, p_bake_userdata);2109}2110if (unlikely(error != BAKE_OK)) {2111return error;2112}2113}2114}21152116/* DILATE */21172118{2119SWAP(light_accum_tex, light_accum_tex2);2120BakeError error = _dilate(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, light_accum_tex, atlas_size, atlas_slices * (p_bake_sh ? 4 : 1));2121if (unlikely(error != BAKE_OK)) {2122return error;2123}21242125if (p_bake_shadowmask) {2126SWAP(shadowmask_tex, shadowmask_tex2);2127error = _dilate(rd, compute_shader, compute_base_uniform_set, push_constant, shadowmask_tex2, shadowmask_tex, atlas_size, atlas_slices);2128if (unlikely(error != BAKE_OK)) {2129return error;2130}2131}2132}21332134#ifdef DEBUG_TEXTURES21352136for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {2137Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);2138Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);2139img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false);2140}2141#endif21422143/* BLEND SEAMS */2144//shaders2145Ref<RDShaderFile> blendseams_shader;2146blendseams_shader.instantiate();2147err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl);2148if (err != OK) {2149FREE_TEXTURES2150FREE_BUFFERS2151FREE_RASTER_RESOURCES2152FREE_COMPUTE_RESOURCES2153memdelete(rd);21542155if (rcd != nullptr) {2156memdelete(rcd);2157}21582159blendseams_shader->print_errors("blendseams_shader");2160}2161ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);21622163RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines"));21642165ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);21662167RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles"));21682169ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);21702171#define FREE_BLENDSEAMS_RESOURCES \2172rd->free(blendseams_line_raster_shader); \2173rd->free(blendseams_triangle_raster_shader);21742175{2176//pre copy2177for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {2178rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i);2179}21802181Vector<RID> framebuffers;2182for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {2183RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0);2184Vector<RID> fb;2185fb.push_back(slice_tex);2186fb.push_back(raster_depth_buffer);2187framebuffers.push_back(rd->framebuffer_create(fb));2188}21892190Vector<RD::Uniform> uniforms;2191{2192{2193RD::Uniform u;2194u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;2195u.binding = 0;2196u.append_id(light_accum_tex2);2197uniforms.push_back(u);2198}2199}22002201RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1);22022203bool debug = false;2204RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1);2205bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;2206bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;22072208RD::PipelineDepthStencilState ds;2209ds.enable_depth_test = true;2210ds.enable_depth_write = true;2211ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending22122213RID blendseams_line_raster_pipeline = rd->render_pipeline_create(blendseams_line_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_LINES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0);2214RID blendseams_triangle_raster_pipeline = rd->render_pipeline_create(blendseams_triangle_raster_shader, rd->framebuffer_get_format(framebuffers[0]), RD::INVALID_FORMAT_ID, RD::RENDER_PRIMITIVE_TRIANGLES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), ds, bs, 0);22152216uint32_t seam_offset = 0;2217uint32_t triangle_offset = 0;22182219for (int i = 0; i < atlas_slices; i++) {2220int subslices = (p_bake_sh ? 4 : 1);22212222if (slice_seam_count[i] == 0) {2223continue;2224}22252226for (int k = 0; k < subslices; k++) {2227RasterSeamsPushConstant seams_push_constant;2228seams_push_constant.slice = uint32_t(i * subslices + k);2229seams_push_constant.debug = debug;22302231// Store the current subslice in the breadcrumb.2232RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i * subslices + k], RD::DRAW_CLEAR_DEPTH, Vector<Color>(), 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::LIGHTMAPPER_PASS | seams_push_constant.slice);22332234rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);2235rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1);22362237const int uv_offset_count = 9;2238static const Vector3 uv_offsets[uv_offset_count] = {2239Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards2240Vector3(0, 1, 0.2),2241Vector3(0, -1, 0.2),2242Vector3(1, 0, 0.2),2243Vector3(-1, 0, 0.2),2244Vector3(-1, -1, 0.1),2245Vector3(1, -1, 0.1),2246Vector3(1, 1, 0.1),2247Vector3(-1, 1, 0.1),2248};22492250/* step 1 use lines to blend the edges */2251{2252seams_push_constant.base_index = seam_offset;2253rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);2254seams_push_constant.uv_offset[0] = (uv_offsets[0].x - 0.5f) / float(atlas_size.width);2255seams_push_constant.uv_offset[1] = (uv_offsets[0].y - 0.5f) / float(atlas_size.height);2256seams_push_constant.blend = uv_offsets[0].z;22572258rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));2259rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);2260}22612262/* step 2 use triangles to mask the interior */22632264{2265seams_push_constant.base_index = triangle_offset;2266rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline);2267seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask22682269rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));2270rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);2271}2272/* step 3 blend around the triangle */22732274rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);22752276for (int j = 1; j < uv_offset_count; j++) {2277seams_push_constant.base_index = seam_offset;2278seams_push_constant.uv_offset[0] = (uv_offsets[j].x - 0.5f) / float(atlas_size.width);2279seams_push_constant.uv_offset[1] = (uv_offsets[j].y - 0.5f) / float(atlas_size.height);2280seams_push_constant.blend = uv_offsets[0].z;22812282rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));2283rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);2284}2285rd->draw_list_end();2286}2287seam_offset += slice_seam_count[i];2288triangle_offset += slice_triangle_count[i];2289}2290}22912292if (p_bake_sh) {2293SWAP(light_accum_tex, light_accum_tex2);2294BakeError error = _pack_l1(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, light_accum_tex, atlas_size, atlas_slices);2295if (unlikely(error != BAKE_OK)) {2296return error;2297}2298}22992300#ifdef DEBUG_TEXTURES23012302for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {2303Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);2304Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);2305img->save_exr("res://5_blendseams" + itos(i) + ".exr", false);2306}2307#endif23082309if (p_step_function) {2310p_step_function(0.9, RTR("Retrieving textures"), p_bake_userdata, true);2311}23122313for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {2314Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);2315Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);2316img->convert(Image::FORMAT_RGBH); //remove alpha2317lightmap_textures.push_back(img);2318}23192320if (p_bake_shadowmask) {2321for (int i = 0; i < atlas_slices; i++) {2322Vector<uint8_t> s = rd->texture_get_data(shadowmask_tex, i);2323Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8, s);2324img->convert(Image::FORMAT_R8);2325shadowmask_textures.push_back(img);2326}2327}23282329if (probe_positions.size() > 0) {2330probe_values.resize(probe_positions.size() * 9);2331Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer);2332memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size());2333rd->free(light_probe_buffer);23342335#ifdef DEBUG_TEXTURES2336{2337Ref<Image> img2 = Image::create_from_data(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);2338img2->save_exr("res://6_lightprobes.exr", false);2339}2340#endif2341}23422343FREE_TEXTURES2344FREE_BUFFERS2345FREE_RASTER_RESOURCES2346FREE_COMPUTE_RESOURCES2347FREE_BLENDSEAMS_RESOURCES23482349memdelete(rd);23502351if (rcd != nullptr) {2352memdelete(rcd);2353}23542355return BAKE_OK;2356}23572358int LightmapperRD::get_bake_texture_count() const {2359return lightmap_textures.size();2360}23612362Ref<Image> LightmapperRD::get_bake_texture(int p_index) const {2363ERR_FAIL_INDEX_V(p_index, lightmap_textures.size(), Ref<Image>());2364return lightmap_textures[p_index];2365}23662367int LightmapperRD::get_shadowmask_texture_count() const {2368return shadowmask_textures.size();2369}23702371Ref<Image> LightmapperRD::get_shadowmask_texture(int p_index) const {2372ERR_FAIL_INDEX_V(p_index, shadowmask_textures.size(), Ref<Image>());2373return shadowmask_textures[p_index];2374}23752376int LightmapperRD::get_bake_mesh_count() const {2377return mesh_instances.size();2378}23792380Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const {2381ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());2382return mesh_instances[p_index].data.userdata;2383}23842385Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const {2386ERR_FAIL_COND_V(lightmap_textures.is_empty(), Rect2());2387Rect2 uv_ofs;2388Vector2 atlas_size = Vector2(lightmap_textures[0]->get_width(), lightmap_textures[0]->get_height());2389uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;2390uv_ofs.size = Vector2(mesh_instances[p_index].data.albedo_on_uv2->get_width(), mesh_instances[p_index].data.albedo_on_uv2->get_height()) / atlas_size;2391return uv_ofs;2392}23932394int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const {2395ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());2396return mesh_instances[p_index].slice;2397}23982399int LightmapperRD::get_bake_probe_count() const {2400return probe_positions.size();2401}24022403Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const {2404ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant());2405return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]);2406}24072408Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const {2409ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>());2410Vector<Color> ret;2411ret.resize(9);2412memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9);2413return ret;2414}24152416LightmapperRD::LightmapperRD() {2417}241824192420