Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/lightmapper_rd/lightmapper_rd.cpp
10277 views
1
/**************************************************************************/
2
/* lightmapper_rd.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "lightmapper_rd.h"
32
33
#include "core/string/print_string.h"
34
#include "lm_blendseams.glsl.gen.h"
35
#include "lm_compute.glsl.gen.h"
36
#include "lm_raster.glsl.gen.h"
37
38
#include "core/config/project_settings.h"
39
#include "core/io/dir_access.h"
40
#include "core/math/geometry_2d.h"
41
#include "editor/file_system/editor_paths.h"
42
#include "editor/settings/editor_settings.h"
43
#include "servers/rendering/rendering_device_binds.h"
44
#include "servers/rendering/rendering_server_globals.h"
45
46
#if defined(VULKAN_ENABLED)
47
#include "drivers/vulkan/rendering_context_driver_vulkan.h"
48
#endif
49
#if defined(METAL_ENABLED)
50
#include "drivers/metal/rendering_context_driver_metal.h"
51
#endif
52
53
//uncomment this if you want to see textures from all the process saved
54
//#define DEBUG_TEXTURES
55
56
void LightmapperRD::add_mesh(const MeshData &p_mesh) {
57
ERR_FAIL_COND(p_mesh.albedo_on_uv2.is_null() || p_mesh.albedo_on_uv2->is_empty());
58
ERR_FAIL_COND(p_mesh.emission_on_uv2.is_null() || p_mesh.emission_on_uv2->is_empty());
59
ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_width() != p_mesh.emission_on_uv2->get_width());
60
ERR_FAIL_COND(p_mesh.albedo_on_uv2->get_height() != p_mesh.emission_on_uv2->get_height());
61
ERR_FAIL_COND(p_mesh.points.is_empty());
62
MeshInstance mi;
63
mi.data = p_mesh;
64
mesh_instances.push_back(mi);
65
}
66
67
void 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) {
68
Light l;
69
l.type = LIGHT_TYPE_DIRECTIONAL;
70
l.direction[0] = p_direction.x;
71
l.direction[1] = p_direction.y;
72
l.direction[2] = p_direction.z;
73
l.color[0] = p_color.r;
74
l.color[1] = p_color.g;
75
l.color[2] = p_color.b;
76
l.energy = p_energy;
77
l.indirect_energy = p_indirect_energy;
78
l.static_bake = p_static;
79
l.size = Math::tan(Math::deg_to_rad(p_angular_distance));
80
l.shadow_blur = p_shadow_blur;
81
lights.push_back(l);
82
83
LightMetadata md;
84
md.name = p_name;
85
md.type = LIGHT_TYPE_DIRECTIONAL;
86
light_metadata.push_back(md);
87
}
88
89
void 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) {
90
Light l;
91
l.type = LIGHT_TYPE_OMNI;
92
l.position[0] = p_position.x;
93
l.position[1] = p_position.y;
94
l.position[2] = p_position.z;
95
l.range = p_range;
96
l.attenuation = p_attenuation;
97
l.color[0] = p_color.r;
98
l.color[1] = p_color.g;
99
l.color[2] = p_color.b;
100
l.energy = p_energy;
101
l.indirect_energy = p_indirect_energy;
102
l.static_bake = p_static;
103
l.size = p_size;
104
l.shadow_blur = p_shadow_blur;
105
lights.push_back(l);
106
107
LightMetadata md;
108
md.name = p_name;
109
md.type = LIGHT_TYPE_OMNI;
110
light_metadata.push_back(md);
111
}
112
113
void 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) {
114
Light l;
115
l.type = LIGHT_TYPE_SPOT;
116
l.position[0] = p_position.x;
117
l.position[1] = p_position.y;
118
l.position[2] = p_position.z;
119
l.direction[0] = p_direction.x;
120
l.direction[1] = p_direction.y;
121
l.direction[2] = p_direction.z;
122
l.range = p_range;
123
l.attenuation = p_attenuation;
124
l.cos_spot_angle = Math::cos(Math::deg_to_rad(p_spot_angle));
125
l.inv_spot_attenuation = 1.0f / p_spot_attenuation;
126
l.color[0] = p_color.r;
127
l.color[1] = p_color.g;
128
l.color[2] = p_color.b;
129
l.energy = p_energy;
130
l.indirect_energy = p_indirect_energy;
131
l.static_bake = p_static;
132
l.size = p_size;
133
l.shadow_blur = p_shadow_blur;
134
lights.push_back(l);
135
136
LightMetadata md;
137
md.name = p_name;
138
md.type = LIGHT_TYPE_SPOT;
139
light_metadata.push_back(md);
140
}
141
142
void LightmapperRD::add_probe(const Vector3 &p_position) {
143
Probe probe;
144
probe.position[0] = p_position.x;
145
probe.position[1] = p_position.y;
146
probe.position[2] = p_position.z;
147
probe.position[3] = 0;
148
probe_positions.push_back(probe);
149
}
150
151
void 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) {
152
int half_size = p_size / 2;
153
154
for (int i = 0; i < 8; i++) {
155
AABB aabb = p_bounds;
156
aabb.size *= 0.5;
157
Vector3i n = p_ofs;
158
159
if (i & 1) {
160
aabb.position.x += aabb.size.x;
161
n.x += half_size;
162
}
163
if (i & 2) {
164
aabb.position.y += aabb.size.y;
165
n.y += half_size;
166
}
167
if (i & 4) {
168
aabb.position.z += aabb.size.z;
169
n.z += half_size;
170
}
171
172
{
173
Vector3 qsize = aabb.size * 0.5; //quarter size, for fast aabb test
174
175
if (!Geometry3D::triangle_box_overlap(aabb.position + qsize, qsize, p_points)) {
176
//does not fit in child, go on
177
continue;
178
}
179
}
180
181
if (half_size == 1) {
182
//got to the end
183
TriangleSort ts;
184
ts.cell_index = n.x + (n.y * p_grid_size) + (n.z * p_grid_size * p_grid_size);
185
ts.triangle_index = p_triangle_index;
186
ts.triangle_aabb.position = p_points[0];
187
ts.triangle_aabb.size = Vector3();
188
ts.triangle_aabb.expand_to(p_points[1]);
189
ts.triangle_aabb.expand_to(p_points[2]);
190
p_triangles_sort.push_back(ts);
191
} else {
192
_plot_triangle_into_triangle_index_list(half_size, n, aabb, p_points, p_triangle_index, p_triangles_sort, p_grid_size);
193
}
194
}
195
}
196
197
void 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) {
198
if (p_count == 0) {
199
return;
200
}
201
202
// Compute AABB for all triangles in the range.
203
SortArray<TriangleSort, TriangleSortAxis<0>> triangle_sorter_x;
204
SortArray<TriangleSort, TriangleSortAxis<1>> triangle_sorter_y;
205
SortArray<TriangleSort, TriangleSortAxis<2>> triangle_sorter_z;
206
AABB cluster_aabb = p_triangle_sort[p_index_start].triangle_aabb;
207
for (uint32_t i = 1; i < p_count; i++) {
208
cluster_aabb.merge_with(p_triangle_sort[p_index_start + i].triangle_aabb);
209
}
210
211
if (p_count > p_cluster_size) {
212
int longest_axis_index = cluster_aabb.get_longest_axis_index();
213
switch (longest_axis_index) {
214
case 0:
215
triangle_sorter_x.sort(&p_triangle_sort[p_index_start], p_count);
216
break;
217
case 1:
218
triangle_sorter_y.sort(&p_triangle_sort[p_index_start], p_count);
219
break;
220
case 2:
221
triangle_sorter_z.sort(&p_triangle_sort[p_index_start], p_count);
222
break;
223
default:
224
DEV_ASSERT(false && "Invalid axis returned by AABB.");
225
break;
226
}
227
228
uint32_t left_cluster_count = next_power_of_2(p_count / 2);
229
left_cluster_count = MAX(left_cluster_count, p_cluster_size);
230
left_cluster_count = MIN(left_cluster_count, p_count);
231
_sort_triangle_clusters(p_cluster_size, p_cluster_index, p_index_start, left_cluster_count, p_triangle_sort, p_cluster_aabb);
232
233
if (left_cluster_count < p_count) {
234
uint32_t cluster_index_right = p_cluster_index + (left_cluster_count / p_cluster_size);
235
_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);
236
}
237
} else {
238
ClusterAABB &aabb = p_cluster_aabb[p_cluster_index];
239
Vector3 aabb_end = cluster_aabb.get_end();
240
aabb.min_bounds[0] = cluster_aabb.position.x;
241
aabb.min_bounds[1] = cluster_aabb.position.y;
242
aabb.min_bounds[2] = cluster_aabb.position.z;
243
aabb.max_bounds[0] = aabb_end.x;
244
aabb.max_bounds[1] = aabb_end.y;
245
aabb.max_bounds[2] = aabb_end.z;
246
}
247
}
248
249
Lightmapper::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) {
250
Vector<Size2i> sizes;
251
252
for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
253
MeshInstance &mi = mesh_instances.write[m_i];
254
Size2i s = Size2i(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height());
255
sizes.push_back(s);
256
atlas_size = atlas_size.max(s + Size2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor);
257
}
258
259
int max = nearest_power_of_2_templated(atlas_size.width);
260
max = MAX(max, nearest_power_of_2_templated(atlas_size.height));
261
262
if (max > p_max_texture_size) {
263
return BAKE_ERROR_TEXTURE_EXCEEDS_MAX_SIZE;
264
}
265
266
if (p_step_function) {
267
if (p_step_function(0.1, RTR("Determining optimal atlas size"), p_bake_userdata, true)) {
268
return BAKE_ERROR_USER_ABORTED;
269
}
270
}
271
272
atlas_size = Size2i(max, max);
273
274
Size2i best_atlas_size;
275
int best_atlas_slices = 0;
276
int best_atlas_memory = 0x7FFFFFFF;
277
Vector<Vector3i> best_atlas_offsets;
278
279
// Determine best texture array atlas size by bruteforce fitting.
280
while (atlas_size.x <= p_max_texture_size && atlas_size.y <= p_max_texture_size) {
281
Vector<Vector2i> source_sizes;
282
Vector<int> source_indices;
283
source_sizes.resize(sizes.size());
284
source_indices.resize(sizes.size());
285
for (int i = 0; i < source_indices.size(); i++) {
286
// Add padding between lightmaps.
287
// Scale the padding if the lightmap will be downsampled at the end of the baking process
288
// Otherwise the padding would be insufficient.
289
source_sizes.write[i] = sizes[i] + Vector2i(2, 2).maxi(p_denoiser_range) * p_supersampling_factor;
290
source_indices.write[i] = i;
291
}
292
Vector<Vector3i> atlas_offsets;
293
atlas_offsets.resize(source_sizes.size());
294
295
// Ensure the sizes can all fit into a single atlas layer.
296
// This should always happen, and this check is only in place to prevent an infinite loop.
297
for (int i = 0; i < source_sizes.size(); i++) {
298
if (source_sizes[i] > atlas_size) {
299
return BAKE_ERROR_ATLAS_TOO_SMALL;
300
}
301
}
302
303
int slices = 0;
304
305
while (source_sizes.size() > 0) {
306
Vector<Vector3i> offsets = Geometry2D::partial_pack_rects(source_sizes, atlas_size);
307
Vector<int> new_indices;
308
Vector<Vector2i> new_sources;
309
for (int i = 0; i < offsets.size(); i++) {
310
Vector3i ofs = offsets[i];
311
int sidx = source_indices[i];
312
if (ofs.z > 0) {
313
//valid
314
ofs.z = slices;
315
atlas_offsets.write[sidx] = ofs + Vector3i(1, 1, 0); // Center lightmap in the reserved oversized region
316
} else {
317
new_indices.push_back(sidx);
318
new_sources.push_back(source_sizes[i]);
319
}
320
}
321
322
source_sizes = new_sources;
323
source_indices = new_indices;
324
slices++;
325
}
326
327
int mem_used = atlas_size.x * atlas_size.y * slices;
328
if (mem_used < best_atlas_memory) {
329
best_atlas_size = atlas_size;
330
best_atlas_offsets = atlas_offsets;
331
best_atlas_slices = slices;
332
best_atlas_memory = mem_used;
333
}
334
335
if (atlas_size.width == atlas_size.height) {
336
atlas_size.width *= 2;
337
} else {
338
atlas_size.height *= 2;
339
}
340
}
341
atlas_size = best_atlas_size;
342
atlas_slices = best_atlas_slices;
343
344
// apply the offsets and slice to all images, and also blit albedo and emission
345
albedo_images.resize(atlas_slices);
346
emission_images.resize(atlas_slices);
347
348
if (p_step_function) {
349
if (p_step_function(0.2, RTR("Blitting albedo and emission"), p_bake_userdata, true)) {
350
return BAKE_ERROR_USER_ABORTED;
351
}
352
}
353
354
for (int i = 0; i < atlas_slices; i++) {
355
Ref<Image> albedo = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8);
356
albedo->set_as_black();
357
albedo_images.write[i] = albedo;
358
359
Ref<Image> emission = Image::create_empty(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH);
360
emission->set_as_black();
361
emission_images.write[i] = emission;
362
}
363
364
//assign uv positions
365
366
for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
367
MeshInstance &mi = mesh_instances.write[m_i];
368
mi.offset.x = best_atlas_offsets[m_i].x;
369
mi.offset.y = best_atlas_offsets[m_i].y;
370
mi.slice = best_atlas_offsets[m_i].z;
371
albedo_images.write[mi.slice]->blit_rect(mi.data.albedo_on_uv2, Rect2i(Vector2i(), mi.data.albedo_on_uv2->get_size()), mi.offset);
372
emission_images.write[mi.slice]->blit_rect(mi.data.emission_on_uv2, Rect2(Vector2i(), mi.data.emission_on_uv2->get_size()), mi.offset);
373
}
374
375
return BAKE_OK;
376
}
377
378
void 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) {
379
HashMap<Vertex, uint32_t, VertexHash> vertex_map;
380
381
//fill triangles array and vertex array
382
LocalVector<Triangle> triangles;
383
LocalVector<Vertex> vertex_array;
384
LocalVector<Seam> seams;
385
386
slice_triangle_count.resize(atlas_slices);
387
slice_seam_count.resize(atlas_slices);
388
389
for (int i = 0; i < atlas_slices; i++) {
390
slice_triangle_count.write[i] = 0;
391
slice_seam_count.write[i] = 0;
392
}
393
394
bounds = AABB();
395
396
for (int m_i = 0; m_i < mesh_instances.size(); m_i++) {
397
if (p_step_function) {
398
float p = float(m_i + 1) / MAX(1, mesh_instances.size()) * 0.1;
399
p_step_function(0.3 + p, vformat(RTR("Plotting mesh into acceleration structure %d/%d"), m_i + 1, mesh_instances.size()), p_bake_userdata, false);
400
}
401
402
HashMap<Edge, EdgeUV2, EdgeHash> edges;
403
404
MeshInstance &mi = mesh_instances.write[m_i];
405
406
Vector2 uv_scale = Vector2(mi.data.albedo_on_uv2->get_width(), mi.data.albedo_on_uv2->get_height()) / Vector2(atlas_size);
407
Vector2 uv_offset = Vector2(mi.offset) / Vector2(atlas_size);
408
if (m_i == 0) {
409
bounds.position = mi.data.points[0];
410
}
411
412
for (int i = 0; i < mi.data.points.size(); i += 3) {
413
Vector3 vtxs[3] = { mi.data.points[i + 0], mi.data.points[i + 1], mi.data.points[i + 2] };
414
Vector2 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 };
415
Vector3 normal[3] = { mi.data.normal[i + 0], mi.data.normal[i + 1], mi.data.normal[i + 2] };
416
417
AABB taabb;
418
Triangle t;
419
t.slice = mi.slice;
420
for (int k = 0; k < 3; k++) {
421
bounds.expand_to(vtxs[k]);
422
423
Vertex v;
424
v.position[0] = vtxs[k].x;
425
v.position[1] = vtxs[k].y;
426
v.position[2] = vtxs[k].z;
427
v.uv[0] = uvs[k].x;
428
v.uv[1] = uvs[k].y;
429
v.normal_xy[0] = normal[k].x;
430
v.normal_xy[1] = normal[k].y;
431
v.normal_z = normal[k].z;
432
433
uint32_t *indexptr = vertex_map.getptr(v);
434
435
if (indexptr) {
436
t.indices[k] = *indexptr;
437
} else {
438
uint32_t new_index = vertex_map.size();
439
t.indices[k] = new_index;
440
vertex_map[v] = new_index;
441
vertex_array.push_back(v);
442
}
443
444
if (k == 0) {
445
taabb.position = vtxs[k];
446
} else {
447
taabb.expand_to(vtxs[k]);
448
}
449
}
450
451
//compute seams that will need to be blended later
452
for (int k = 0; k < 3; k++) {
453
int n = (k + 1) % 3;
454
455
Edge edge(vtxs[k], vtxs[n], normal[k], normal[n]);
456
Vector2i edge_indices(t.indices[k], t.indices[n]);
457
EdgeUV2 uv2(uvs[k], uvs[n], edge_indices);
458
459
if (edge.b == edge.a) {
460
continue; //degenerate, somehow
461
}
462
if (edge.b < edge.a) {
463
SWAP(edge.a, edge.b);
464
SWAP(edge.na, edge.nb);
465
SWAP(uv2.a, uv2.b);
466
SWAP(uv2.indices.x, uv2.indices.y);
467
SWAP(edge_indices.x, edge_indices.y);
468
}
469
470
EdgeUV2 *euv2 = edges.getptr(edge);
471
if (!euv2) {
472
edges[edge] = uv2;
473
} else {
474
if (*euv2 == uv2) {
475
continue; // seam shared UV space, no need to blend
476
}
477
if (euv2->seam_found) {
478
continue; //bad geometry
479
}
480
481
Seam seam;
482
seam.a = edge_indices;
483
seam.b = euv2->indices;
484
seam.slice = mi.slice;
485
seams.push_back(seam);
486
slice_seam_count.write[mi.slice]++;
487
euv2->seam_found = true;
488
}
489
}
490
491
t.min_bounds[0] = taabb.position.x;
492
t.min_bounds[1] = taabb.position.y;
493
t.min_bounds[2] = taabb.position.z;
494
t.max_bounds[0] = taabb.position.x + MAX(taabb.size.x, 0.0001);
495
t.max_bounds[1] = taabb.position.y + MAX(taabb.size.y, 0.0001);
496
t.max_bounds[2] = taabb.position.z + MAX(taabb.size.z, 0.0001);
497
498
t.cull_mode = RS::CULL_MODE_BACK;
499
500
RID material = mi.data.material[i];
501
if (material.is_valid()) {
502
t.cull_mode = RSG::material_storage->material_get_cull_mode(material);
503
}
504
t.pad1 = 0; //make valgrind not complain
505
triangles.push_back(t);
506
slice_triangle_count.write[t.slice]++;
507
}
508
}
509
510
//also consider probe positions for bounds
511
for (int i = 0; i < p_probe_positions.size(); i++) {
512
Vector3 pp(p_probe_positions[i].position[0], p_probe_positions[i].position[1], p_probe_positions[i].position[2]);
513
bounds.expand_to(pp);
514
}
515
bounds.grow_by(0.1); //grow a bit to avoid numerical error
516
517
triangles.sort(); //sort by slice
518
seams.sort();
519
520
if (p_step_function) {
521
p_step_function(0.4, RTR("Optimizing acceleration structure"), p_bake_userdata, true);
522
}
523
524
//fill list of triangles in grid
525
LocalVector<TriangleSort> triangle_sort;
526
for (uint32_t i = 0; i < triangles.size(); i++) {
527
const Triangle &t = triangles[i];
528
Vector3 face[3] = {
529
Vector3(vertex_array[t.indices[0]].position[0], vertex_array[t.indices[0]].position[1], vertex_array[t.indices[0]].position[2]),
530
Vector3(vertex_array[t.indices[1]].position[0], vertex_array[t.indices[1]].position[1], vertex_array[t.indices[1]].position[2]),
531
Vector3(vertex_array[t.indices[2]].position[0], vertex_array[t.indices[2]].position[1], vertex_array[t.indices[2]].position[2])
532
};
533
_plot_triangle_into_triangle_index_list(grid_size, Vector3i(), bounds, face, i, triangle_sort, grid_size);
534
}
535
//sort it
536
triangle_sort.sort();
537
538
LocalVector<uint32_t> cluster_indices;
539
LocalVector<ClusterAABB> cluster_aabbs;
540
Vector<uint32_t> triangle_indices;
541
triangle_indices.resize(triangle_sort.size());
542
Vector<uint32_t> grid_indices;
543
grid_indices.resize(grid_size * grid_size * grid_size * 2);
544
memset(grid_indices.ptrw(), 0, grid_indices.size() * sizeof(uint32_t));
545
546
{
547
// Fill grid with cell indices.
548
uint32_t last_cell = 0xFFFFFFFF;
549
uint32_t *giw = grid_indices.ptrw();
550
uint32_t cluster_count = 0;
551
uint32_t solid_cell_count = 0;
552
for (uint32_t i = 0; i < triangle_sort.size(); i++) {
553
uint32_t cell = triangle_sort[i].cell_index;
554
if (cell != last_cell) {
555
giw[cell * 2 + 1] = solid_cell_count;
556
solid_cell_count++;
557
}
558
559
if ((giw[cell * 2] % p_cluster_size) == 0) {
560
// Add an extra cluster every time the triangle counter reaches a multiple of the cluster size.
561
cluster_count++;
562
}
563
564
giw[cell * 2]++;
565
last_cell = cell;
566
}
567
568
// Build fixed-size triangle clusters for all the cells to speed up the traversal. A cell can hold multiple clusters that each contain a fixed
569
// 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.
570
//
571
// The building algorithm will divide the triangles recursively contained inside each cell, sorting by the longest axis of the AABB on each step.
572
//
573
// - If the amount of triangles is less or equal to the cluster size, the AABB will be stored and the algorithm stops.
574
//
575
// - 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) to
576
// ensure the first half always fills the cluster.
577
578
cluster_indices.resize(solid_cell_count * 2);
579
cluster_aabbs.resize(cluster_count);
580
581
uint32_t i = 0;
582
uint32_t cluster_index = 0;
583
uint32_t solid_cell_index = 0;
584
uint32_t *tiw = triangle_indices.ptrw();
585
while (i < triangle_sort.size()) {
586
cluster_indices[solid_cell_index * 2] = cluster_index;
587
cluster_indices[solid_cell_index * 2 + 1] = i;
588
589
uint32_t cell = triangle_sort[i].cell_index;
590
uint32_t triangle_count = giw[cell * 2];
591
uint32_t cell_cluster_count = (triangle_count + p_cluster_size - 1) / p_cluster_size;
592
_sort_triangle_clusters(p_cluster_size, cluster_index, i, triangle_count, triangle_sort, cluster_aabbs);
593
594
for (uint32_t j = 0; j < triangle_count; j++) {
595
tiw[i + j] = triangle_sort[i + j].triangle_index;
596
}
597
598
i += triangle_count;
599
cluster_index += cell_cluster_count;
600
solid_cell_index++;
601
}
602
}
603
#if 0
604
for (int i = 0; i < grid_size; i++) {
605
for (int j = 0; j < grid_size; j++) {
606
for (int k = 0; k < grid_size; k++) {
607
uint32_t index = i * (grid_size * grid_size) + j * grid_size + k;
608
grid_indices.write[index * 2] = float(i) / grid_size * 255;
609
grid_indices.write[index * 2 + 1] = float(j) / grid_size * 255;
610
}
611
}
612
}
613
#endif
614
615
#if 0
616
for (int i = 0; i < grid_size; i++) {
617
Vector<uint8_t> grid_usage;
618
grid_usage.resize(grid_size * grid_size);
619
for (int j = 0; j < grid_usage.size(); j++) {
620
uint32_t ofs = i * grid_size * grid_size + j;
621
uint32_t count = grid_indices[ofs * 2];
622
grid_usage.write[j] = count > 0 ? 255 : 0;
623
}
624
625
Ref<Image> img = Image::create_from_data(grid_size, grid_size, false, Image::FORMAT_L8, grid_usage);
626
img->save_png("res://grid_layer_" + itos(1000 + i).substr(1, 3) + ".png");
627
}
628
#endif
629
630
/*****************************/
631
/*** CREATE GPU STRUCTURES ***/
632
/*****************************/
633
634
lights.sort();
635
light_metadata.sort();
636
637
Vector<Vector2i> seam_buffer_vec;
638
seam_buffer_vec.resize(seams.size() * 2);
639
for (uint32_t i = 0; i < seams.size(); i++) {
640
seam_buffer_vec.write[i * 2 + 0] = seams[i].a;
641
seam_buffer_vec.write[i * 2 + 1] = seams[i].b;
642
}
643
644
{ //buffers
645
vertex_buffer = rd->storage_buffer_create(vertex_array.size() * sizeof(Vertex), vertex_array.span().reinterpret<uint8_t>());
646
647
triangle_buffer = rd->storage_buffer_create(triangles.size() * sizeof(Triangle), triangles.span().reinterpret<uint8_t>());
648
649
r_triangle_indices_buffer = rd->storage_buffer_create(triangle_indices.size() * sizeof(uint32_t), triangle_indices.span().reinterpret<uint8_t>());
650
651
r_cluster_indices_buffer = rd->storage_buffer_create(cluster_indices.size() * sizeof(uint32_t), cluster_indices.span().reinterpret<uint8_t>());
652
653
r_cluster_aabbs_buffer = rd->storage_buffer_create(cluster_aabbs.size() * sizeof(ClusterAABB), cluster_aabbs.span().reinterpret<uint8_t>());
654
655
// Even when there are no lights, the buffer must exist.
656
static const Light empty_lights[1];
657
Span<uint8_t> lb = (lights.is_empty() ? Span(empty_lights) : lights.span()).reinterpret<uint8_t>();
658
lights_buffer = rd->storage_buffer_create(lb.size(), lb);
659
660
// Even when there are no seams, the buffer must exist.
661
static const Vector2i empty_seams[2];
662
Span<uint8_t> sb = (seam_buffer_vec.is_empty() ? Span(empty_seams) : seam_buffer_vec.span()).reinterpret<uint8_t>();
663
seams_buffer = rd->storage_buffer_create(sb.size(), sb);
664
665
// Even when there are no probes, the buffer must exist.
666
static const Probe empty_probes[1];
667
Span<uint8_t> pb = (p_probe_positions.is_empty() ? Span(empty_probes) : p_probe_positions.span()).reinterpret<uint8_t>();
668
probe_positions_buffer = rd->storage_buffer_create(pb.size(), pb);
669
}
670
671
{ //grid
672
673
RD::TextureFormat tf;
674
tf.width = grid_size;
675
tf.height = grid_size;
676
tf.depth = grid_size;
677
tf.texture_type = RD::TEXTURE_TYPE_3D;
678
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
679
680
Vector<Vector<uint8_t>> texdata;
681
texdata.resize(1);
682
//grid and indices
683
tf.format = RD::DATA_FORMAT_R32G32_UINT;
684
texdata.write[0] = grid_indices.to_byte_array();
685
grid_texture = rd->texture_create(tf, RD::TextureView(), texdata);
686
}
687
}
688
689
void 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) {
690
Vector<RID> framebuffers;
691
692
for (int i = 0; i < atlas_slices; i++) {
693
RID slice_pos_tex = rd->texture_create_shared_from_slice(RD::TextureView(), position_tex, i, 0);
694
RID slice_unoc_tex = rd->texture_create_shared_from_slice(RD::TextureView(), unocclude_tex, i, 0);
695
RID slice_norm_tex = rd->texture_create_shared_from_slice(RD::TextureView(), normal_tex, i, 0);
696
Vector<RID> fb;
697
fb.push_back(slice_pos_tex);
698
fb.push_back(slice_norm_tex);
699
fb.push_back(slice_unoc_tex);
700
fb.push_back(raster_depth_buffer);
701
framebuffers.push_back(rd->framebuffer_create(fb));
702
}
703
704
RD::PipelineDepthStencilState ds;
705
ds.enable_depth_test = true;
706
ds.enable_depth_write = true;
707
ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does render same pixel twice
708
709
RID 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);
710
RID raster_pipeline_wire;
711
{
712
RD::PipelineRasterizationState rw;
713
rw.wireframe = true;
714
raster_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);
715
}
716
717
uint32_t triangle_offset = 0;
718
Vector<Color> clear_colors;
719
clear_colors.push_back(Color(0, 0, 0, 0));
720
clear_colors.push_back(Color(0, 0, 0, 0));
721
clear_colors.push_back(Color(0, 0, 0, 0));
722
723
for (int i = 0; i < atlas_slices; i++) {
724
RasterPushConstant raster_push_constant;
725
raster_push_constant.atlas_size[0] = atlas_size.x;
726
raster_push_constant.atlas_size[1] = atlas_size.y;
727
raster_push_constant.base_triangle = triangle_offset;
728
raster_push_constant.to_cell_offset[0] = bounds.position.x;
729
raster_push_constant.to_cell_offset[1] = bounds.position.y;
730
raster_push_constant.to_cell_offset[2] = bounds.position.z;
731
raster_push_constant.bias = p_bias;
732
raster_push_constant.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
733
raster_push_constant.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
734
raster_push_constant.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
735
raster_push_constant.grid_size[0] = grid_size;
736
raster_push_constant.grid_size[1] = grid_size;
737
raster_push_constant.grid_size[2] = grid_size;
738
739
// Half pixel offset is required so the rasterizer doesn't output face edges directly aligned into pixels.
740
// This fixes artifacts where the pixel would be traced from the edge of a face, causing half the rays to
741
// be outside of the boundaries of the geometry. See <https://github.com/godotengine/godot/issues/69126>.
742
raster_push_constant.uv_offset[0] = -0.5f / float(atlas_size.x);
743
raster_push_constant.uv_offset[1] = -0.5f / float(atlas_size.y);
744
745
RD::DrawListID draw_list = rd->draw_list_begin(framebuffers[i], RD::DRAW_CLEAR_ALL, clear_colors, 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::LIGHTMAPPER_PASS);
746
//draw opaque
747
rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline);
748
rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
749
rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
750
rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
751
//draw wire
752
rd->draw_list_bind_render_pipeline(draw_list, raster_pipeline_wire);
753
rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
754
rd->draw_list_set_push_constant(draw_list, &raster_push_constant, sizeof(RasterPushConstant));
755
rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
756
757
rd->draw_list_end();
758
759
triangle_offset += slice_triangle_count[i];
760
}
761
}
762
763
static Vector<RD::Uniform> dilate_or_denoise_common_uniforms(RID &p_source_light_tex, RID &p_dest_light_tex) {
764
Vector<RD::Uniform> uniforms;
765
{
766
RD::Uniform u;
767
u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
768
u.binding = 0;
769
u.append_id(p_dest_light_tex);
770
uniforms.push_back(u);
771
}
772
{
773
RD::Uniform u;
774
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
775
u.binding = 1;
776
u.append_id(p_source_light_tex);
777
uniforms.push_back(u);
778
}
779
780
return uniforms;
781
}
782
783
LightmapperRD::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) {
784
Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex);
785
786
RID compute_shader_dilate = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("dilate"));
787
ERR_FAIL_COND_V(compute_shader_dilate.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
788
RID compute_shader_dilate_pipeline = rd->compute_pipeline_create(compute_shader_dilate);
789
790
RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_dilate, 1);
791
792
RD::ComputeListID compute_list = rd->compute_list_begin();
793
rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_dilate_pipeline);
794
rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
795
rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
796
push_constant.region_ofs[0] = 0;
797
push_constant.region_ofs[1] = 0;
798
Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size
799
800
for (int i = 0; i < atlas_slices; i++) {
801
push_constant.atlas_slice = i;
802
rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
803
rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
804
//no barrier, let them run all together
805
}
806
rd->compute_list_end();
807
rd->free(compute_shader_dilate);
808
809
#ifdef DEBUG_TEXTURES
810
for (int i = 0; i < atlas_slices; i++) {
811
Vector<uint8_t> s = rd->texture_get_data(source_light_tex, i);
812
Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
813
img->convert(Image::FORMAT_RGBA8);
814
img->save_png("res://5_dilated_" + itos(i) + ".png");
815
}
816
#endif
817
return BAKE_OK;
818
}
819
820
LightmapperRD::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) {
821
Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(source_light_tex, dest_light_tex);
822
823
RID compute_shader_pack = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("pack_coeffs"));
824
ERR_FAIL_COND_V(compute_shader_pack.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
825
RID compute_shader_pack_pipeline = rd->compute_pipeline_create(compute_shader_pack);
826
827
RID dilate_uniform_set = rd->uniform_set_create(uniforms, compute_shader_pack, 1);
828
829
RD::ComputeListID compute_list = rd->compute_list_begin();
830
rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_pack_pipeline);
831
rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
832
rd->compute_list_bind_uniform_set(compute_list, dilate_uniform_set, 1);
833
push_constant.region_ofs[0] = 0;
834
push_constant.region_ofs[1] = 0;
835
Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1); //restore group size
836
837
for (int i = 0; i < atlas_slices; i++) {
838
push_constant.atlas_slice = i;
839
rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
840
rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
841
//no barrier, let them run all together
842
}
843
rd->compute_list_end();
844
rd->free(compute_shader_pack);
845
846
return BAKE_OK;
847
}
848
849
Error 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) {
850
Vector<uint8_t> data = p_rd->texture_get_data(p_atlas_tex, p_index);
851
Ref<Image> img = Image::create_from_data(p_atlas_size.width, p_atlas_size.height, false, p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH, data);
852
img->convert(Image::FORMAT_RGBF);
853
Vector<uint8_t> data_float = img->get_data();
854
855
Error err = OK;
856
Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::WRITE, &err);
857
ERR_FAIL_COND_V_MSG(err, err, vformat("Can't save PFN at path: '%s'.", p_name));
858
file->store_line("PF");
859
file->store_line(vformat("%d %d", img->get_width(), img->get_height()));
860
#ifdef BIG_ENDIAN_ENABLED
861
file->store_line("1.0");
862
#else
863
file->store_line("-1.0");
864
#endif
865
file->store_buffer(data_float);
866
file->close();
867
868
return OK;
869
}
870
871
Ref<Image> LightmapperRD::_read_pfm(const String &p_name, bool p_shadowmask) {
872
Error err = OK;
873
Ref<FileAccess> file = FileAccess::open(p_name, FileAccess::READ, &err);
874
ERR_FAIL_COND_V_MSG(err, Ref<Image>(), vformat("Can't load PFM at path: '%s'.", p_name));
875
ERR_FAIL_COND_V(file->get_line() != "PF", Ref<Image>());
876
877
Vector<String> new_size = file->get_line().split(" ");
878
ERR_FAIL_COND_V(new_size.size() != 2, Ref<Image>());
879
int new_width = new_size[0].to_int();
880
int new_height = new_size[1].to_int();
881
882
float endian = file->get_line().to_float();
883
Vector<uint8_t> new_data = file->get_buffer(file->get_length() - file->get_position());
884
file->close();
885
886
#ifdef BIG_ENDIAN_ENABLED
887
if (unlikely(endian < 0.0)) {
888
uint32_t count = new_data.size() / 4;
889
uint16_t *dst = (uint16_t *)new_data.ptrw();
890
for (uint32_t j = 0; j < count; j++) {
891
dst[j * 4] = BSWAP32(dst[j * 4]);
892
}
893
}
894
#else
895
if (unlikely(endian > 0.0)) {
896
uint32_t count = new_data.size() / 4;
897
uint16_t *dst = (uint16_t *)new_data.ptrw();
898
for (uint32_t j = 0; j < count; j++) {
899
dst[j * 4] = BSWAP32(dst[j * 4]);
900
}
901
}
902
#endif
903
Ref<Image> img = Image::create_from_data(new_width, new_height, false, Image::FORMAT_RGBF, new_data);
904
img->convert(p_shadowmask ? Image::FORMAT_RGBA8 : Image::FORMAT_RGBAH);
905
return img;
906
}
907
908
LightmapperRD::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) {
909
Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
910
911
for (int i = 0; i < p_atlas_slices; i++) {
912
String fname_norm_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_norm_%d.pfm", i));
913
_store_pfm(p_rd, p_source_normal_tex, i, p_atlas_size, fname_norm_in, false);
914
915
for (int j = 0; j < (p_bake_sh ? 4 : 1); j++) {
916
int index = i * (p_bake_sh ? 4 : 1) + j;
917
String fname_light_in = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_light_%d.pfm", index));
918
String fname_out = EditorPaths::get_singleton()->get_cache_dir().path_join(vformat("temp_denoised_%d.pfm", index));
919
920
_store_pfm(p_rd, p_source_light_tex, index, p_atlas_size, fname_light_in, p_shadowmask);
921
922
List<String> args;
923
args.push_back("--device");
924
args.push_back("default");
925
926
args.push_back("--filter");
927
args.push_back("RTLightmap");
928
929
args.push_back(p_shadowmask ? "--ldr" : "--hdr");
930
args.push_back(fname_light_in);
931
932
args.push_back("--nrm");
933
args.push_back(fname_norm_in);
934
935
args.push_back("--output");
936
args.push_back(fname_out);
937
938
String str;
939
int exitcode = 0;
940
941
Error err = OS::get_singleton()->execute(p_exe, args, &str, &exitcode, true);
942
943
da->remove(fname_light_in);
944
945
if (err != OK || exitcode != 0) {
946
da->remove(fname_out);
947
print_verbose(str);
948
ERR_FAIL_V_MSG(BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES, vformat("OIDN denoiser failed, return code: %d", exitcode));
949
}
950
951
Ref<Image> img = _read_pfm(fname_out, p_shadowmask);
952
da->remove(fname_out);
953
954
ERR_FAIL_COND_V(img.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
955
956
Vector<uint8_t> old_data = p_rd->texture_get_data(p_source_light_tex, index);
957
Vector<uint8_t> new_data = img->get_data();
958
img.unref(); // Avoid copy on write.
959
960
uint32_t count = old_data.size() / 2;
961
const uint16_t *src = (const uint16_t *)old_data.ptr();
962
uint16_t *dst = (uint16_t *)new_data.ptrw();
963
for (uint32_t k = 0; k < count; k += 4) {
964
dst[k + 3] = src[k + 3];
965
}
966
967
p_rd->texture_update(p_dest_light_tex, index, new_data);
968
}
969
da->remove(fname_norm_in);
970
}
971
return BAKE_OK;
972
}
973
974
LightmapperRD::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) {
975
RID denoise_params_buffer = p_rd->uniform_buffer_create(sizeof(DenoiseParams));
976
DenoiseParams denoise_params;
977
denoise_params.spatial_bandwidth = 5.0f;
978
denoise_params.light_bandwidth = p_denoiser_strength;
979
denoise_params.albedo_bandwidth = 1.0f;
980
denoise_params.normal_bandwidth = 0.1f;
981
denoise_params.filter_strength = 10.0f;
982
denoise_params.half_search_window = p_denoiser_range;
983
p_rd->buffer_update(denoise_params_buffer, 0, sizeof(DenoiseParams), &denoise_params);
984
985
Vector<RD::Uniform> uniforms = dilate_or_denoise_common_uniforms(p_source_light_tex, p_dest_light_tex);
986
{
987
RD::Uniform u;
988
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
989
u.binding = 2;
990
u.append_id(p_source_normal_tex);
991
uniforms.push_back(u);
992
}
993
{
994
RD::Uniform u;
995
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
996
u.binding = 3;
997
u.append_id(p_unocclude_tex);
998
uniforms.push_back(u);
999
}
1000
{
1001
RD::Uniform u;
1002
u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
1003
u.binding = 4;
1004
u.append_id(denoise_params_buffer);
1005
uniforms.push_back(u);
1006
}
1007
1008
RID compute_shader_denoise = p_rd->shader_create_from_spirv(p_compute_shader->get_spirv_stages("denoise"));
1009
ERR_FAIL_COND_V(compute_shader_denoise.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
1010
1011
RID compute_shader_denoise_pipeline = p_rd->compute_pipeline_create(compute_shader_denoise);
1012
RID denoise_uniform_set = p_rd->uniform_set_create(uniforms, compute_shader_denoise, 1);
1013
1014
// We denoise in fixed size regions and synchronize execution to avoid GPU timeouts.
1015
// We use a region with 1/4 the amount of pixels if we're denoising SH lightmaps, as
1016
// all four of them are denoised in the shader in one dispatch.
1017
const int user_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));
1018
const int max_region_size = p_bake_sh ? user_region_size / 2 : user_region_size;
1019
int x_regions = Math::division_round_up(p_atlas_size.width, max_region_size);
1020
int y_regions = Math::division_round_up(p_atlas_size.height, max_region_size);
1021
for (int s = 0; s < p_atlas_slices; s++) {
1022
p_push_constant.atlas_slice = s;
1023
1024
for (int i = 0; i < x_regions; i++) {
1025
for (int j = 0; j < y_regions; j++) {
1026
int x = i * max_region_size;
1027
int y = j * max_region_size;
1028
int w = MIN((i + 1) * max_region_size, p_atlas_size.width) - x;
1029
int h = MIN((j + 1) * max_region_size, p_atlas_size.height) - y;
1030
p_push_constant.region_ofs[0] = x;
1031
p_push_constant.region_ofs[1] = y;
1032
1033
RD::ComputeListID compute_list = p_rd->compute_list_begin();
1034
p_rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_denoise_pipeline);
1035
p_rd->compute_list_bind_uniform_set(compute_list, p_compute_base_uniform_set, 0);
1036
p_rd->compute_list_bind_uniform_set(compute_list, denoise_uniform_set, 1);
1037
p_rd->compute_list_set_push_constant(compute_list, &p_push_constant, sizeof(PushConstant));
1038
p_rd->compute_list_dispatch(compute_list, Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
1039
p_rd->compute_list_end();
1040
1041
p_rd->submit();
1042
p_rd->sync();
1043
}
1044
}
1045
if (p_step_function) {
1046
int percent = (s + 1) * 100 / p_atlas_slices;
1047
float p = float(s) / p_atlas_slices * 0.1;
1048
if (p_step_function(0.8 + p, vformat(RTR("Denoising %d%%"), percent), p_bake_userdata, false)) {
1049
return BAKE_ERROR_USER_ABORTED;
1050
}
1051
}
1052
}
1053
1054
p_rd->free(compute_shader_denoise);
1055
p_rd->free(denoise_params_buffer);
1056
1057
return BAKE_OK;
1058
}
1059
1060
LightmapperRD::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) {
1061
int denoiser = GLOBAL_GET("rendering/lightmapping/denoising/denoiser");
1062
String oidn_path = EDITOR_GET("filesystem/tools/oidn/oidn_denoise_path");
1063
1064
if (p_use_denoiser && denoiser == 1) {
1065
// OIDN (external).
1066
Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
1067
1068
if (da->dir_exists(oidn_path)) {
1069
if (OS::get_singleton()->get_name() == "Windows") {
1070
oidn_path = oidn_path.path_join("oidnDenoise.exe");
1071
} else {
1072
oidn_path = oidn_path.path_join("oidnDenoise");
1073
}
1074
}
1075
ERR_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.");
1076
}
1077
1078
if (p_step_function) {
1079
p_step_function(0.0, RTR("Begin Bake"), p_bake_userdata, true);
1080
}
1081
lightmap_textures.clear();
1082
shadowmask_textures.clear();
1083
int grid_size = 128;
1084
1085
/* STEP 1: Fetch material textures and compute the bounds */
1086
1087
AABB bounds;
1088
Size2i atlas_size;
1089
int atlas_slices;
1090
Vector<Ref<Image>> albedo_images;
1091
Vector<Ref<Image>> emission_images;
1092
1093
BakeError 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);
1094
if (bake_error != BAKE_OK) {
1095
return bake_error;
1096
}
1097
1098
// Find any directional light suitable for shadowmasking.
1099
if (p_bake_shadowmask) {
1100
bool found = false;
1101
for (int i = 0; i < lights.size(); i++) {
1102
if (lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL && !lights[i].static_bake) {
1103
found = true;
1104
break;
1105
}
1106
}
1107
1108
if (!found) {
1109
p_bake_shadowmask = false;
1110
WARN_PRINT("Shadowmask disabled: no directional light with their bake mode set to dynamic exists.");
1111
}
1112
}
1113
1114
#ifdef DEBUG_TEXTURES
1115
for (int i = 0; i < atlas_slices; i++) {
1116
albedo_images[i]->save_png("res://0_albedo_" + itos(i) + ".png");
1117
emission_images[i]->save_png("res://0_emission_" + itos(i) + ".png");
1118
}
1119
#endif
1120
1121
// Attempt to create a local device by requesting it from rendering server first.
1122
// If that fails because the current renderer is not implemented on top of RD, we fall back to creating
1123
// a local rendering device manually depending on the current platform.
1124
Error err;
1125
RenderingContextDriver *rcd = nullptr;
1126
RenderingDevice *rd = RenderingServer::get_singleton()->create_local_rendering_device();
1127
if (rd == nullptr) {
1128
#if defined(RD_ENABLED)
1129
#if defined(METAL_ENABLED)
1130
rcd = memnew(RenderingContextDriverMetal);
1131
rd = memnew(RenderingDevice);
1132
#endif
1133
#if defined(VULKAN_ENABLED)
1134
if (rcd == nullptr) {
1135
rcd = memnew(RenderingContextDriverVulkan);
1136
rd = memnew(RenderingDevice);
1137
}
1138
#endif
1139
#endif
1140
if (rcd != nullptr && rd != nullptr) {
1141
err = rcd->initialize();
1142
if (err == OK) {
1143
err = rd->initialize(rcd);
1144
}
1145
1146
if (err != OK) {
1147
memdelete(rd);
1148
memdelete(rcd);
1149
rd = nullptr;
1150
rcd = nullptr;
1151
}
1152
}
1153
}
1154
1155
ERR_FAIL_NULL_V(rd, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
1156
1157
RID albedo_array_tex;
1158
RID emission_array_tex;
1159
RID normal_tex;
1160
RID position_tex;
1161
RID unocclude_tex;
1162
RID light_source_tex;
1163
RID light_dest_tex;
1164
RID light_accum_tex;
1165
RID light_accum_tex2;
1166
RID light_environment_tex;
1167
RID shadowmask_tex;
1168
RID shadowmask_tex2;
1169
1170
#define FREE_TEXTURES \
1171
rd->free(albedo_array_tex); \
1172
rd->free(emission_array_tex); \
1173
rd->free(normal_tex); \
1174
rd->free(position_tex); \
1175
rd->free(unocclude_tex); \
1176
rd->free(light_source_tex); \
1177
rd->free(light_accum_tex2); \
1178
rd->free(light_accum_tex); \
1179
rd->free(light_environment_tex); \
1180
if (p_bake_shadowmask) { \
1181
rd->free(shadowmask_tex); \
1182
rd->free(shadowmask_tex2); \
1183
}
1184
1185
{ // create all textures
1186
1187
Vector<Vector<uint8_t>> albedo_data;
1188
Vector<Vector<uint8_t>> emission_data;
1189
for (int i = 0; i < atlas_slices; i++) {
1190
albedo_data.push_back(albedo_images[i]->get_data());
1191
emission_data.push_back(emission_images[i]->get_data());
1192
}
1193
1194
RD::TextureFormat tf;
1195
tf.width = atlas_size.width;
1196
tf.height = atlas_size.height;
1197
tf.array_layers = atlas_slices;
1198
tf.texture_type = RD::TEXTURE_TYPE_2D_ARRAY;
1199
tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
1200
tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
1201
1202
albedo_array_tex = rd->texture_create(tf, RD::TextureView(), albedo_data);
1203
1204
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
1205
1206
emission_array_tex = rd->texture_create(tf, RD::TextureView(), emission_data);
1207
1208
//this will be rastered to
1209
tf.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;
1210
normal_tex = rd->texture_create(tf, RD::TextureView());
1211
tf.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
1212
position_tex = rd->texture_create(tf, RD::TextureView());
1213
unocclude_tex = rd->texture_create(tf, RD::TextureView());
1214
1215
tf.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;
1216
1217
// shadowmask
1218
if (p_bake_shadowmask) {
1219
tf.format = RD::DATA_FORMAT_R8G8B8A8_UNORM;
1220
1221
shadowmask_tex = rd->texture_create(tf, RD::TextureView());
1222
rd->texture_clear(shadowmask_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
1223
1224
shadowmask_tex2 = rd->texture_create(tf, RD::TextureView());
1225
rd->texture_clear(shadowmask_tex2, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
1226
}
1227
1228
// lightmap
1229
tf.format = RD::DATA_FORMAT_R16G16B16A16_SFLOAT;
1230
1231
light_source_tex = rd->texture_create(tf, RD::TextureView());
1232
rd->texture_clear(light_source_tex, Color(0, 0, 0, 0), 0, 1, 0, atlas_slices);
1233
1234
if (p_bake_sh) {
1235
tf.array_layers *= 4;
1236
}
1237
light_accum_tex = rd->texture_create(tf, RD::TextureView());
1238
rd->texture_clear(light_accum_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
1239
light_dest_tex = rd->texture_create(tf, RD::TextureView());
1240
rd->texture_clear(light_dest_tex, Color(0, 0, 0, 0), 0, 1, 0, tf.array_layers);
1241
light_accum_tex2 = light_dest_tex;
1242
1243
//env
1244
{
1245
Ref<Image> panorama_tex;
1246
if (p_environment_panorama.is_valid()) {
1247
panorama_tex = p_environment_panorama;
1248
panorama_tex->convert(Image::FORMAT_RGBAF);
1249
} else {
1250
panorama_tex.instantiate();
1251
panorama_tex->initialize_data(8, 8, false, Image::FORMAT_RGBAF);
1252
panorama_tex->fill(Color(0, 0, 0, 1));
1253
}
1254
1255
RD::TextureFormat tfp;
1256
tfp.width = panorama_tex->get_width();
1257
tfp.height = panorama_tex->get_height();
1258
tfp.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_CAN_UPDATE_BIT;
1259
tfp.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
1260
1261
Vector<Vector<uint8_t>> tdata;
1262
tdata.push_back(panorama_tex->get_data());
1263
light_environment_tex = rd->texture_create(tfp, RD::TextureView(), tdata);
1264
1265
#ifdef DEBUG_TEXTURES
1266
panorama_tex->save_exr("res://0_panorama.exr", false);
1267
#endif
1268
}
1269
}
1270
1271
/* STEP 2: create the acceleration structure for the GPU*/
1272
1273
Vector<int> slice_triangle_count;
1274
RID bake_parameters_buffer;
1275
RID vertex_buffer;
1276
RID triangle_buffer;
1277
RID lights_buffer;
1278
RID triangle_indices_buffer;
1279
RID cluster_indices_buffer;
1280
RID cluster_aabbs_buffer;
1281
RID grid_texture;
1282
RID seams_buffer;
1283
RID probe_positions_buffer;
1284
1285
Vector<int> slice_seam_count;
1286
1287
#define FREE_BUFFERS \
1288
rd->free(bake_parameters_buffer); \
1289
rd->free(vertex_buffer); \
1290
rd->free(triangle_buffer); \
1291
rd->free(lights_buffer); \
1292
rd->free(triangle_indices_buffer); \
1293
rd->free(cluster_indices_buffer); \
1294
rd->free(cluster_aabbs_buffer); \
1295
rd->free(grid_texture); \
1296
rd->free(seams_buffer); \
1297
rd->free(probe_positions_buffer);
1298
1299
const uint32_t cluster_size = 16;
1300
_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);
1301
1302
// The index of the directional light used for shadowmasking.
1303
int shadowmask_light_idx = -1;
1304
1305
// Find the directional light index in the sorted lights array.
1306
if (p_bake_shadowmask) {
1307
int shadowmask_lights_count = 0;
1308
1309
for (int i = 0; i < lights.size(); i++) {
1310
if (lights[i].type == LightType::LIGHT_TYPE_DIRECTIONAL && !lights[i].static_bake) {
1311
if (shadowmask_light_idx < 0) {
1312
shadowmask_light_idx = i;
1313
}
1314
shadowmask_lights_count += 1;
1315
}
1316
}
1317
1318
if (shadowmask_lights_count > 1) {
1319
WARN_PRINT(
1320
vformat("%d directional lights detected for shadowmask baking. Only %s will be used.",
1321
shadowmask_lights_count, light_metadata[shadowmask_light_idx].name));
1322
}
1323
}
1324
1325
// Create global bake parameters buffer.
1326
BakeParameters bake_parameters;
1327
bake_parameters.world_size[0] = bounds.size.x;
1328
bake_parameters.world_size[1] = bounds.size.y;
1329
bake_parameters.world_size[2] = bounds.size.z;
1330
bake_parameters.bias = p_bias;
1331
bake_parameters.to_cell_offset[0] = bounds.position.x;
1332
bake_parameters.to_cell_offset[1] = bounds.position.y;
1333
bake_parameters.to_cell_offset[2] = bounds.position.z;
1334
bake_parameters.grid_size = grid_size;
1335
bake_parameters.to_cell_size[0] = (1.0 / bounds.size.x) * float(grid_size);
1336
bake_parameters.to_cell_size[1] = (1.0 / bounds.size.y) * float(grid_size);
1337
bake_parameters.to_cell_size[2] = (1.0 / bounds.size.z) * float(grid_size);
1338
bake_parameters.light_count = lights.size();
1339
bake_parameters.env_transform[0] = p_environment_transform.rows[0][0];
1340
bake_parameters.env_transform[1] = p_environment_transform.rows[1][0];
1341
bake_parameters.env_transform[2] = p_environment_transform.rows[2][0];
1342
bake_parameters.env_transform[3] = 0.0f;
1343
bake_parameters.env_transform[4] = p_environment_transform.rows[0][1];
1344
bake_parameters.env_transform[5] = p_environment_transform.rows[1][1];
1345
bake_parameters.env_transform[6] = p_environment_transform.rows[2][1];
1346
bake_parameters.env_transform[7] = 0.0f;
1347
bake_parameters.env_transform[8] = p_environment_transform.rows[0][2];
1348
bake_parameters.env_transform[9] = p_environment_transform.rows[1][2];
1349
bake_parameters.env_transform[10] = p_environment_transform.rows[2][2];
1350
bake_parameters.env_transform[11] = 0.0f;
1351
bake_parameters.atlas_size[0] = atlas_size.width;
1352
bake_parameters.atlas_size[1] = atlas_size.height;
1353
bake_parameters.exposure_normalization = p_exposure_normalization;
1354
bake_parameters.bounces = p_bounces;
1355
bake_parameters.bounce_indirect_energy = p_bounce_indirect_energy;
1356
bake_parameters.shadowmask_light_idx = shadowmask_light_idx;
1357
// Same number of rays for transparency regardless of quality (it's more of a retry rather than shooting new ones).
1358
bake_parameters.transparency_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_transparency_rays");
1359
bake_parameters.supersampling_factor = p_supersampling_factor;
1360
1361
bake_parameters_buffer = rd->uniform_buffer_create(sizeof(BakeParameters));
1362
rd->buffer_update(bake_parameters_buffer, 0, sizeof(BakeParameters), &bake_parameters);
1363
1364
if (p_step_function) {
1365
if (p_step_function(0.47, RTR("Preparing shaders"), p_bake_userdata, true)) {
1366
FREE_TEXTURES
1367
FREE_BUFFERS
1368
memdelete(rd);
1369
if (rcd != nullptr) {
1370
memdelete(rcd);
1371
}
1372
return BAKE_ERROR_USER_ABORTED;
1373
}
1374
}
1375
1376
//shaders
1377
Ref<RDShaderFile> raster_shader;
1378
raster_shader.instantiate();
1379
err = raster_shader->parse_versions_from_text(lm_raster_shader_glsl);
1380
if (err != OK) {
1381
raster_shader->print_errors("raster_shader");
1382
1383
FREE_TEXTURES
1384
FREE_BUFFERS
1385
1386
memdelete(rd);
1387
1388
if (rcd != nullptr) {
1389
memdelete(rcd);
1390
}
1391
}
1392
ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
1393
1394
RID rasterize_shader = rd->shader_create_from_spirv(raster_shader->get_spirv_stages());
1395
1396
ERR_FAIL_COND_V(rasterize_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //this is a bug check, though, should not happen
1397
1398
RID sampler;
1399
{
1400
RD::SamplerState s;
1401
s.mag_filter = RD::SAMPLER_FILTER_LINEAR;
1402
s.min_filter = RD::SAMPLER_FILTER_LINEAR;
1403
s.max_lod = 0;
1404
1405
sampler = rd->sampler_create(s);
1406
}
1407
1408
Vector<RD::Uniform> base_uniforms;
1409
{
1410
{
1411
RD::Uniform u;
1412
u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
1413
u.binding = 0;
1414
u.append_id(bake_parameters_buffer);
1415
base_uniforms.push_back(u);
1416
}
1417
{
1418
RD::Uniform u;
1419
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1420
u.binding = 1;
1421
u.append_id(vertex_buffer);
1422
base_uniforms.push_back(u);
1423
}
1424
{
1425
RD::Uniform u;
1426
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1427
u.binding = 2;
1428
u.append_id(triangle_buffer);
1429
base_uniforms.push_back(u);
1430
}
1431
{
1432
RD::Uniform u;
1433
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1434
u.binding = 3;
1435
u.append_id(triangle_indices_buffer);
1436
base_uniforms.push_back(u);
1437
}
1438
{
1439
RD::Uniform u;
1440
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1441
u.binding = 4;
1442
u.append_id(lights_buffer);
1443
base_uniforms.push_back(u);
1444
}
1445
{
1446
RD::Uniform u;
1447
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1448
u.binding = 5;
1449
u.append_id(seams_buffer);
1450
base_uniforms.push_back(u);
1451
}
1452
{
1453
RD::Uniform u;
1454
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1455
u.binding = 6;
1456
u.append_id(probe_positions_buffer);
1457
base_uniforms.push_back(u);
1458
}
1459
{
1460
RD::Uniform u;
1461
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1462
u.binding = 7;
1463
u.append_id(grid_texture);
1464
base_uniforms.push_back(u);
1465
}
1466
{
1467
RD::Uniform u;
1468
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1469
u.binding = 8;
1470
u.append_id(albedo_array_tex);
1471
base_uniforms.push_back(u);
1472
}
1473
{
1474
RD::Uniform u;
1475
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1476
u.binding = 9;
1477
u.append_id(emission_array_tex);
1478
base_uniforms.push_back(u);
1479
}
1480
{
1481
RD::Uniform u;
1482
u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
1483
u.binding = 10;
1484
u.append_id(sampler);
1485
base_uniforms.push_back(u);
1486
}
1487
{
1488
RD::Uniform u;
1489
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1490
u.binding = 11;
1491
u.append_id(cluster_indices_buffer);
1492
base_uniforms.push_back(u);
1493
}
1494
{
1495
RD::Uniform u;
1496
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1497
u.binding = 12;
1498
u.append_id(cluster_aabbs_buffer);
1499
base_uniforms.push_back(u);
1500
}
1501
}
1502
1503
RID raster_base_uniform = rd->uniform_set_create(base_uniforms, rasterize_shader, 0);
1504
RID raster_depth_buffer;
1505
{
1506
RD::TextureFormat tf;
1507
tf.width = atlas_size.width;
1508
tf.height = atlas_size.height;
1509
tf.depth = 1;
1510
tf.texture_type = RD::TEXTURE_TYPE_2D;
1511
tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
1512
tf.format = RD::DATA_FORMAT_D32_SFLOAT;
1513
tf.is_discardable = true;
1514
1515
raster_depth_buffer = rd->texture_create(tf, RD::TextureView());
1516
}
1517
1518
rd->submit();
1519
rd->sync();
1520
1521
/* STEP 3: Raster the geometry to UV2 coords in the atlas textures GPU*/
1522
1523
_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);
1524
1525
#ifdef DEBUG_TEXTURES
1526
1527
for (int i = 0; i < atlas_slices; i++) {
1528
Vector<uint8_t> s = rd->texture_get_data(position_tex, i);
1529
Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
1530
img->save_exr("res://1_position_" + itos(i) + ".exr", false);
1531
1532
s = rd->texture_get_data(normal_tex, i);
1533
img->set_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
1534
img->save_exr("res://1_normal_" + itos(i) + ".exr", false);
1535
}
1536
#endif
1537
1538
#define FREE_RASTER_RESOURCES \
1539
rd->free(rasterize_shader); \
1540
rd->free(sampler); \
1541
rd->free(raster_depth_buffer);
1542
1543
/* Plot direct light */
1544
1545
Ref<RDShaderFile> compute_shader;
1546
String defines = "";
1547
defines += "\n#define CLUSTER_SIZE " + uitos(cluster_size) + "\n";
1548
1549
if (p_bake_sh) {
1550
defines += "\n#define USE_SH_LIGHTMAPS\n";
1551
}
1552
1553
if (p_texture_for_bounces) {
1554
defines += "\n#define USE_LIGHT_TEXTURE_FOR_BOUNCES\n";
1555
}
1556
1557
if (p_bake_shadowmask) {
1558
defines += "\n#define USE_SHADOWMASK\n";
1559
}
1560
1561
compute_shader.instantiate();
1562
err = compute_shader->parse_versions_from_text(lm_compute_shader_glsl, defines);
1563
if (err != OK) {
1564
FREE_TEXTURES
1565
FREE_BUFFERS
1566
FREE_RASTER_RESOURCES
1567
memdelete(rd);
1568
1569
if (rcd != nullptr) {
1570
memdelete(rcd);
1571
}
1572
1573
compute_shader->print_errors("compute_shader");
1574
}
1575
ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
1576
1577
// Unoccluder
1578
RID compute_shader_unocclude = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("unocclude"));
1579
ERR_FAIL_COND_V(compute_shader_unocclude.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
1580
RID compute_shader_unocclude_pipeline = rd->compute_pipeline_create(compute_shader_unocclude);
1581
1582
// Direct light
1583
RID compute_shader_primary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("primary"));
1584
ERR_FAIL_COND_V(compute_shader_primary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); // internal check, should not happen
1585
RID compute_shader_primary_pipeline = rd->compute_pipeline_create(compute_shader_primary);
1586
1587
// Indirect light
1588
RID compute_shader_secondary = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("secondary"));
1589
ERR_FAIL_COND_V(compute_shader_secondary.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
1590
RID compute_shader_secondary_pipeline = rd->compute_pipeline_create(compute_shader_secondary);
1591
1592
// Light probes
1593
RID compute_shader_light_probes = rd->shader_create_from_spirv(compute_shader->get_spirv_stages("light_probes"));
1594
ERR_FAIL_COND_V(compute_shader_light_probes.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES); //internal check, should not happen
1595
RID compute_shader_light_probes_pipeline = rd->compute_pipeline_create(compute_shader_light_probes);
1596
1597
RID compute_base_uniform_set = rd->uniform_set_create(base_uniforms, compute_shader_primary, 0);
1598
1599
#define FREE_COMPUTE_RESOURCES \
1600
rd->free(compute_shader_unocclude); \
1601
rd->free(compute_shader_primary); \
1602
rd->free(compute_shader_secondary); \
1603
rd->free(compute_shader_light_probes);
1604
1605
Vector3i group_size(Math::division_round_up(atlas_size.x, 8), Math::division_round_up(atlas_size.y, 8), 1);
1606
rd->submit();
1607
rd->sync();
1608
1609
if (p_step_function) {
1610
if (p_step_function(0.49, RTR("Un-occluding geometry"), p_bake_userdata, true)) {
1611
FREE_TEXTURES
1612
FREE_BUFFERS
1613
FREE_RASTER_RESOURCES
1614
FREE_COMPUTE_RESOURCES
1615
memdelete(rd);
1616
if (rcd != nullptr) {
1617
memdelete(rcd);
1618
}
1619
return BAKE_ERROR_USER_ABORTED;
1620
}
1621
}
1622
1623
PushConstant push_constant;
1624
push_constant.denoiser_range = p_use_denoiser ? p_denoiser_range : 1.0;
1625
1626
/* UNOCCLUDE */
1627
{
1628
Vector<RD::Uniform> uniforms;
1629
{
1630
{
1631
RD::Uniform u;
1632
u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
1633
u.binding = 0;
1634
u.append_id(position_tex);
1635
uniforms.push_back(u);
1636
}
1637
{
1638
RD::Uniform u;
1639
u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
1640
u.binding = 1;
1641
u.append_id(unocclude_tex);
1642
uniforms.push_back(u);
1643
}
1644
}
1645
1646
RID unocclude_uniform_set = rd->uniform_set_create(uniforms, compute_shader_unocclude, 1);
1647
1648
RD::ComputeListID compute_list = rd->compute_list_begin();
1649
rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_unocclude_pipeline);
1650
rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
1651
rd->compute_list_bind_uniform_set(compute_list, unocclude_uniform_set, 1);
1652
1653
for (int i = 0; i < atlas_slices; i++) {
1654
push_constant.atlas_slice = i;
1655
rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
1656
rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
1657
//no barrier, let them run all together
1658
}
1659
rd->compute_list_end(); //done
1660
}
1661
1662
#ifdef DEBUG_TEXTURES
1663
for (int i = 0; i < atlas_slices; i++) {
1664
Vector<uint8_t> s = rd->texture_get_data(unocclude_tex, i);
1665
Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAF, s);
1666
img->save_exr("res://1_unocclude_" + itos(i) + ".exr", false);
1667
}
1668
#endif
1669
1670
if (p_step_function) {
1671
if (p_step_function(0.5, RTR("Plot direct lighting"), p_bake_userdata, true)) {
1672
FREE_TEXTURES
1673
FREE_BUFFERS
1674
FREE_RASTER_RESOURCES
1675
FREE_COMPUTE_RESOURCES
1676
memdelete(rd);
1677
if (rcd != nullptr) {
1678
memdelete(rcd);
1679
}
1680
return BAKE_ERROR_USER_ABORTED;
1681
}
1682
}
1683
1684
const int max_region_size = nearest_power_of_2_templated(int(GLOBAL_GET("rendering/lightmapping/bake_performance/region_size")));
1685
const int x_regions = Math::division_round_up(atlas_size.width, max_region_size);
1686
const int y_regions = Math::division_round_up(atlas_size.height, max_region_size);
1687
1688
// Set ray count to the quality used for direct light and bounces.
1689
switch (p_quality) {
1690
case BAKE_QUALITY_LOW: {
1691
push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_ray_count");
1692
} break;
1693
case BAKE_QUALITY_MEDIUM: {
1694
push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_ray_count");
1695
} break;
1696
case BAKE_QUALITY_HIGH: {
1697
push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_ray_count");
1698
} break;
1699
case BAKE_QUALITY_ULTRA: {
1700
push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_ray_count");
1701
} break;
1702
}
1703
1704
push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
1705
1706
/* PRIMARY (direct) LIGHT PASS */
1707
{
1708
Vector<RD::Uniform> uniforms;
1709
{
1710
{
1711
RD::Uniform u;
1712
u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
1713
u.binding = 0;
1714
u.append_id(light_source_tex);
1715
uniforms.push_back(u);
1716
}
1717
{
1718
RD::Uniform u;
1719
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1720
u.binding = 1;
1721
u.append_id(light_dest_tex); //will be unused
1722
uniforms.push_back(u);
1723
}
1724
{
1725
RD::Uniform u;
1726
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1727
u.binding = 2;
1728
u.append_id(position_tex);
1729
uniforms.push_back(u);
1730
}
1731
{
1732
RD::Uniform u;
1733
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1734
u.binding = 3;
1735
u.append_id(normal_tex);
1736
uniforms.push_back(u);
1737
}
1738
{
1739
RD::Uniform u;
1740
u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
1741
u.binding = 4;
1742
u.append_id(light_accum_tex);
1743
uniforms.push_back(u);
1744
}
1745
1746
if (p_bake_shadowmask) {
1747
RD::Uniform u;
1748
u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
1749
u.binding = 5;
1750
u.append_id(shadowmask_tex);
1751
uniforms.push_back(u);
1752
}
1753
}
1754
1755
RID light_uniform_set = rd->uniform_set_create(uniforms, compute_shader_primary, 1);
1756
1757
int count = 0;
1758
for (int s = 0; s < atlas_slices; s++) {
1759
push_constant.atlas_slice = s;
1760
1761
for (int i = 0; i < x_regions; i++) {
1762
for (int j = 0; j < y_regions; j++) {
1763
int x = i * max_region_size;
1764
int y = j * max_region_size;
1765
int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
1766
int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
1767
1768
push_constant.region_ofs[0] = x;
1769
push_constant.region_ofs[1] = y;
1770
1771
group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
1772
RD::ComputeListID compute_list = rd->compute_list_begin();
1773
rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_primary_pipeline);
1774
rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
1775
rd->compute_list_bind_uniform_set(compute_list, light_uniform_set, 1);
1776
rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
1777
rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
1778
rd->compute_list_end();
1779
1780
rd->submit();
1781
rd->sync();
1782
1783
count++;
1784
if (p_step_function) {
1785
int total = (atlas_slices * x_regions * y_regions);
1786
int percent = count * 100 / total;
1787
float p = float(count) / total * 0.1;
1788
if (p_step_function(0.5 + p, vformat(RTR("Plot direct lighting %d%%"), percent), p_bake_userdata, false)) {
1789
FREE_TEXTURES
1790
FREE_BUFFERS
1791
FREE_RASTER_RESOURCES
1792
FREE_COMPUTE_RESOURCES
1793
memdelete(rd);
1794
if (rcd != nullptr) {
1795
memdelete(rcd);
1796
}
1797
return BAKE_ERROR_USER_ABORTED;
1798
}
1799
}
1800
}
1801
}
1802
}
1803
}
1804
1805
#ifdef DEBUG_TEXTURES
1806
1807
for (int i = 0; i < atlas_slices; i++) {
1808
Vector<uint8_t> s = rd->texture_get_data(light_source_tex, i);
1809
Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
1810
img->save_exr("res://2_light_primary_" + itos(i) + ".exr", false);
1811
}
1812
1813
if (p_bake_sh) {
1814
for (int i = 0; i < atlas_slices * 4; i++) {
1815
Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
1816
Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
1817
img->save_exr("res://2_light_primary_accum_" + itos(i) + ".exr", false);
1818
}
1819
}
1820
#endif
1821
1822
/* SECONDARY (indirect) LIGHT PASS(ES) */
1823
1824
if (p_bounces > 0) {
1825
Vector<RD::Uniform> uniforms;
1826
{
1827
{
1828
// Unused.
1829
RD::Uniform u;
1830
u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
1831
u.binding = 0;
1832
u.append_id(light_dest_tex);
1833
uniforms.push_back(u);
1834
}
1835
{
1836
RD::Uniform u;
1837
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1838
u.binding = 1;
1839
u.append_id(light_source_tex);
1840
uniforms.push_back(u);
1841
}
1842
{
1843
RD::Uniform u;
1844
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1845
u.binding = 2;
1846
u.append_id(position_tex);
1847
uniforms.push_back(u);
1848
}
1849
{
1850
RD::Uniform u;
1851
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1852
u.binding = 3;
1853
u.append_id(normal_tex);
1854
uniforms.push_back(u);
1855
}
1856
{
1857
RD::Uniform u;
1858
u.uniform_type = RD::UNIFORM_TYPE_IMAGE;
1859
u.binding = 4;
1860
u.append_id(light_accum_tex);
1861
uniforms.push_back(u);
1862
}
1863
{
1864
RD::Uniform u;
1865
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1866
u.binding = 5;
1867
u.append_id(light_environment_tex);
1868
uniforms.push_back(u);
1869
}
1870
}
1871
1872
RID secondary_uniform_set;
1873
secondary_uniform_set = rd->uniform_set_create(uniforms, compute_shader_secondary, 1);
1874
1875
const int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_pass");
1876
int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);
1877
1878
if (p_step_function) {
1879
if (p_step_function(0.6, RTR("Integrate indirect lighting"), p_bake_userdata, true)) {
1880
FREE_TEXTURES
1881
FREE_BUFFERS
1882
FREE_RASTER_RESOURCES
1883
FREE_COMPUTE_RESOURCES
1884
memdelete(rd);
1885
if (rcd != nullptr) {
1886
memdelete(rcd);
1887
}
1888
return BAKE_ERROR_USER_ABORTED;
1889
}
1890
}
1891
1892
int count = 0;
1893
for (int s = 0; s < atlas_slices; s++) {
1894
push_constant.atlas_slice = s;
1895
1896
for (int i = 0; i < x_regions; i++) {
1897
for (int j = 0; j < y_regions; j++) {
1898
int x = i * max_region_size;
1899
int y = j * max_region_size;
1900
int w = MIN((i + 1) * max_region_size, atlas_size.width) - x;
1901
int h = MIN((j + 1) * max_region_size, atlas_size.height) - y;
1902
1903
push_constant.region_ofs[0] = x;
1904
push_constant.region_ofs[1] = y;
1905
1906
group_size = Vector3i(Math::division_round_up(w, 8), Math::division_round_up(h, 8), 1);
1907
1908
for (int k = 0; k < ray_iterations; k++) {
1909
RD::ComputeListID compute_list = rd->compute_list_begin();
1910
rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_secondary_pipeline);
1911
rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
1912
rd->compute_list_bind_uniform_set(compute_list, secondary_uniform_set, 1);
1913
1914
push_constant.ray_from = k * max_rays;
1915
push_constant.ray_to = MIN((k + 1) * max_rays, int32_t(push_constant.ray_count));
1916
rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
1917
rd->compute_list_dispatch(compute_list, group_size.x, group_size.y, group_size.z);
1918
1919
rd->compute_list_end();
1920
rd->submit();
1921
rd->sync();
1922
1923
count++;
1924
if (p_step_function) {
1925
int total = (atlas_slices * x_regions * y_regions * ray_iterations);
1926
int percent = count * 100 / total;
1927
float p = float(count) / total * 0.1;
1928
if (p_step_function(0.6 + p, vformat(RTR("Integrate indirect lighting %d%%"), percent), p_bake_userdata, false)) {
1929
FREE_TEXTURES
1930
FREE_BUFFERS
1931
FREE_RASTER_RESOURCES
1932
FREE_COMPUTE_RESOURCES
1933
memdelete(rd);
1934
if (rcd != nullptr) {
1935
memdelete(rcd);
1936
}
1937
return BAKE_ERROR_USER_ABORTED;
1938
}
1939
}
1940
}
1941
}
1942
}
1943
}
1944
}
1945
1946
/* LIGHTPROBES */
1947
1948
RID light_probe_buffer;
1949
1950
if (probe_positions.size()) {
1951
light_probe_buffer = rd->storage_buffer_create(sizeof(float) * 4 * 9 * probe_positions.size());
1952
1953
if (p_step_function) {
1954
if (p_step_function(0.7, RTR("Baking light probes"), p_bake_userdata, true)) {
1955
FREE_TEXTURES
1956
FREE_BUFFERS
1957
FREE_RASTER_RESOURCES
1958
FREE_COMPUTE_RESOURCES
1959
if (probe_positions.size() > 0) {
1960
rd->free(light_probe_buffer);
1961
}
1962
memdelete(rd);
1963
if (rcd != nullptr) {
1964
memdelete(rcd);
1965
}
1966
return BAKE_ERROR_USER_ABORTED;
1967
}
1968
}
1969
1970
Vector<RD::Uniform> uniforms;
1971
{
1972
{
1973
RD::Uniform u;
1974
u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
1975
u.binding = 0;
1976
u.append_id(light_probe_buffer);
1977
uniforms.push_back(u);
1978
}
1979
{
1980
RD::Uniform u;
1981
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1982
u.binding = 1;
1983
u.append_id(light_source_tex);
1984
uniforms.push_back(u);
1985
}
1986
{
1987
RD::Uniform u;
1988
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
1989
u.binding = 2;
1990
u.append_id(light_environment_tex);
1991
uniforms.push_back(u);
1992
}
1993
}
1994
RID light_probe_uniform_set = rd->uniform_set_create(uniforms, compute_shader_light_probes, 1);
1995
1996
switch (p_quality) {
1997
case BAKE_QUALITY_LOW: {
1998
push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/low_quality_probe_ray_count");
1999
} break;
2000
case BAKE_QUALITY_MEDIUM: {
2001
push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/medium_quality_probe_ray_count");
2002
} break;
2003
case BAKE_QUALITY_HIGH: {
2004
push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/high_quality_probe_ray_count");
2005
} break;
2006
case BAKE_QUALITY_ULTRA: {
2007
push_constant.ray_count = GLOBAL_GET("rendering/lightmapping/bake_quality/ultra_quality_probe_ray_count");
2008
} break;
2009
}
2010
2011
push_constant.ray_count = CLAMP(push_constant.ray_count, 16u, 8192u);
2012
push_constant.probe_count = probe_positions.size();
2013
2014
int max_rays = GLOBAL_GET("rendering/lightmapping/bake_performance/max_rays_per_probe_pass");
2015
int ray_iterations = Math::division_round_up((int32_t)push_constant.ray_count, max_rays);
2016
2017
for (int i = 0; i < ray_iterations; i++) {
2018
RD::ComputeListID compute_list = rd->compute_list_begin();
2019
rd->compute_list_bind_compute_pipeline(compute_list, compute_shader_light_probes_pipeline);
2020
rd->compute_list_bind_uniform_set(compute_list, compute_base_uniform_set, 0);
2021
rd->compute_list_bind_uniform_set(compute_list, light_probe_uniform_set, 1);
2022
2023
push_constant.ray_from = i * max_rays;
2024
push_constant.ray_to = MIN((i + 1) * max_rays, int32_t(push_constant.ray_count));
2025
rd->compute_list_set_push_constant(compute_list, &push_constant, sizeof(PushConstant));
2026
rd->compute_list_dispatch(compute_list, Math::division_round_up((int)probe_positions.size(), 64), 1, 1);
2027
2028
rd->compute_list_end(); //done
2029
rd->submit();
2030
rd->sync();
2031
2032
if (p_step_function) {
2033
int percent = i * 100 / ray_iterations;
2034
float p = float(i) / ray_iterations * 0.1;
2035
if (p_step_function(0.7 + p, vformat(RTR("Integrating light probes %d%%"), percent), p_bake_userdata, false)) {
2036
FREE_TEXTURES
2037
FREE_BUFFERS
2038
FREE_RASTER_RESOURCES
2039
FREE_COMPUTE_RESOURCES
2040
if (probe_positions.size() > 0) {
2041
rd->free(light_probe_buffer);
2042
}
2043
memdelete(rd);
2044
if (rcd != nullptr) {
2045
memdelete(rcd);
2046
}
2047
return BAKE_ERROR_USER_ABORTED;
2048
}
2049
}
2050
}
2051
}
2052
2053
#if 0
2054
for (int i = 0; i < probe_positions.size(); i++) {
2055
Ref<Image> img = Image::create_empty(6, 4, false, Image::FORMAT_RGB8);
2056
for (int j = 0; j < 6; j++) {
2057
Vector<uint8_t> s = rd->texture_get_data(lightprobe_tex, i * 6 + j);
2058
Ref<Image> img2 = Image::create_from_data(2, 2, false, Image::FORMAT_RGBAF, s);
2059
img2->convert(Image::FORMAT_RGB8);
2060
img->blit_rect(img2, Rect2i(0, 0, 2, 2), Point2i((j % 3) * 2, (j / 3) * 2));
2061
}
2062
img->save_png("res://3_light_probe_" + itos(i) + ".png");
2063
}
2064
#endif
2065
2066
/* DENOISE */
2067
2068
if (p_use_denoiser) {
2069
if (p_step_function) {
2070
if (p_step_function(0.8, RTR("Denoising"), p_bake_userdata, true)) {
2071
FREE_TEXTURES
2072
FREE_BUFFERS
2073
FREE_RASTER_RESOURCES
2074
FREE_COMPUTE_RESOURCES
2075
if (probe_positions.size() > 0) {
2076
rd->free(light_probe_buffer);
2077
}
2078
memdelete(rd);
2079
if (rcd != nullptr) {
2080
memdelete(rcd);
2081
}
2082
return BAKE_ERROR_USER_ABORTED;
2083
}
2084
}
2085
2086
{
2087
BakeError error;
2088
if (denoiser == 1) {
2089
// OIDN (external).
2090
error = _denoise_oidn(rd, light_accum_tex, normal_tex, light_accum_tex, atlas_size, atlas_slices, p_bake_sh, false, oidn_path);
2091
} else {
2092
// JNLM (built-in).
2093
SWAP(light_accum_tex, light_accum_tex2);
2094
error = _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);
2095
}
2096
if (unlikely(error != BAKE_OK)) {
2097
return error;
2098
}
2099
}
2100
2101
if (p_bake_shadowmask) {
2102
BakeError error;
2103
if (denoiser == 1) {
2104
// OIDN (external).
2105
error = _denoise_oidn(rd, shadowmask_tex, normal_tex, shadowmask_tex, atlas_size, atlas_slices, false, true, oidn_path);
2106
} else {
2107
// JNLM (built-in).
2108
SWAP(shadowmask_tex, shadowmask_tex2);
2109
error = _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);
2110
}
2111
if (unlikely(error != BAKE_OK)) {
2112
return error;
2113
}
2114
}
2115
}
2116
2117
/* DILATE */
2118
2119
{
2120
SWAP(light_accum_tex, light_accum_tex2);
2121
BakeError 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));
2122
if (unlikely(error != BAKE_OK)) {
2123
return error;
2124
}
2125
2126
if (p_bake_shadowmask) {
2127
SWAP(shadowmask_tex, shadowmask_tex2);
2128
error = _dilate(rd, compute_shader, compute_base_uniform_set, push_constant, shadowmask_tex2, shadowmask_tex, atlas_size, atlas_slices);
2129
if (unlikely(error != BAKE_OK)) {
2130
return error;
2131
}
2132
}
2133
}
2134
2135
#ifdef DEBUG_TEXTURES
2136
2137
for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
2138
Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
2139
Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
2140
img->save_exr("res://4_light_secondary_" + itos(i) + ".exr", false);
2141
}
2142
#endif
2143
2144
/* BLEND SEAMS */
2145
//shaders
2146
Ref<RDShaderFile> blendseams_shader;
2147
blendseams_shader.instantiate();
2148
err = blendseams_shader->parse_versions_from_text(lm_blendseams_shader_glsl);
2149
if (err != OK) {
2150
FREE_TEXTURES
2151
FREE_BUFFERS
2152
FREE_RASTER_RESOURCES
2153
FREE_COMPUTE_RESOURCES
2154
memdelete(rd);
2155
2156
if (rcd != nullptr) {
2157
memdelete(rcd);
2158
}
2159
2160
blendseams_shader->print_errors("blendseams_shader");
2161
}
2162
ERR_FAIL_COND_V(err != OK, BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
2163
2164
RID blendseams_line_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("lines"));
2165
2166
ERR_FAIL_COND_V(blendseams_line_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
2167
2168
RID blendseams_triangle_raster_shader = rd->shader_create_from_spirv(blendseams_shader->get_spirv_stages("triangles"));
2169
2170
ERR_FAIL_COND_V(blendseams_triangle_raster_shader.is_null(), BAKE_ERROR_LIGHTMAP_CANT_PRE_BAKE_MESHES);
2171
2172
#define FREE_BLENDSEAMS_RESOURCES \
2173
rd->free(blendseams_line_raster_shader); \
2174
rd->free(blendseams_triangle_raster_shader);
2175
2176
{
2177
//pre copy
2178
for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
2179
rd->texture_copy(light_accum_tex, light_accum_tex2, Vector3(), Vector3(), Vector3(atlas_size.width, atlas_size.height, 1), 0, 0, i, i);
2180
}
2181
2182
Vector<RID> framebuffers;
2183
for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
2184
RID slice_tex = rd->texture_create_shared_from_slice(RD::TextureView(), light_accum_tex, i, 0);
2185
Vector<RID> fb;
2186
fb.push_back(slice_tex);
2187
fb.push_back(raster_depth_buffer);
2188
framebuffers.push_back(rd->framebuffer_create(fb));
2189
}
2190
2191
Vector<RD::Uniform> uniforms;
2192
{
2193
{
2194
RD::Uniform u;
2195
u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
2196
u.binding = 0;
2197
u.append_id(light_accum_tex2);
2198
uniforms.push_back(u);
2199
}
2200
}
2201
2202
RID blendseams_raster_uniform = rd->uniform_set_create(uniforms, blendseams_line_raster_shader, 1);
2203
2204
bool debug = false;
2205
RD::PipelineColorBlendState bs = RD::PipelineColorBlendState::create_blend(1);
2206
bs.attachments.write[0].src_alpha_blend_factor = RD::BLEND_FACTOR_ZERO;
2207
bs.attachments.write[0].dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
2208
2209
RD::PipelineDepthStencilState ds;
2210
ds.enable_depth_test = true;
2211
ds.enable_depth_write = true;
2212
ds.depth_compare_operator = RD::COMPARE_OP_LESS; //so it does not render same pixel twice, this avoids wrong blending
2213
2214
RID 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);
2215
RID 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);
2216
2217
uint32_t seam_offset = 0;
2218
uint32_t triangle_offset = 0;
2219
2220
for (int i = 0; i < atlas_slices; i++) {
2221
int subslices = (p_bake_sh ? 4 : 1);
2222
2223
if (slice_seam_count[i] == 0) {
2224
continue;
2225
}
2226
2227
for (int k = 0; k < subslices; k++) {
2228
RasterSeamsPushConstant seams_push_constant;
2229
seams_push_constant.slice = uint32_t(i * subslices + k);
2230
seams_push_constant.debug = debug;
2231
2232
// Store the current subslice in the breadcrumb.
2233
RD::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);
2234
2235
rd->draw_list_bind_uniform_set(draw_list, raster_base_uniform, 0);
2236
rd->draw_list_bind_uniform_set(draw_list, blendseams_raster_uniform, 1);
2237
2238
const int uv_offset_count = 9;
2239
static const Vector3 uv_offsets[uv_offset_count] = {
2240
Vector3(0, 0, 0.5), //using zbuffer, so go inwards-outwards
2241
Vector3(0, 1, 0.2),
2242
Vector3(0, -1, 0.2),
2243
Vector3(1, 0, 0.2),
2244
Vector3(-1, 0, 0.2),
2245
Vector3(-1, -1, 0.1),
2246
Vector3(1, -1, 0.1),
2247
Vector3(1, 1, 0.1),
2248
Vector3(-1, 1, 0.1),
2249
};
2250
2251
/* step 1 use lines to blend the edges */
2252
{
2253
seams_push_constant.base_index = seam_offset;
2254
rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
2255
seams_push_constant.uv_offset[0] = (uv_offsets[0].x - 0.5f) / float(atlas_size.width);
2256
seams_push_constant.uv_offset[1] = (uv_offsets[0].y - 0.5f) / float(atlas_size.height);
2257
seams_push_constant.blend = uv_offsets[0].z;
2258
2259
rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
2260
rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
2261
}
2262
2263
/* step 2 use triangles to mask the interior */
2264
2265
{
2266
seams_push_constant.base_index = triangle_offset;
2267
rd->draw_list_bind_render_pipeline(draw_list, blendseams_triangle_raster_pipeline);
2268
seams_push_constant.blend = 0; //do not draw them, just fill the z-buffer so its used as a mask
2269
2270
rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
2271
rd->draw_list_draw(draw_list, false, 1, slice_triangle_count[i] * 3);
2272
}
2273
/* step 3 blend around the triangle */
2274
2275
rd->draw_list_bind_render_pipeline(draw_list, blendseams_line_raster_pipeline);
2276
2277
for (int j = 1; j < uv_offset_count; j++) {
2278
seams_push_constant.base_index = seam_offset;
2279
seams_push_constant.uv_offset[0] = (uv_offsets[j].x - 0.5f) / float(atlas_size.width);
2280
seams_push_constant.uv_offset[1] = (uv_offsets[j].y - 0.5f) / float(atlas_size.height);
2281
seams_push_constant.blend = uv_offsets[0].z;
2282
2283
rd->draw_list_set_push_constant(draw_list, &seams_push_constant, sizeof(RasterSeamsPushConstant));
2284
rd->draw_list_draw(draw_list, false, 1, slice_seam_count[i] * 4);
2285
}
2286
rd->draw_list_end();
2287
}
2288
seam_offset += slice_seam_count[i];
2289
triangle_offset += slice_triangle_count[i];
2290
}
2291
}
2292
2293
if (p_bake_sh) {
2294
SWAP(light_accum_tex, light_accum_tex2);
2295
BakeError error = _pack_l1(rd, compute_shader, compute_base_uniform_set, push_constant, light_accum_tex2, light_accum_tex, atlas_size, atlas_slices);
2296
if (unlikely(error != BAKE_OK)) {
2297
return error;
2298
}
2299
}
2300
2301
#ifdef DEBUG_TEXTURES
2302
2303
for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
2304
Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
2305
Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
2306
img->save_exr("res://5_blendseams" + itos(i) + ".exr", false);
2307
}
2308
#endif
2309
2310
if (p_step_function) {
2311
p_step_function(0.9, RTR("Retrieving textures"), p_bake_userdata, true);
2312
}
2313
2314
for (int i = 0; i < atlas_slices * (p_bake_sh ? 4 : 1); i++) {
2315
Vector<uint8_t> s = rd->texture_get_data(light_accum_tex, i);
2316
Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBAH, s);
2317
img->convert(Image::FORMAT_RGBH); //remove alpha
2318
lightmap_textures.push_back(img);
2319
}
2320
2321
if (p_bake_shadowmask) {
2322
for (int i = 0; i < atlas_slices; i++) {
2323
Vector<uint8_t> s = rd->texture_get_data(shadowmask_tex, i);
2324
Ref<Image> img = Image::create_from_data(atlas_size.width, atlas_size.height, false, Image::FORMAT_RGBA8, s);
2325
img->convert(Image::FORMAT_R8);
2326
shadowmask_textures.push_back(img);
2327
}
2328
}
2329
2330
if (probe_positions.size() > 0) {
2331
probe_values.resize(probe_positions.size() * 9);
2332
Vector<uint8_t> probe_data = rd->buffer_get_data(light_probe_buffer);
2333
memcpy(probe_values.ptrw(), probe_data.ptr(), probe_data.size());
2334
rd->free(light_probe_buffer);
2335
2336
#ifdef DEBUG_TEXTURES
2337
{
2338
Ref<Image> img2 = Image::create_from_data(probe_values.size(), 1, false, Image::FORMAT_RGBAF, probe_data);
2339
img2->save_exr("res://6_lightprobes.exr", false);
2340
}
2341
#endif
2342
}
2343
2344
FREE_TEXTURES
2345
FREE_BUFFERS
2346
FREE_RASTER_RESOURCES
2347
FREE_COMPUTE_RESOURCES
2348
FREE_BLENDSEAMS_RESOURCES
2349
2350
memdelete(rd);
2351
2352
if (rcd != nullptr) {
2353
memdelete(rcd);
2354
}
2355
2356
return BAKE_OK;
2357
}
2358
2359
int LightmapperRD::get_bake_texture_count() const {
2360
return lightmap_textures.size();
2361
}
2362
2363
Ref<Image> LightmapperRD::get_bake_texture(int p_index) const {
2364
ERR_FAIL_INDEX_V(p_index, lightmap_textures.size(), Ref<Image>());
2365
return lightmap_textures[p_index];
2366
}
2367
2368
int LightmapperRD::get_shadowmask_texture_count() const {
2369
return shadowmask_textures.size();
2370
}
2371
2372
Ref<Image> LightmapperRD::get_shadowmask_texture(int p_index) const {
2373
ERR_FAIL_INDEX_V(p_index, shadowmask_textures.size(), Ref<Image>());
2374
return shadowmask_textures[p_index];
2375
}
2376
2377
int LightmapperRD::get_bake_mesh_count() const {
2378
return mesh_instances.size();
2379
}
2380
2381
Variant LightmapperRD::get_bake_mesh_userdata(int p_index) const {
2382
ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
2383
return mesh_instances[p_index].data.userdata;
2384
}
2385
2386
Rect2 LightmapperRD::get_bake_mesh_uv_scale(int p_index) const {
2387
ERR_FAIL_COND_V(lightmap_textures.is_empty(), Rect2());
2388
Rect2 uv_ofs;
2389
Vector2 atlas_size = Vector2(lightmap_textures[0]->get_width(), lightmap_textures[0]->get_height());
2390
uv_ofs.position = Vector2(mesh_instances[p_index].offset) / atlas_size;
2391
uv_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;
2392
return uv_ofs;
2393
}
2394
2395
int LightmapperRD::get_bake_mesh_texture_slice(int p_index) const {
2396
ERR_FAIL_INDEX_V(p_index, mesh_instances.size(), Variant());
2397
return mesh_instances[p_index].slice;
2398
}
2399
2400
int LightmapperRD::get_bake_probe_count() const {
2401
return probe_positions.size();
2402
}
2403
2404
Vector3 LightmapperRD::get_bake_probe_point(int p_probe) const {
2405
ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Variant());
2406
return Vector3(probe_positions[p_probe].position[0], probe_positions[p_probe].position[1], probe_positions[p_probe].position[2]);
2407
}
2408
2409
Vector<Color> LightmapperRD::get_bake_probe_sh(int p_probe) const {
2410
ERR_FAIL_INDEX_V(p_probe, probe_positions.size(), Vector<Color>());
2411
Vector<Color> ret;
2412
ret.resize(9);
2413
memcpy(ret.ptrw(), &probe_values[p_probe * 9], sizeof(Color) * 9);
2414
return ret;
2415
}
2416
2417
LightmapperRD::LightmapperRD() {
2418
}
2419
2420