1 /*************************************************************************/
2 /* baked_light_baker.cpp */
3 /*************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
9 /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
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 #include "baked_light_baker.h"
31 #include "editor/editor_node.h"
32 #include "editor/editor_settings.h"
33 #include "io/marshalls.h"
34 #include <stdlib.h>
35 #include <cmath>
36
37 void baked_light_baker_add_64f(double *dst, double value);
38 void baked_light_baker_add_64i(int64_t *dst, int64_t value);
39
40 //-separar en 2 testuras?
41 //*mejorar performance y threads
42 //*modos lineales
43 //*saturacion
44
get_uv_normal_bit(const Vector3 & p_vector)45 _FORCE_INLINE_ static uint64_t get_uv_normal_bit(const Vector3 &p_vector) {
46
47 int lat = Math::fast_ftoi(Math::floor(Math::acos(p_vector.dot(Vector3(0, 1, 0))) * 6.0 / Math_PI + 0.5));
48
49 if (lat == 0) {
50 return 60;
51 } else if (lat == 6) {
52 return 61;
53 }
54
55 int lon = Math::fast_ftoi(Math::floor((Math_PI + Math::atan2(p_vector.x, p_vector.z)) * 12.0 / (Math_PI * 2.0) + 0.5)) % 12;
56
57 return lon + (lat - 1) * 12;
58 }
59
get_bit_normal(int p_bit)60 _FORCE_INLINE_ static Vector3 get_bit_normal(int p_bit) {
61
62 if (p_bit == 61) {
63 return Vector3(0, 1, 0);
64 } else if (p_bit == 62) {
65 return Vector3(0, -1, 0);
66 }
67
68 float latang = ((p_bit / 12) + 1) * Math_PI / 6.0;
69
70 Vector2 latv(Math::sin(latang), Math::cos(latang));
71
72 float lonang = ((p_bit % 12) * Math_PI * 2.0 / 12.0) - Math_PI;
73
74 Vector2 lonv(Math::sin(lonang), Math::cos(lonang));
75
76 return Vector3(lonv.x * latv.x, latv.y, lonv.y * latv.x).normalized();
77 }
78
_get_mat_tex(const Ref<Texture> & p_tex)79 BakedLightBaker::MeshTexture *BakedLightBaker::_get_mat_tex(const Ref<Texture> &p_tex) {
80
81 if (!tex_map.has(p_tex)) {
82
83 Ref<ImageTexture> imgtex = p_tex;
84 if (imgtex.is_null())
85 return NULL;
86 Image image = imgtex->get_data();
87 if (image.empty())
88 return NULL;
89
90 if (image.get_format() != Image::FORMAT_RGBA) {
91 if (image.get_format() > Image::FORMAT_INDEXED_ALPHA) {
92 Error err = image.decompress();
93 if (err)
94 return NULL;
95 }
96
97 if (image.get_format() != Image::FORMAT_RGBA)
98 image.convert(Image::FORMAT_RGBA);
99 }
100
101 if (imgtex->get_flags() & Texture::FLAG_CONVERT_TO_LINEAR) {
102 Image copy = image;
103 copy.srgb_to_linear();
104 image = copy;
105 }
106
107 DVector<uint8_t> dvt = image.get_data();
108 DVector<uint8_t>::Read r = dvt.read();
109 MeshTexture mt;
110 mt.tex_w = image.get_width();
111 mt.tex_h = image.get_height();
112 int len = image.get_width() * image.get_height() * 4;
113 mt.tex.resize(len);
114 copymem(mt.tex.ptr(), r.ptr(), len);
115
116 textures.push_back(mt);
117 tex_map[p_tex] = &textures.back()->get();
118 }
119
120 return tex_map[p_tex];
121 }
122
_add_mesh(const Ref<Mesh> & p_mesh,const Ref<Material> & p_mat_override,const Transform & p_xform,int p_baked_texture)123 void BakedLightBaker::_add_mesh(const Ref<Mesh> &p_mesh, const Ref<Material> &p_mat_override, const Transform &p_xform, int p_baked_texture) {
124
125 for (int i = 0; i < p_mesh->get_surface_count(); i++) {
126
127 if (p_mesh->surface_get_primitive_type(i) != Mesh::PRIMITIVE_TRIANGLES)
128 continue;
129 Ref<Material> mat = p_mat_override.is_valid() ? p_mat_override : p_mesh->surface_get_material(i);
130
131 MeshMaterial *matptr = NULL;
132 int baked_tex = p_baked_texture;
133
134 if (mat.is_valid()) {
135
136 if (!mat_map.has(mat)) {
137
138 MeshMaterial mm;
139
140 Ref<FixedMaterial> fm = mat;
141 if (fm.is_valid()) {
142 //fixed route
143 mm.diffuse.color = fm->get_parameter(FixedMaterial::PARAM_DIFFUSE);
144 if (linear_color)
145 mm.diffuse.color = mm.diffuse.color.to_linear();
146 mm.diffuse.tex = _get_mat_tex(fm->get_texture(FixedMaterial::PARAM_DIFFUSE));
147 mm.specular.color = fm->get_parameter(FixedMaterial::PARAM_SPECULAR);
148 if (linear_color)
149 mm.specular.color = mm.specular.color.to_linear();
150
151 mm.specular.tex = _get_mat_tex(fm->get_texture(FixedMaterial::PARAM_SPECULAR));
152 } else {
153
154 mm.diffuse.color = Color(1, 1, 1, 1);
155 mm.diffuse.tex = NULL;
156 mm.specular.color = Color(0, 0, 0, 1);
157 mm.specular.tex = NULL;
158 }
159
160 materials.push_back(mm);
161 mat_map[mat] = &materials.back()->get();
162 }
163
164 matptr = mat_map[mat];
165 }
166
167 int facecount = 0;
168
169 if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
170
171 facecount = p_mesh->surface_get_array_index_len(i);
172 } else {
173
174 facecount = p_mesh->surface_get_array_len(i);
175 }
176
177 ERR_CONTINUE((facecount == 0 || (facecount % 3) != 0));
178
179 facecount /= 3;
180
181 int tbase = triangles.size();
182 triangles.resize(facecount + tbase);
183
184 Array a = p_mesh->surface_get_arrays(i);
185
186 DVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX];
187 DVector<Vector3>::Read vr = vertices.read();
188 DVector<Vector2> uv;
189 DVector<Vector2>::Read uvr;
190 DVector<Vector2> uv2;
191 DVector<Vector2>::Read uv2r;
192 DVector<Vector3> normal;
193 DVector<Vector3>::Read normalr;
194 bool read_uv = false;
195 bool read_normal = false;
196
197 if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_TEX_UV) {
198
199 uv = a[Mesh::ARRAY_TEX_UV];
200 uvr = uv.read();
201 read_uv = true;
202
203 if (mat.is_valid() && mat->get_flag(Material::FLAG_LIGHTMAP_ON_UV2) && p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_TEX_UV2) {
204
205 uv2 = a[Mesh::ARRAY_TEX_UV2];
206 uv2r = uv2.read();
207
208 } else {
209 uv2r = uv.read();
210 if (baked_light->get_transfer_lightmaps_only_to_uv2()) {
211 baked_tex = -1;
212 }
213 }
214 }
215
216 if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_NORMAL) {
217
218 normal = a[Mesh::ARRAY_NORMAL];
219 normalr = normal.read();
220 read_normal = true;
221 }
222
223 Matrix3 normal_xform = p_xform.basis.inverse().transposed();
224
225 if (p_mesh->surface_get_format(i) & Mesh::ARRAY_FORMAT_INDEX) {
226
227 DVector<int> indices = a[Mesh::ARRAY_INDEX];
228 DVector<int>::Read ir = indices.read();
229
230 for (int i = 0; i < facecount; i++) {
231 Triangle &t = triangles[tbase + i];
232 t.vertices[0] = p_xform.xform(vr[ir[i * 3 + 0]]);
233 t.vertices[1] = p_xform.xform(vr[ir[i * 3 + 1]]);
234 t.vertices[2] = p_xform.xform(vr[ir[i * 3 + 2]]);
235 t.material = matptr;
236 t.baked_texture = baked_tex;
237 if (read_uv) {
238
239 t.uvs[0] = uvr[ir[i * 3 + 0]];
240 t.uvs[1] = uvr[ir[i * 3 + 1]];
241 t.uvs[2] = uvr[ir[i * 3 + 2]];
242
243 t.bake_uvs[0] = uv2r[ir[i * 3 + 0]];
244 t.bake_uvs[1] = uv2r[ir[i * 3 + 1]];
245 t.bake_uvs[2] = uv2r[ir[i * 3 + 2]];
246 }
247 if (read_normal) {
248
249 t.normals[0] = normal_xform.xform(normalr[ir[i * 3 + 0]]).normalized();
250 t.normals[1] = normal_xform.xform(normalr[ir[i * 3 + 1]]).normalized();
251 t.normals[2] = normal_xform.xform(normalr[ir[i * 3 + 2]]).normalized();
252 }
253 }
254
255 } else {
256
257 for (int i = 0; i < facecount; i++) {
258 Triangle &t = triangles[tbase + i];
259 t.vertices[0] = p_xform.xform(vr[i * 3 + 0]);
260 t.vertices[1] = p_xform.xform(vr[i * 3 + 1]);
261 t.vertices[2] = p_xform.xform(vr[i * 3 + 2]);
262 t.material = matptr;
263 t.baked_texture = baked_tex;
264 if (read_uv) {
265
266 t.uvs[0] = uvr[i * 3 + 0];
267 t.uvs[1] = uvr[i * 3 + 1];
268 t.uvs[2] = uvr[i * 3 + 2];
269
270 t.bake_uvs[0] = uv2r[i * 3 + 0];
271 t.bake_uvs[1] = uv2r[i * 3 + 1];
272 t.bake_uvs[2] = uv2r[i * 3 + 2];
273 }
274 if (read_normal) {
275
276 t.normals[0] = normal_xform.xform(normalr[i * 3 + 0]).normalized();
277 t.normals[1] = normal_xform.xform(normalr[i * 3 + 1]).normalized();
278 t.normals[2] = normal_xform.xform(normalr[i * 3 + 2]).normalized();
279 }
280 }
281 }
282 }
283 }
284
_parse_geometry(Node * p_node)285 void BakedLightBaker::_parse_geometry(Node *p_node) {
286
287 if (p_node->cast_to<MeshInstance>()) {
288
289 MeshInstance *meshi = p_node->cast_to<MeshInstance>();
290 Ref<Mesh> mesh = meshi->get_mesh();
291 if (mesh.is_valid()) {
292 _add_mesh(mesh, meshi->get_material_override(), base_inv * meshi->get_global_transform(), meshi->get_baked_light_texture_id());
293 }
294 } else if (p_node->cast_to<Light>()) {
295
296 Light *dl = p_node->cast_to<Light>();
297
298 if (dl->get_bake_mode() != Light::BAKE_MODE_DISABLED) {
299
300 LightData dirl;
301 dirl.type = VS::LightType(dl->get_light_type());
302 dirl.diffuse = dl->get_color(DirectionalLight::COLOR_DIFFUSE);
303 dirl.specular = dl->get_color(DirectionalLight::COLOR_SPECULAR);
304 if (linear_color)
305 dirl.diffuse = dirl.diffuse.to_linear();
306 if (linear_color)
307 dirl.specular = dirl.specular.to_linear();
308
309 dirl.energy = dl->get_parameter(DirectionalLight::PARAM_ENERGY);
310 dirl.pos = dl->get_global_transform().origin;
311 dirl.up = dl->get_global_transform().basis.get_axis(1).normalized();
312 dirl.left = dl->get_global_transform().basis.get_axis(0).normalized();
313 dirl.dir = -dl->get_global_transform().basis.get_axis(2).normalized();
314 dirl.spot_angle = dl->get_parameter(DirectionalLight::PARAM_SPOT_ANGLE);
315 dirl.spot_attenuation = dl->get_parameter(DirectionalLight::PARAM_SPOT_ATTENUATION);
316 dirl.attenuation = dl->get_parameter(DirectionalLight::PARAM_ATTENUATION);
317 dirl.darkening = dl->get_parameter(DirectionalLight::PARAM_SHADOW_DARKENING);
318 dirl.radius = dl->get_parameter(DirectionalLight::PARAM_RADIUS);
319 dirl.bake_direct = dl->get_bake_mode() == Light::BAKE_MODE_FULL;
320 dirl.rays_thrown = 0;
321 dirl.bake_shadow = dl->get_bake_mode() == Light::BAKE_MODE_INDIRECT_AND_SHADOWS;
322 lights.push_back(dirl);
323 }
324
325 } else if (p_node->cast_to<Spatial>()) {
326
327 Spatial *sp = p_node->cast_to<Spatial>();
328
329 Array arr = p_node->call("_get_baked_light_meshes");
330 for (int i = 0; i < arr.size(); i += 2) {
331
332 Transform xform = arr[i];
333 Ref<Mesh> mesh = arr[i + 1];
334 _add_mesh(mesh, Ref<Material>(), base_inv * (sp->get_global_transform() * xform));
335 }
336 }
337
338 for (int i = 0; i < p_node->get_child_count(); i++) {
339
340 _parse_geometry(p_node->get_child(i));
341 }
342 }
343
_fix_lights()344 void BakedLightBaker::_fix_lights() {
345
346 total_light_area = 0;
347 for (int i = 0; i < lights.size(); i++) {
348
349 LightData &dl = lights[i];
350
351 switch (dl.type) {
352 case VS::LIGHT_DIRECTIONAL: {
353
354 float up_max = -1e10;
355 float dir_max = -1e10;
356 float left_max = -1e10;
357 float up_min = 1e10;
358 float dir_min = 1e10;
359 float left_min = 1e10;
360
361 for (int j = 0; j < triangles.size(); j++) {
362
363 for (int k = 0; k < 3; k++) {
364
365 Vector3 v = triangles[j].vertices[k];
366
367 float up_d = dl.up.dot(v);
368 float dir_d = dl.dir.dot(v);
369 float left_d = dl.left.dot(v);
370
371 if (up_d > up_max)
372 up_max = up_d;
373 if (up_d < up_min)
374 up_min = up_d;
375
376 if (left_d > left_max)
377 left_max = left_d;
378 if (left_d < left_min)
379 left_min = left_d;
380
381 if (dir_d > dir_max)
382 dir_max = dir_d;
383 if (dir_d < dir_min)
384 dir_min = dir_d;
385 }
386 }
387
388 //make a center point, then the upvector and leftvector
389 dl.pos = dl.left * (left_max + left_min) * 0.5 + dl.up * (up_max + up_min) * 0.5 + dl.dir * (dir_min - (dir_max - dir_min));
390 dl.left *= (left_max - left_min) * 0.5;
391 dl.up *= (up_max - up_min) * 0.5;
392 dl.length = (dir_max - dir_min) * 10; //arbitrary number to keep it in scale
393 dl.area = dl.left.length() * 2 * dl.up.length() * 2;
394 dl.constant = 1.0 / dl.area;
395 } break;
396 case VS::LIGHT_OMNI:
397 case VS::LIGHT_SPOT: {
398
399 dl.attenuation_table.resize(ATTENUATION_CURVE_LEN);
400 for (int j = 0; j < ATTENUATION_CURVE_LEN; j++) {
401 dl.attenuation_table[j] = 1.0 - Math::pow(j / float(ATTENUATION_CURVE_LEN), dl.attenuation);
402 float falloff = j * dl.radius / float(ATTENUATION_CURVE_LEN);
403 if (falloff == 0)
404 falloff = 0.000001;
405 float intensity = 4 * Math_PI * (falloff * falloff);
406 //dl.attenuation_table[j]*=falloff*falloff;
407 dl.attenuation_table[j] *= 1.0 / (3.0 / intensity);
408 }
409 if (dl.type == VS::LIGHT_OMNI) {
410
411 dl.area = 4.0 * Math_PI * pow(dl.radius, 2.0f);
412 dl.constant = 1.0 / 3.5;
413 } else {
414
415 float r = Math::tan(Math::deg2rad(dl.spot_angle)) * dl.radius;
416 float c = 1.0 - (Math::deg2rad(dl.spot_angle) * 0.5 + 0.5);
417 dl.constant = 1.0 / 3.5;
418 dl.constant *= 1.0 / c;
419
420 dl.area = Math_PI * r * r * c;
421 }
422
423 } break;
424 }
425
426 total_light_area += dl.area;
427 }
428 }
429
_parse_bvh(BVH ** p_children,int p_size,int p_depth,int & max_depth)430 BakedLightBaker::BVH *BakedLightBaker::_parse_bvh(BVH **p_children, int p_size, int p_depth, int &max_depth) {
431
432 if (p_depth > max_depth) {
433 max_depth = p_depth;
434 }
435
436 if (p_size == 1) {
437
438 return p_children[0];
439 } else if (p_size == 0) {
440
441 return NULL;
442 }
443
444 AABB aabb;
445 aabb = p_children[0]->aabb;
446 for (int i = 1; i < p_size; i++) {
447
448 aabb.merge_with(p_children[i]->aabb);
449 }
450
451 int li = aabb.get_longest_axis_index();
452
453 switch (li) {
454
455 case Vector3::AXIS_X: {
456 SortArray<BVH *, BVHCmpX> sort_x;
457 sort_x.nth_element(0, p_size, p_size / 2, p_children);
458 //sort_x.sort(&p_bb[p_from],p_size);
459 } break;
460 case Vector3::AXIS_Y: {
461 SortArray<BVH *, BVHCmpY> sort_y;
462 sort_y.nth_element(0, p_size, p_size / 2, p_children);
463 //sort_y.sort(&p_bb[p_from],p_size);
464 } break;
465 case Vector3::AXIS_Z: {
466 SortArray<BVH *, BVHCmpZ> sort_z;
467 sort_z.nth_element(0, p_size, p_size / 2, p_children);
468 //sort_z.sort(&p_bb[p_from],p_size);
469
470 } break;
471 }
472
473 BVH *left = _parse_bvh(p_children, p_size / 2, p_depth + 1, max_depth);
474 BVH *right = _parse_bvh(&p_children[p_size / 2], p_size - p_size / 2, p_depth + 1, max_depth);
475
476 BVH *_new = memnew(BVH);
477 _new->aabb = aabb;
478 _new->center = aabb.pos + aabb.size * 0.5;
479 _new->children[0] = left;
480 _new->children[1] = right;
481 _new->leaf = NULL;
482
483 return _new;
484 }
485
_make_bvh()486 void BakedLightBaker::_make_bvh() {
487
488 Vector<BVH *> bases;
489 bases.resize(triangles.size());
490 int max_depth = 0;
491 for (int i = 0; i < triangles.size(); i++) {
492 bases[i] = memnew(BVH);
493 bases[i]->leaf = &triangles[i];
494 bases[i]->aabb.pos = triangles[i].vertices[0];
495 bases[i]->aabb.expand_to(triangles[i].vertices[1]);
496 bases[i]->aabb.expand_to(triangles[i].vertices[2]);
497 triangles[i].aabb = bases[i]->aabb;
498 bases[i]->center = bases[i]->aabb.pos + bases[i]->aabb.size * 0.5;
499 }
500
501 bvh = _parse_bvh(bases.ptr(), bases.size(), 1, max_depth);
502
503 ray_stack = memnew_arr(uint32_t, max_depth);
504 bvh_stack = memnew_arr(BVH *, max_depth);
505
506 bvh_depth = max_depth;
507 }
508
_octree_insert(int p_octant,Triangle * p_triangle,int p_depth)509 void BakedLightBaker::_octree_insert(int p_octant, Triangle *p_triangle, int p_depth) {
510
511 uint32_t *stack = octant_stack;
512 uint32_t *ptr_stack = octantptr_stack;
513 Octant *octants = octant_pool.ptr();
514
515 stack[0] = 0;
516 ptr_stack[0] = 0;
517
518 int stack_pos = 0;
519
520 while (true) {
521
522 Octant *octant = &octants[ptr_stack[stack_pos]];
523 if (stack[stack_pos] < 8) {
524
525 int i = stack[stack_pos];
526 stack[stack_pos]++;
527
528 //fit_aabb=fit_aabb.grow(bvh->aabb.size.x*0.0001);
529
530 int child_idx = octant->children[i];
531 bool encloses;
532 if (!child_idx) {
533
534 AABB aabb = octant->aabb;
535 aabb.size *= 0.5;
536 if (i & 1)
537 aabb.pos.x += aabb.size.x;
538 if (i & 2)
539 aabb.pos.y += aabb.size.y;
540 if (i & 4)
541 aabb.pos.z += aabb.size.z;
542
543 aabb.grow_by(cell_size * octree_extra_margin);
544 if (!aabb.intersects(p_triangle->aabb))
545 continue;
546 encloses = aabb.grow(cell_size * -octree_extra_margin * 2.0).encloses(p_triangle->aabb);
547 if (!encloses && !Face3(p_triangle->vertices[0], p_triangle->vertices[1], p_triangle->vertices[2]).intersects_aabb2(aabb))
548 continue;
549 } else {
550
551 Octant *child = &octants[child_idx];
552 AABB aabb = child->aabb;
553 aabb.grow_by(cell_size * octree_extra_margin);
554 if (!aabb.intersects(p_triangle->aabb))
555 continue;
556 encloses = aabb.grow(cell_size * -octree_extra_margin * 2.0).encloses(p_triangle->aabb);
557 if (!encloses && !Face3(p_triangle->vertices[0], p_triangle->vertices[1], p_triangle->vertices[2]).intersects_aabb2(aabb))
558 continue;
559 }
560
561 if (encloses)
562 stack[stack_pos] = 8; // quick and dirty opt
563
564 if (!child_idx) {
565
566 if (octant_pool_size == octant_pool.size()) {
567 octant_pool.resize(octant_pool_size + OCTANT_POOL_CHUNK);
568 octants = octant_pool.ptr();
569 octant = &octants[ptr_stack[stack_pos]];
570 }
571 child_idx = octant_pool_size++;
572 octant->children[i] = child_idx;
573 Octant *child = &octants[child_idx];
574
575 child->aabb = octant->aabb;
576 child->texture_x = 0;
577 child->texture_y = 0;
578
579 child->aabb.size *= 0.5;
580 if (i & 1)
581 child->aabb.pos.x += child->aabb.size.x;
582 if (i & 2)
583 child->aabb.pos.y += child->aabb.size.y;
584 if (i & 4)
585 child->aabb.pos.z += child->aabb.size.z;
586
587 child->full_accum[0] = 0;
588 child->full_accum[1] = 0;
589 child->full_accum[2] = 0;
590 child->sampler_ofs = 0;
591
592 if (stack_pos == octree_depth - 1) {
593 child->leaf = true;
594 child->offset[0] = child->aabb.pos.x + child->aabb.size.x * 0.5;
595 child->offset[1] = child->aabb.pos.y + child->aabb.size.y * 0.5;
596 child->offset[2] = child->aabb.pos.z + child->aabb.size.z * 0.5;
597 child->next_leaf = leaf_list;
598
599 for (int ci = 0; ci < 8; ci++) {
600 child->normal_accum[ci][0] = 0;
601 child->normal_accum[ci][1] = 0;
602 child->normal_accum[ci][2] = 0;
603 }
604
605 child->bake_neighbour = 0;
606 child->first_neighbour = true;
607 leaf_list = child_idx;
608 cell_count++;
609
610 for (int ci = 0; ci < 8; ci++) {
611 child->light_accum[ci][0] = 0;
612 child->light_accum[ci][1] = 0;
613 child->light_accum[ci][2] = 0;
614 }
615
616 child->parent = ptr_stack[stack_pos];
617
618 } else {
619
620 child->leaf = false;
621 for (int j = 0; j < 8; j++) {
622 child->children[j] = 0;
623 }
624 }
625 }
626
627 if (!octants[child_idx].leaf) {
628 stack_pos++;
629 stack[stack_pos] = 0;
630 ptr_stack[stack_pos] = child_idx;
631 } else {
632
633 Octant *child = &octants[child_idx];
634
635 Vector3 n = Plane(p_triangle->vertices[0], p_triangle->vertices[1], p_triangle->vertices[2]).normal;
636
637 for (int ci = 0; ci < 8; ci++) {
638
639 Vector3 pos = child->aabb.pos;
640
641 if (ci & 1)
642 pos.x += child->aabb.size.x;
643 if (ci & 2)
644 pos.y += child->aabb.size.y;
645 if (ci & 4)
646 pos.z += child->aabb.size.z;
647
648 pos.x = floor((pos.x + cell_size * 0.5) / cell_size);
649 pos.y = floor((pos.y + cell_size * 0.5) / cell_size);
650 pos.z = floor((pos.z + cell_size * 0.5) / cell_size);
651
652 {
653 Map<Vector3, Vector3>::Element *E = endpoint_normal.find(pos);
654 if (!E) {
655 endpoint_normal[pos] = n;
656 } else {
657 E->get() += n;
658 }
659 }
660
661 {
662
663 uint64_t bit = get_uv_normal_bit(n);
664
665 Map<Vector3, uint64_t>::Element *E = endpoint_normal_bits.find(pos);
666 if (!E) {
667 endpoint_normal_bits[pos] = (1 << bit);
668 } else {
669 E->get() |= (1 << bit);
670 }
671 }
672 }
673 }
674
675 } else {
676 stack_pos--;
677 if (stack_pos < 0)
678 break;
679 }
680 }
681 }
682
_make_octree()683 void BakedLightBaker::_make_octree() {
684
685 AABB base = bvh->aabb;
686 float lal = base.get_longest_axis_size();
687 //must be square because we want square blocks
688 base.size.x = lal;
689 base.size.y = lal;
690 base.size.z = lal;
691 base.grow_by(lal * 0.001); //for precision
692 octree_aabb = base;
693
694 cell_size = base.size.x;
695 for (int i = 0; i < octree_depth; i++)
696 cell_size /= 2.0;
697 octant_stack = memnew_arr(uint32_t, octree_depth * 2);
698 octantptr_stack = memnew_arr(uint32_t, octree_depth * 2);
699
700 octant_pool.resize(OCTANT_POOL_CHUNK);
701 octant_pool_size = 1;
702 Octant *root = octant_pool.ptr();
703 root->leaf = false;
704 root->aabb = octree_aabb;
705 root->parent = -1;
706 for (int i = 0; i < 8; i++)
707 root->children[i] = 0;
708
709 EditorProgress ep("bake_octree", vformat(TTR("Parsing %d Triangles:"), triangles.size()), triangles.size());
710
711 for (int i = 0; i < triangles.size(); i++) {
712
713 _octree_insert(0, &triangles[i], octree_depth - 1);
714 if ((i % 1000) == 0) {
715
716 ep.step(TTR("Triangle #") + itos(i), i);
717 }
718 }
719
720 {
721 uint32_t oct_idx = leaf_list;
722 Octant *octants = octant_pool.ptr();
723 while (oct_idx) {
724
725 BakedLightBaker::Octant *oct = &octants[oct_idx];
726 for (int ci = 0; ci < 8; ci++) {
727
728 Vector3 pos = oct->aabb.pos;
729
730 if (ci & 1)
731 pos.x += oct->aabb.size.x;
732 if (ci & 2)
733 pos.y += oct->aabb.size.y;
734 if (ci & 4)
735 pos.z += oct->aabb.size.z;
736
737 pos.x = floor((pos.x + cell_size * 0.5) / cell_size);
738 pos.y = floor((pos.y + cell_size * 0.5) / cell_size);
739 pos.z = floor((pos.z + cell_size * 0.5) / cell_size);
740
741 {
742 Map<Vector3, Vector3>::Element *E = endpoint_normal.find(pos);
743 if (!E) {
744 //?
745 print_line("lolwut?");
746 } else {
747 Vector3 n = E->get().normalized();
748 oct->normal_accum[ci][0] = n.x;
749 oct->normal_accum[ci][1] = n.y;
750 oct->normal_accum[ci][2] = n.z;
751 }
752 }
753
754 {
755
756 Map<Vector3, uint64_t>::Element *E = endpoint_normal_bits.find(pos);
757 if (!E) {
758 //?
759 print_line("lolwut?");
760 } else {
761
762 float max_aper = 0;
763 for (uint64_t i = 0; i < 62; i++) {
764
765 if (!(E->get() & (1 << i)))
766 continue;
767 Vector3 ang_i = get_bit_normal(i);
768
769 for (uint64_t j = 0; j < 62; j++) {
770
771 if (i == j)
772 continue;
773 if (!(E->get() & (1 << j)))
774 continue;
775 Vector3 ang_j = get_bit_normal(j);
776 float ang = Math::acos(ang_i.dot(ang_j));
777 if (ang > max_aper)
778 max_aper = ang;
779 }
780 }
781 if (max_aper > 0.75 * Math_PI) {
782 //angle too wide prevent problems and forget
783 oct->normal_accum[ci][0] = 0;
784 oct->normal_accum[ci][1] = 0;
785 oct->normal_accum[ci][2] = 0;
786 }
787 }
788 }
789 }
790
791 oct_idx = oct->next_leaf;
792 }
793 }
794 }
795
_plot_light(ThreadStack & thread_stack,const Vector3 & p_plot_pos,const AABB & p_plot_aabb,const Color & p_light,const Color & p_tint_light,bool p_only_full,const Plane & p_plane)796 void BakedLightBaker::_plot_light(ThreadStack &thread_stack, const Vector3 &p_plot_pos, const AABB &p_plot_aabb, const Color &p_light, const Color &p_tint_light, bool p_only_full, const Plane &p_plane) {
797
798 //stackless version
799
800 uint32_t *stack = thread_stack.octant_stack;
801 uint32_t *ptr_stack = thread_stack.octantptr_stack;
802 Octant *octants = octant_pool.ptr();
803
804 stack[0] = 0;
805 ptr_stack[0] = 0;
806
807 int stack_pos = 0;
808
809 while (true) {
810
811 Octant &octant = octants[ptr_stack[stack_pos]];
812
813 if (stack[stack_pos] == 0) {
814
815 Vector3 pos = octant.aabb.pos + octant.aabb.size * 0.5;
816 float md = 1 << (octree_depth - stack_pos);
817 float r = cell_size * plot_size * md;
818 float div = 1.0 / (md * md * md);
819 //div=1.0;
820
821 float d = p_plot_pos.distance_to(pos);
822
823 if ((p_plane.distance_to(pos) > -cell_size * 1.75 * md) && d <= r) {
824
825 float intensity = 1.0 - (d / r) * (d / r); //not gauss but..
826
827 baked_light_baker_add_64f(&octant.full_accum[0], p_tint_light.r * intensity * div);
828 baked_light_baker_add_64f(&octant.full_accum[1], p_tint_light.g * intensity * div);
829 baked_light_baker_add_64f(&octant.full_accum[2], p_tint_light.b * intensity * div);
830 }
831 }
832
833 if (octant.leaf) {
834
835 //if (p_plane.normal.dot(octant.aabb.get_support(p_plane.normal)) < p_plane.d-CMP_EPSILON) { //octants behind are no go
836
837 if (!p_only_full) {
838 float r = cell_size * plot_size;
839 for (int i = 0; i < 8; i++) {
840 Vector3 pos = octant.aabb.pos;
841 if (i & 1)
842 pos.x += octant.aabb.size.x;
843 if (i & 2)
844 pos.y += octant.aabb.size.y;
845 if (i & 4)
846 pos.z += octant.aabb.size.z;
847
848 float d = p_plot_pos.distance_to(pos);
849
850 if ((p_plane.distance_to(pos) > -cell_size * 1.75) && d <= r) {
851
852 float intensity = 1.0 - (d / r) * (d / r); //not gauss but..
853 if (edge_damp > 0) {
854 Vector3 normal = Vector3(octant.normal_accum[i][0], octant.normal_accum[i][1], octant.normal_accum[i][2]);
855 if (normal.x > 0 || normal.y > 0 || normal.z > 0) {
856
857 float damp = Math::abs(p_plane.normal.dot(normal));
858 intensity *= pow(damp, edge_damp);
859 }
860 }
861
862 //intensity*=1.0-Math::abs(p_plane.distance_to(pos))/(plot_size*cell_size);
863 //intensity = Math::cos(d*Math_PI*0.5/r);
864
865 baked_light_baker_add_64f(&octant.light_accum[i][0], p_light.r * intensity);
866 baked_light_baker_add_64f(&octant.light_accum[i][1], p_light.g * intensity);
867 baked_light_baker_add_64f(&octant.light_accum[i][2], p_light.b * intensity);
868 }
869 }
870 }
871
872 stack_pos--;
873 } else if (stack[stack_pos] < 8) {
874
875 int i = stack[stack_pos];
876 stack[stack_pos]++;
877
878 if (!octant.children[i]) {
879 continue;
880 }
881
882 Octant &child = octants[octant.children[i]];
883
884 if (!child.aabb.intersects(p_plot_aabb))
885 continue;
886
887 if (child.aabb.encloses(p_plot_aabb)) {
888 stack[stack_pos] = 8; //don't test the rest
889 }
890
891 stack_pos++;
892 stack[stack_pos] = 0;
893 ptr_stack[stack_pos] = octant.children[i];
894 } else {
895 stack_pos--;
896 if (stack_pos < 0)
897 break;
898 }
899 }
900 }
901
_throw_ray(ThreadStack & thread_stack,bool p_bake_direct,const Vector3 & p_begin,const Vector3 & p_end,float p_rest,const Color & p_light,float * p_att_curve,float p_att_pos,int p_att_curve_len,int p_bounces,bool p_first_bounce,bool p_only_dist)902 float BakedLightBaker::_throw_ray(ThreadStack &thread_stack, bool p_bake_direct, const Vector3 &p_begin, const Vector3 &p_end, float p_rest, const Color &p_light, float *p_att_curve, float p_att_pos, int p_att_curve_len, int p_bounces, bool p_first_bounce, bool p_only_dist) {
903
904 uint32_t *stack = thread_stack.ray_stack;
905 BVH **bstack = thread_stack.bvh_stack;
906
907 enum {
908 TEST_AABB_BIT = 0,
909 VISIT_LEFT_BIT = 1,
910 VISIT_RIGHT_BIT = 2,
911 VISIT_DONE_BIT = 3,
912
913 };
914
915 Vector3 n = (p_end - p_begin);
916 float len = n.length();
917 if (len == 0)
918 return 0;
919 n /= len;
920
921 real_t d = 1e10;
922 bool inters = false;
923 Vector3 r_normal;
924 Vector3 r_point;
925 Vector3 end = p_end;
926
927 Triangle *triangle = NULL;
928
929 //for(int i=0;i<max_depth;i++)
930 // stack[i]=0;
931
932 int level = 0;
933 //AABB ray_aabb;
934 //ray_aabb.pos=p_begin;
935 //ray_aabb.expand_to(p_end);
936
937 bstack[0] = bvh;
938 stack[0] = TEST_AABB_BIT;
939
940 while (true) {
941
942 uint32_t mode = stack[level];
943 const BVH &b = *bstack[level];
944 bool done = false;
945
946 switch (mode) {
947 case TEST_AABB_BIT: {
948
949 if (b.leaf) {
950
951 Face3 f3(b.leaf->vertices[0], b.leaf->vertices[1], b.leaf->vertices[2]);
952
953 Vector3 res;
954
955 if (f3.intersects_segment(p_begin, end, &res)) {
956
957 float nd = n.dot(res);
958 if (nd < d) {
959
960 d = nd;
961 r_point = res;
962 end = res;
963 len = (p_begin - end).length();
964 r_normal = f3.get_plane().get_normal();
965 triangle = b.leaf;
966 inters = true;
967 }
968 }
969
970 stack[level] = VISIT_DONE_BIT;
971 } else {
972
973 bool valid = b.aabb.smits_intersect_ray(p_begin, n, 0, len);
974 //bool valid = b.aabb.intersects_segment(p_begin,p_end);
975 // bool valid = b.aabb.intersects(ray_aabb);
976
977 if (!valid) {
978
979 stack[level] = VISIT_DONE_BIT;
980
981 } else {
982
983 stack[level] = VISIT_LEFT_BIT;
984 }
985 }
986 }
987 continue;
988 case VISIT_LEFT_BIT: {
989
990 stack[level] = VISIT_RIGHT_BIT;
991 bstack[level + 1] = b.children[0];
992 stack[level + 1] = TEST_AABB_BIT;
993 level++;
994 }
995 continue;
996 case VISIT_RIGHT_BIT: {
997
998 stack[level] = VISIT_DONE_BIT;
999 bstack[level + 1] = b.children[1];
1000 stack[level + 1] = TEST_AABB_BIT;
1001 level++;
1002 }
1003 continue;
1004 case VISIT_DONE_BIT: {
1005
1006 if (level == 0) {
1007 done = true;
1008 break;
1009 } else
1010 level--;
1011 }
1012 continue;
1013 }
1014
1015 if (done)
1016 break;
1017 }
1018
1019 if (inters) {
1020
1021 if (p_only_dist) {
1022
1023 return p_begin.distance_to(r_point);
1024 }
1025
1026 //should check if there is normals first
1027 Vector2 uv;
1028 if (true) {
1029
1030 triangle->get_uv_and_normal(r_point, uv, r_normal);
1031
1032 } else {
1033 }
1034
1035 if (n.dot(r_normal) > 0)
1036 return -1;
1037
1038 if (n.dot(r_normal) > 0)
1039 r_normal = -r_normal;
1040
1041 //ok...
1042 Color diffuse_at_point(0.8, 0.8, 0.8);
1043 Color specular_at_point(0.0, 0.0, 0.0);
1044
1045 float dist = p_begin.distance_to(r_point);
1046
1047 AABB aabb;
1048 aabb.pos = r_point;
1049 aabb.pos -= Vector3(1, 1, 1) * cell_size * plot_size;
1050 aabb.size = Vector3(2, 2, 2) * cell_size * plot_size;
1051
1052 Color res_light = p_light;
1053 float att = 1.0;
1054 float dp = (1.0 - normal_damp) * n.dot(-r_normal) + normal_damp;
1055
1056 if (p_att_curve) {
1057
1058 p_att_pos += dist;
1059 int cpos = Math::fast_ftoi((p_att_pos / p_att_curve_len) * ATTENUATION_CURVE_LEN);
1060 cpos = CLAMP(cpos, 0, ATTENUATION_CURVE_LEN - 1);
1061 att = p_att_curve[cpos];
1062 }
1063
1064 res_light.r *= dp;
1065 res_light.g *= dp;
1066 res_light.b *= dp;
1067
1068 //light is plotted before multiplication with diffuse, this way
1069 //the multiplication can happen with more detail in the shader
1070
1071 if (triangle->material) {
1072
1073 //triangle->get_uv(r_point);
1074
1075 diffuse_at_point = triangle->material->diffuse.get_color(uv);
1076 specular_at_point = triangle->material->specular.get_color(uv);
1077 }
1078
1079 diffuse_at_point.r = res_light.r * diffuse_at_point.r;
1080 diffuse_at_point.g = res_light.g * diffuse_at_point.g;
1081 diffuse_at_point.b = res_light.b * diffuse_at_point.b;
1082
1083 float ret = 1e6;
1084
1085 if (p_bounces > 0) {
1086
1087 p_rest -= dist;
1088 if (p_rest < CMP_EPSILON)
1089 return 0;
1090
1091 if (r_normal == -n)
1092 return 0; //todo change a little
1093
1094 r_point += r_normal * 0.01;
1095
1096 specular_at_point.r = res_light.r * specular_at_point.r;
1097 specular_at_point.g = res_light.g * specular_at_point.g;
1098 specular_at_point.b = res_light.b * specular_at_point.b;
1099
1100 if (use_diffuse && (diffuse_at_point.r > CMP_EPSILON || diffuse_at_point.g > CMP_EPSILON || diffuse_at_point.b > CMP_EPSILON)) {
1101 //diffuse bounce
1102
1103 Vector3 c1 = r_normal.cross(n).normalized();
1104 Vector3 c2 = r_normal.cross(c1).normalized();
1105 double r1 = double(rand()) / RAND_MAX;
1106 double r2 = double(rand()) / RAND_MAX;
1107 double r3 = double(rand()) / RAND_MAX;
1108 #if 0
1109 Vector3 next = - ((c1*(r1-0.5)) + (c2*(r2-0.5)) + (r_normal*(r3-0.5))).normalized()*0.5 + r_normal*0.5;
1110
1111 if (next==Vector3())
1112 next=r_normal;
1113 Vector3 rn=next.normalized();
1114
1115 #else
1116 Vector3 rn = ((c1 * (r1 - 0.5)) + (c2 * (r2 - 0.5)) + (r_normal * r3 * 0.5)).normalized();
1117 #endif
1118
1119 ret = _throw_ray(thread_stack, p_bake_direct, r_point, r_point + rn * p_rest, p_rest, diffuse_at_point, p_att_curve, p_att_pos, p_att_curve_len, p_bounces - 1);
1120 }
1121
1122 if (use_specular && (specular_at_point.r > CMP_EPSILON || specular_at_point.g > CMP_EPSILON || specular_at_point.b > CMP_EPSILON)) {
1123 //specular bounce
1124
1125 //Vector3 c1=r_normal.cross(n).normalized();
1126 //Vector3 c2=r_normal.cross(c1).normalized();
1127
1128 Vector3 rn = n - r_normal * r_normal.dot(n) * 2.0;
1129
1130 _throw_ray(thread_stack, p_bake_direct, r_point, r_point + rn * p_rest, p_rest, specular_at_point, p_att_curve, p_att_pos, p_att_curve_len, p_bounces - 1);
1131 }
1132 }
1133
1134 //specular later
1135 // _plot_light_point(r_point,octree,octree_aabb,p_light);
1136
1137 Color plot_light = res_light.linear_interpolate(diffuse_at_point, tint);
1138 plot_light.r *= att;
1139 plot_light.g *= att;
1140 plot_light.b *= att;
1141 Color tint_light = diffuse_at_point;
1142 tint_light.r *= att;
1143 tint_light.g *= att;
1144 tint_light.b *= att;
1145
1146 bool skip = false;
1147
1148 if (!p_first_bounce || p_bake_direct) {
1149
1150 float r = plot_size * cell_size * 2;
1151 if (dist < r) {
1152 //avoid accumulaiton of light on corners
1153 //plot_light=plot_light.linear_interpolate(Color(0,0,0,0),1.0-sd/plot_size*plot_size);
1154 skip = true;
1155
1156 } else {
1157
1158 Vector3 c1 = r_normal.cross(n).normalized();
1159 Vector3 c2 = r_normal.cross(c1).normalized();
1160 double r1 = double(rand()) / RAND_MAX;
1161 double r2 = double(rand()) / RAND_MAX;
1162 double r3 = double(rand()) / RAND_MAX;
1163 Vector3 rn = ((c1 * (r1 - 0.5)) + (c2 * (r2 - 0.5)) + (r_normal * r3 * 0.25)).normalized();
1164 float d = _throw_ray(thread_stack, p_bake_direct, r_point, r_point + rn * p_rest, p_rest, diffuse_at_point, p_att_curve, p_att_pos, p_att_curve_len, p_bounces - 1, false, true);
1165 r = plot_size * cell_size * ao_radius;
1166 if (d > 0 && d < r) {
1167 //avoid accumulaiton of light on corners
1168 //plot_light=plot_light.linear_interpolate(Color(0,0,0,0),1.0-sd/plot_size*plot_size);
1169 skip = true;
1170
1171 } else {
1172 //plot_light=Color(0,0,0,0);
1173 }
1174 }
1175 }
1176
1177 Plane plane(r_point, r_normal);
1178 if (!skip)
1179 _plot_light(thread_stack, r_point, aabb, plot_light, tint_light, !(!p_first_bounce || p_bake_direct), plane);
1180
1181 return dist;
1182 }
1183
1184 return -1;
1185 }
1186
_make_octree_texture()1187 void BakedLightBaker::_make_octree_texture() {
1188
1189 BakedLightBaker::Octant *octants = octant_pool.ptr();
1190
1191 //find neighbours first, to have a better idea of what amount of space is needed
1192 {
1193
1194 Vector<OctantHash> octant_hashing;
1195 octant_hashing.resize(octant_pool_size);
1196 Vector<uint32_t> hash_table;
1197 int hash_table_size = Math::larger_prime(16384);
1198 hash_table.resize(hash_table_size);
1199 uint32_t *hashptr = hash_table.ptr();
1200 OctantHash *octhashptr = octant_hashing.ptr();
1201
1202 for (int i = 0; i < hash_table_size; i++)
1203 hashptr[i] = 0;
1204
1205 //step 1 add to hash table
1206
1207 uint32_t oct_idx = leaf_list;
1208
1209 while (oct_idx) {
1210
1211 BakedLightBaker::Octant *oct = &octants[oct_idx];
1212 uint64_t base = 0;
1213 Vector3 pos = oct->aabb.pos - octree_aabb.pos; //make sure is always positive
1214 base = int((pos.x + cell_size * 0.5) / cell_size);
1215 base <<= 16;
1216 base |= int((pos.y + cell_size * 0.5) / cell_size);
1217 base <<= 16;
1218 base |= int((pos.z + cell_size * 0.5) / cell_size);
1219
1220 uint32_t hash = HashMapHasherDefault::hash(base);
1221 uint32_t idx = hash % hash_table_size;
1222 octhashptr[oct_idx].next = hashptr[idx];
1223 octhashptr[oct_idx].hash = hash;
1224 octhashptr[oct_idx].value = base;
1225 hashptr[idx] = oct_idx;
1226
1227 oct_idx = oct->next_leaf;
1228 }
1229
1230 //step 2 find neighbours
1231 oct_idx = leaf_list;
1232 int neighbours = 0;
1233
1234 while (oct_idx) {
1235
1236 BakedLightBaker::Octant *oct = &octants[oct_idx];
1237 Vector3 pos = oct->aabb.pos - octree_aabb.pos; //make sure is always positive
1238 pos.x += cell_size;
1239 uint64_t base = 0;
1240 base = int((pos.x + cell_size * 0.5) / cell_size);
1241 base <<= 16;
1242 base |= int((pos.y + cell_size * 0.5) / cell_size);
1243 base <<= 16;
1244 base |= int((pos.z + cell_size * 0.5) / cell_size);
1245
1246 uint32_t hash = HashMapHasherDefault::hash(base);
1247 uint32_t idx = hash % hash_table_size;
1248
1249 uint32_t bucket = hashptr[idx];
1250
1251 while (bucket) {
1252
1253 if (octhashptr[bucket].value == base) {
1254
1255 oct->bake_neighbour = bucket;
1256 octants[bucket].first_neighbour = false;
1257 neighbours++;
1258 break;
1259 }
1260
1261 bucket = octhashptr[bucket].next;
1262 }
1263
1264 oct_idx = oct->next_leaf;
1265 }
1266
1267 print_line("octant with neighbour: " + itos(neighbours));
1268 }
1269
1270 //ok let's try to just create a texture
1271
1272 int otex_w = 256;
1273
1274 while (true) {
1275
1276 uint32_t oct_idx = leaf_list;
1277
1278 int row = 0;
1279
1280 print_line("begin at row " + itos(row));
1281 int longest_line_reused = 0;
1282 int col = 0;
1283 int processed = 0;
1284
1285 //reset
1286 while (oct_idx) {
1287
1288 BakedLightBaker::Octant *oct = &octants[oct_idx];
1289 oct->texture_x = 0;
1290 oct->texture_y = 0;
1291 oct_idx = oct->next_leaf;
1292 }
1293
1294 oct_idx = leaf_list;
1295 //assign
1296 while (oct_idx) {
1297
1298 BakedLightBaker::Octant *oct = &octants[oct_idx];
1299 if (oct->first_neighbour && oct->texture_x == 0 && oct->texture_y == 0) {
1300 //was not processed
1301 uint32_t current_idx = oct_idx;
1302 int reused = 0;
1303
1304 while (current_idx) {
1305 BakedLightBaker::Octant *o = &octants[current_idx];
1306 if (col + 1 >= otex_w) {
1307 col = 0;
1308 row += 4;
1309 }
1310 o->texture_x = col;
1311 o->texture_y = row;
1312 processed++;
1313
1314 if (o->bake_neighbour) {
1315 reused++;
1316 }
1317 col += o->bake_neighbour ? 1 : 2; //reuse neighbour
1318 current_idx = o->bake_neighbour;
1319 }
1320
1321 if (reused > longest_line_reused) {
1322 longest_line_reused = reused;
1323 }
1324 }
1325 oct_idx = oct->next_leaf;
1326 }
1327
1328 row += 4;
1329
1330 if (otex_w < row) {
1331
1332 otex_w *= 2;
1333 } else {
1334
1335 baked_light_texture_w = otex_w;
1336 baked_light_texture_h = next_power_of_2(row);
1337 print_line("w: " + itos(otex_w));
1338 print_line("h: " + itos(row));
1339 break;
1340 }
1341 }
1342
1343 {
1344
1345 otex_w = (1 << lattice_size) * (1 << lattice_size) * 2; //make sure lattice fits horizontally
1346 Vector3 lattice_cell_size = octree_aabb.size;
1347 for (int i = 0; i < lattice_size; i++) {
1348
1349 lattice_cell_size *= 0.5;
1350 }
1351
1352 while (true) {
1353
1354 //let's plot the leafs first, given the octree is not so obvious which size it will have
1355 int row = 4 + 4 * (1 << lattice_size);
1356 int col = 0;
1357
1358 col = 0;
1359 row += 4;
1360 print_line("end at row " + itos(row));
1361
1362 //put octree, no need for recursion, just loop backwards.
1363 int regular_octants = 0;
1364 for (int i = octant_pool_size - 1; i >= 0; i--) {
1365
1366 BakedLightBaker::Octant *oct = &octants[i];
1367 if (oct->leaf) //ignore leaf
1368 continue;
1369 if (oct->aabb.size.x > lattice_cell_size.x * 1.1) { //bigger than latice, skip
1370 oct->texture_x = 0;
1371 oct->texture_y = 0;
1372 } else if (oct->aabb.size.x > lattice_cell_size.x * 0.8) {
1373 //this is the initial lattice
1374 Vector3 pos = oct->aabb.pos - octree_aabb.pos; //make sure is always positive
1375 int x = int((pos.x + lattice_cell_size.x * 0.5) / lattice_cell_size.x);
1376 int y = int((pos.y + lattice_cell_size.y * 0.5) / lattice_cell_size.y);
1377 int z = int((pos.z + lattice_cell_size.z * 0.5) / lattice_cell_size.z);
1378 //bug net
1379 ERR_FAIL_INDEX(x, (1 << lattice_size));
1380 ERR_FAIL_INDEX(y, (1 << lattice_size));
1381 ERR_FAIL_INDEX(z, (1 << lattice_size));
1382
1383 /*int ofs = z*(1<<lattice_size)*(1<<lattice_size)+y*(1<<lattice_size)+x;
1384 ofs*=4;
1385 oct->texture_x=ofs%otex_w;
1386 oct->texture_y=(ofs/otex_w)*4+4;
1387 */
1388
1389 oct->texture_x = (x + (1 << lattice_size) * z) * 2;
1390 oct->texture_y = 4 + y * 4;
1391 //print_line("pos: "+itos(x)+","+itos(y)+","+itos(z)+" - ofs"+itos(oct->texture_x)+","+itos(oct->texture_y));
1392
1393 } else {
1394 //an everyday regular octant
1395
1396 if (col + 2 > otex_w) {
1397 col = 0;
1398 row += 4;
1399 }
1400
1401 oct->texture_x = col;
1402 oct->texture_y = row;
1403 col += 2;
1404 regular_octants++;
1405 }
1406 }
1407 print_line("octants end at row " + itos(row) + " totalling" + itos(regular_octants));
1408
1409 //ok evaluation.
1410
1411 if (otex_w <= 2048 && row > 2048) { //too big upwards, try bigger texture
1412 otex_w *= 2;
1413 continue;
1414 } else {
1415 baked_octree_texture_w = otex_w;
1416 baked_octree_texture_h = row + 4;
1417 break;
1418 }
1419 }
1420 }
1421
1422 baked_octree_texture_h = next_power_of_2(baked_octree_texture_h);
1423 print_line("RESULT! " + itos(baked_octree_texture_w) + "," + itos(baked_octree_texture_h));
1424 }
1425
get_normalization(int p_light_idx) const1426 double BakedLightBaker::get_normalization(int p_light_idx) const {
1427
1428 double nrg = 0;
1429
1430 const LightData &dl = lights[p_light_idx];
1431 double cell_area = cell_size * cell_size;
1432 //nrg+= /*dl.energy */ (dl.rays_thrown * cell_area / dl.area);
1433 nrg = dl.rays_thrown * cell_area;
1434 nrg *= (Math_PI * plot_size * plot_size) * 0.5; // damping of radial linear gradient kernel
1435 nrg *= dl.constant;
1436 //nrg*=5;
1437
1438 return nrg;
1439 }
1440
get_modifier(int p_light_idx) const1441 double BakedLightBaker::get_modifier(int p_light_idx) const {
1442
1443 double nrg = 0;
1444
1445 const LightData &dl = lights[p_light_idx];
1446 double cell_area = cell_size * cell_size;
1447 //nrg+= /*dl.energy */ (dl.rays_thrown * cell_area / dl.area);
1448 nrg = cell_area;
1449 nrg *= (Math_PI * plot_size * plot_size) * 0.5; // damping of radial linear gradient kernel
1450 nrg *= dl.constant;
1451 //nrg*=5;
1452
1453 return nrg;
1454 }
1455
throw_rays(ThreadStack & thread_stack,int p_amount)1456 void BakedLightBaker::throw_rays(ThreadStack &thread_stack, int p_amount) {
1457
1458 for (int i = 0; i < lights.size(); i++) {
1459
1460 LightData &dl = lights[i];
1461
1462 int amount = p_amount * total_light_area / dl.area;
1463 double mod = 1.0 / double(get_modifier(i));
1464 mod *= p_amount / float(amount);
1465
1466 switch (dl.type) {
1467
1468 case VS::LIGHT_DIRECTIONAL: {
1469
1470 for (int j = 0; j < amount; j++) {
1471 Vector3 from = dl.pos;
1472 double r1 = double(rand()) / RAND_MAX;
1473 double r2 = double(rand()) / RAND_MAX;
1474 from += dl.up * (r1 * 2.0 - 1.0);
1475 from += dl.left * (r2 * 2.0 - 1.0);
1476 Vector3 to = from + dl.dir * dl.length;
1477 Color col = dl.diffuse;
1478 float m = mod * dl.energy;
1479 col.r *= m;
1480 col.g *= m;
1481 col.b *= m;
1482
1483 dl.rays_thrown++;
1484 baked_light_baker_add_64i(&total_rays, 1);
1485
1486 _throw_ray(thread_stack, dl.bake_direct, from, to, dl.length, col, NULL, 0, 0, max_bounces, true);
1487 }
1488 } break;
1489 case VS::LIGHT_OMNI: {
1490
1491 for (int j = 0; j < amount; j++) {
1492 Vector3 from = dl.pos;
1493
1494 double r1 = double(rand()) / RAND_MAX;
1495 double r2 = double(rand()) / RAND_MAX;
1496 double r3 = double(rand()) / RAND_MAX;
1497
1498 #if 0
1499 //crap is not uniform..
1500 Vector3 dir = Vector3(r1*2.0-1.0,r2*2.0-1.0,r3*2.0-1.0).normalized();
1501
1502 #else
1503
1504 double phi = r1 * Math_PI * 2.0;
1505 double costheta = r2 * 2.0 - 1.0;
1506 double u = r3;
1507
1508 double theta = acos(costheta);
1509 double r = 1.0 * pow(u, 1 / 3.0);
1510
1511 Vector3 dir(
1512 r * sin(theta) * cos(phi),
1513 r * sin(theta) * sin(phi),
1514 r * cos(theta));
1515 dir.normalize();
1516
1517 #endif
1518 Vector3 to = dl.pos + dir * dl.radius;
1519 Color col = dl.diffuse;
1520 float m = mod * dl.energy;
1521 col.r *= m;
1522 col.g *= m;
1523 col.b *= m;
1524
1525 dl.rays_thrown++;
1526 baked_light_baker_add_64i(&total_rays, 1);
1527 _throw_ray(thread_stack, dl.bake_direct, from, to, dl.radius, col, dl.attenuation_table.ptr(), 0, dl.radius, max_bounces, true);
1528 // _throw_ray(i,from,to,dl.radius,col,NULL,0,dl.radius,max_bounces,true);
1529 }
1530
1531 } break;
1532 case VS::LIGHT_SPOT: {
1533
1534 for (int j = 0; j < amount; j++) {
1535 Vector3 from = dl.pos;
1536
1537 double r1 = double(rand()) / RAND_MAX;
1538 //double r2 = double(rand())/RAND_MAX;
1539 double r3 = double(rand()) / RAND_MAX;
1540
1541 float d = Math::tan(Math::deg2rad(dl.spot_angle));
1542
1543 float x = sin(r1 * Math_PI * 2.0) * d;
1544 float y = cos(r1 * Math_PI * 2.0) * d;
1545
1546 Vector3 dir = r3 * (dl.dir + dl.up * y + dl.left * x) + (1.0 - r3) * dl.dir;
1547 dir.normalize();
1548
1549 Vector3 to = dl.pos + dir * dl.radius;
1550 Color col = dl.diffuse;
1551 float m = mod * dl.energy;
1552 col.r *= m;
1553 col.g *= m;
1554 col.b *= m;
1555
1556 dl.rays_thrown++;
1557 baked_light_baker_add_64i(&total_rays, 1);
1558 _throw_ray(thread_stack, dl.bake_direct, from, to, dl.radius, col, dl.attenuation_table.ptr(), 0, dl.radius, max_bounces, true);
1559 // _throw_ray(i,from,to,dl.radius,col,NULL,0,dl.radius,max_bounces,true);
1560 }
1561
1562 } break;
1563 }
1564 }
1565 }
1566
bake(const Ref<BakedLight> & p_light,Node * p_node)1567 void BakedLightBaker::bake(const Ref<BakedLight> &p_light, Node *p_node) {
1568
1569 if (baking)
1570 return;
1571 cell_count = 0;
1572
1573 base_inv = p_node->cast_to<Spatial>()->get_global_transform().affine_inverse();
1574 EditorProgress ep("bake", TTR("Light Baker Setup:"), 5);
1575 baked_light = p_light;
1576 lattice_size = baked_light->get_initial_lattice_subdiv();
1577 octree_depth = baked_light->get_cell_subdivision();
1578 plot_size = baked_light->get_plot_size();
1579 max_bounces = baked_light->get_bounces();
1580 use_diffuse = baked_light->get_bake_flag(BakedLight::BAKE_DIFFUSE);
1581 use_specular = baked_light->get_bake_flag(BakedLight::BAKE_SPECULAR);
1582 use_translucency = baked_light->get_bake_flag(BakedLight::BAKE_TRANSLUCENT);
1583
1584 edge_damp = baked_light->get_edge_damp();
1585 normal_damp = baked_light->get_normal_damp();
1586 octree_extra_margin = baked_light->get_cell_extra_margin();
1587 tint = baked_light->get_tint();
1588 ao_radius = baked_light->get_ao_radius();
1589 ao_strength = baked_light->get_ao_strength();
1590 linear_color = baked_light->get_bake_flag(BakedLight::BAKE_LINEAR_COLOR);
1591
1592 baked_textures.clear();
1593 for (int i = 0; i < baked_light->get_lightmaps_count(); i++) {
1594 BakeTexture bt;
1595 bt.width = baked_light->get_lightmap_gen_size(i).x;
1596 bt.height = baked_light->get_lightmap_gen_size(i).y;
1597 baked_textures.push_back(bt);
1598 }
1599
1600 ep.step(TTR("Parsing Geometry"), 0);
1601 _parse_geometry(p_node);
1602 mat_map.clear();
1603 tex_map.clear();
1604 print_line("\ttotal triangles: " + itos(triangles.size()));
1605 // no geometry
1606 if (triangles.size() == 0) {
1607 return;
1608 }
1609 ep.step(TTR("Fixing Lights"), 1);
1610 _fix_lights();
1611 ep.step(TTR("Making BVH"), 2);
1612 _make_bvh();
1613 ep.step(TTR("Creating Light Octree"), 3);
1614 _make_octree();
1615 ep.step(TTR("Creating Octree Texture"), 4);
1616 _make_octree_texture();
1617 baking = true;
1618 _start_thread();
1619 }
1620
update_octree_sampler(DVector<int> & p_sampler)1621 void BakedLightBaker::update_octree_sampler(DVector<int> &p_sampler) {
1622
1623 BakedLightBaker::Octant *octants = octant_pool.ptr();
1624 double norm = 1.0 / double(total_rays);
1625
1626 if (p_sampler.size() == 0 || first_bake_to_map) {
1627
1628 Vector<int> tmp_smp;
1629 tmp_smp.resize(32); //32 for header
1630
1631 for (int i = 0; i < 32; i++) {
1632 tmp_smp[i] = 0;
1633 }
1634
1635 for (int i = octant_pool_size - 1; i >= 0; i--) {
1636
1637 if (i == 0)
1638 tmp_smp[1] = tmp_smp.size();
1639
1640 Octant &octant = octants[i];
1641 octant.sampler_ofs = tmp_smp.size();
1642 int idxcol[2] = { 0, 0 };
1643
1644 int r = CLAMP((octant.full_accum[0] * norm) * 2048, 0, 32767);
1645 int g = CLAMP((octant.full_accum[1] * norm) * 2048, 0, 32767);
1646 int b = CLAMP((octant.full_accum[2] * norm) * 2048, 0, 32767);
1647
1648 idxcol[0] |= r;
1649 idxcol[1] |= (g << 16) | b;
1650
1651 if (octant.leaf) {
1652 tmp_smp.push_back(idxcol[0]);
1653 tmp_smp.push_back(idxcol[1]);
1654 } else {
1655
1656 for (int j = 0; j < 8; j++) {
1657 if (octant.children[j]) {
1658 idxcol[0] |= (1 << (j + 16));
1659 }
1660 }
1661 tmp_smp.push_back(idxcol[0]);
1662 tmp_smp.push_back(idxcol[1]);
1663 for (int j = 0; j < 8; j++) {
1664 if (octant.children[j]) {
1665 tmp_smp.push_back(octants[octant.children[j]].sampler_ofs);
1666 if (octants[octant.children[j]].sampler_ofs == 0) {
1667 print_line("FUUUUUUUUCK");
1668 }
1669 }
1670 }
1671 }
1672 }
1673
1674 p_sampler.resize(tmp_smp.size());
1675 DVector<int>::Write w = p_sampler.write();
1676 int ss = tmp_smp.size();
1677 for (int i = 0; i < ss; i++) {
1678 w[i] = tmp_smp[i];
1679 }
1680
1681 first_bake_to_map = false;
1682 }
1683
1684 double gamma = baked_light->get_gamma_adjust();
1685 double mult = baked_light->get_energy_multiplier();
1686 float saturation = baked_light->get_saturation();
1687
1688 DVector<int>::Write w = p_sampler.write();
1689
1690 encode_uint32(octree_depth, (uint8_t *)&w[2]);
1691 encode_uint32(linear_color, (uint8_t *)&w[3]);
1692
1693 encode_float(octree_aabb.pos.x, (uint8_t *)&w[4]);
1694 encode_float(octree_aabb.pos.y, (uint8_t *)&w[5]);
1695 encode_float(octree_aabb.pos.z, (uint8_t *)&w[6]);
1696 encode_float(octree_aabb.size.x, (uint8_t *)&w[7]);
1697 encode_float(octree_aabb.size.y, (uint8_t *)&w[8]);
1698 encode_float(octree_aabb.size.z, (uint8_t *)&w[9]);
1699
1700 //norm*=multiplier;
1701
1702 for (int i = octant_pool_size - 1; i >= 0; i--) {
1703
1704 Octant &octant = octants[i];
1705 int idxcol[2] = { w[octant.sampler_ofs], w[octant.sampler_ofs + 1] };
1706
1707 double rf = pow(octant.full_accum[0] * norm * mult, gamma);
1708 double gf = pow(octant.full_accum[1] * norm * mult, gamma);
1709 double bf = pow(octant.full_accum[2] * norm * mult, gamma);
1710
1711 double gray = (rf + gf + bf) / 3.0;
1712 rf = gray + (rf - gray) * saturation;
1713 gf = gray + (gf - gray) * saturation;
1714 bf = gray + (bf - gray) * saturation;
1715
1716 int r = CLAMP((rf)*2048, 0, 32767);
1717 int g = CLAMP((gf)*2048, 0, 32767);
1718 int b = CLAMP((bf)*2048, 0, 32767);
1719
1720 idxcol[0] = ((idxcol[0] >> 16) << 16) | r;
1721 idxcol[1] = (g << 16) | b;
1722 w[octant.sampler_ofs] = idxcol[0];
1723 w[octant.sampler_ofs + 1] = idxcol[1];
1724 }
1725 }
1726
update_octree_images(DVector<uint8_t> & p_octree,DVector<uint8_t> & p_light)1727 void BakedLightBaker::update_octree_images(DVector<uint8_t> &p_octree, DVector<uint8_t> &p_light) {
1728
1729 int len = baked_octree_texture_w * baked_octree_texture_h * 4;
1730 p_octree.resize(len);
1731
1732 int ilen = baked_light_texture_w * baked_light_texture_h * 4;
1733 p_light.resize(ilen);
1734
1735 DVector<uint8_t>::Write w = p_octree.write();
1736 zeromem(w.ptr(), len);
1737
1738 DVector<uint8_t>::Write iw = p_light.write();
1739 zeromem(iw.ptr(), ilen);
1740
1741 float gamma = baked_light->get_gamma_adjust();
1742 float mult = baked_light->get_energy_multiplier();
1743
1744 for (int i = 0; i < len; i += 4) {
1745 w[i + 0] = 0xFF;
1746 w[i + 1] = 0;
1747 w[i + 2] = 0xFF;
1748 w[i + 3] = 0xFF;
1749 }
1750
1751 for (int i = 0; i < ilen; i += 4) {
1752 iw[i + 0] = 0xFF;
1753 iw[i + 1] = 0;
1754 iw[i + 2] = 0xFF;
1755 iw[i + 3] = 0xFF;
1756 }
1757
1758 float multiplier = 1.0;
1759
1760 if (baked_light->get_format() == BakedLight::FORMAT_HDR8)
1761 multiplier = 8;
1762 encode_uint32(baked_octree_texture_w, &w[0]);
1763 encode_uint32(baked_octree_texture_h, &w[4]);
1764 encode_uint32(0, &w[8]);
1765 encode_float(1 << lattice_size, &w[12]);
1766 encode_uint32(octree_depth - lattice_size, &w[16]);
1767 encode_uint32(multiplier, &w[20]);
1768 encode_uint16(baked_light_texture_w, &w[24]); //if present, use the baked light texture
1769 encode_uint16(baked_light_texture_h, &w[26]);
1770 encode_uint32(0, &w[28]); //baked light texture format
1771
1772 encode_float(octree_aabb.pos.x, &w[32]);
1773 encode_float(octree_aabb.pos.y, &w[36]);
1774 encode_float(octree_aabb.pos.z, &w[40]);
1775 encode_float(octree_aabb.size.x, &w[44]);
1776 encode_float(octree_aabb.size.y, &w[48]);
1777 encode_float(octree_aabb.size.z, &w[52]);
1778
1779 BakedLightBaker::Octant *octants = octant_pool.ptr();
1780 int octant_count = octant_pool_size;
1781 uint8_t *ptr = w.ptr();
1782 uint8_t *lptr = iw.ptr();
1783
1784 int child_offsets[8] = {
1785 0,
1786 4,
1787 baked_octree_texture_w * 4,
1788 baked_octree_texture_w * 4 + 4,
1789 baked_octree_texture_w * 8 + 0,
1790 baked_octree_texture_w * 8 + 4,
1791 baked_octree_texture_w * 8 + baked_octree_texture_w * 4,
1792 baked_octree_texture_w * 8 + baked_octree_texture_w * 4 + 4,
1793 };
1794
1795 int lchild_offsets[8] = {
1796 0,
1797 4,
1798 baked_light_texture_w * 4,
1799 baked_light_texture_w * 4 + 4,
1800 baked_light_texture_w * 8 + 0,
1801 baked_light_texture_w * 8 + 4,
1802 baked_light_texture_w * 8 + baked_light_texture_w * 4,
1803 baked_light_texture_w * 8 + baked_light_texture_w * 4 + 4,
1804 };
1805
1806 /*Vector<double> norm_arr;
1807 norm_arr.resize(lights.size());
1808
1809 for(int i=0;i<lights.size();i++) {
1810 norm_arr[i] = 1.0/get_normalization(i);
1811 }
1812
1813 const double *normptr=norm_arr.ptr();
1814 */
1815 double norm = 1.0 / double(total_rays);
1816 mult /= multiplier;
1817 double saturation = baked_light->get_saturation();
1818
1819 for (int i = 0; i < octant_count; i++) {
1820
1821 Octant &oct = octants[i];
1822 if (oct.texture_x == 0 && oct.texture_y == 0)
1823 continue;
1824
1825 if (oct.leaf) {
1826
1827 int ofs = (oct.texture_y * baked_light_texture_w + oct.texture_x) << 2;
1828 ERR_CONTINUE(ofs < 0 || ofs > ilen);
1829 //write colors
1830 for (int j = 0; j < 8; j++) {
1831
1832 //if (!oct.children[j])
1833 // continue;
1834 uint8_t *iptr = &lptr[ofs + lchild_offsets[j]];
1835
1836 float r = oct.light_accum[j][0] * norm;
1837 float g = oct.light_accum[j][1] * norm;
1838 float b = oct.light_accum[j][2] * norm;
1839
1840 r = pow(r * mult, gamma);
1841 g = pow(g * mult, gamma);
1842 b = pow(b * mult, gamma);
1843
1844 double gray = (r + g + b) / 3.0;
1845 r = gray + (r - gray) * saturation;
1846 g = gray + (g - gray) * saturation;
1847 b = gray + (b - gray) * saturation;
1848
1849 float ic[3] = {
1850 r,
1851 g,
1852 b,
1853 };
1854 iptr[0] = CLAMP(ic[0] * 255.0, 0, 255);
1855 iptr[1] = CLAMP(ic[1] * 255.0, 0, 255);
1856 iptr[2] = CLAMP(ic[2] * 255.0, 0, 255);
1857 iptr[3] = 255;
1858 }
1859
1860 } else {
1861
1862 int ofs = (oct.texture_y * baked_octree_texture_w + oct.texture_x) << 2;
1863 ERR_CONTINUE(ofs < 0 || ofs > len);
1864
1865 //write indices
1866 for (int j = 0; j < 8; j++) {
1867
1868 if (!oct.children[j])
1869 continue;
1870 Octant &choct = octants[oct.children[j]];
1871 uint8_t *iptr = &ptr[ofs + child_offsets[j]];
1872
1873 iptr[0] = choct.texture_x >> 8;
1874 iptr[1] = choct.texture_x & 0xFF;
1875 iptr[2] = choct.texture_y >> 8;
1876 iptr[3] = choct.texture_y & 0xFF;
1877 }
1878 }
1879 }
1880 }
1881
_free_bvh(BVH * p_bvh)1882 void BakedLightBaker::_free_bvh(BVH *p_bvh) {
1883
1884 if (!p_bvh->leaf) {
1885 if (p_bvh->children[0])
1886 _free_bvh(p_bvh->children[0]);
1887 if (p_bvh->children[1])
1888 _free_bvh(p_bvh->children[1]);
1889 }
1890
1891 memdelete(p_bvh);
1892 }
1893
is_baking()1894 bool BakedLightBaker::is_baking() {
1895
1896 return baking;
1897 }
1898
set_pause(bool p_pause)1899 void BakedLightBaker::set_pause(bool p_pause) {
1900
1901 if (paused == p_pause)
1902 return;
1903
1904 paused = p_pause;
1905
1906 if (paused) {
1907 _stop_thread();
1908 } else {
1909 _start_thread();
1910 }
1911 }
is_paused()1912 bool BakedLightBaker::is_paused() {
1913
1914 return paused;
1915 }
1916
_bake_thread_func(void * arg)1917 void BakedLightBaker::_bake_thread_func(void *arg) {
1918
1919 BakedLightBaker *ble = (BakedLightBaker *)arg;
1920
1921 ThreadStack thread_stack;
1922
1923 thread_stack.ray_stack = memnew_arr(uint32_t, ble->bvh_depth);
1924 thread_stack.bvh_stack = memnew_arr(BVH *, ble->bvh_depth);
1925 thread_stack.octant_stack = memnew_arr(uint32_t, ble->octree_depth * 2);
1926 thread_stack.octantptr_stack = memnew_arr(uint32_t, ble->octree_depth * 2);
1927
1928 while (!ble->bake_thread_exit) {
1929
1930 ble->throw_rays(thread_stack, 1000);
1931 }
1932
1933 memdelete_arr(thread_stack.ray_stack);
1934 memdelete_arr(thread_stack.bvh_stack);
1935 memdelete_arr(thread_stack.octant_stack);
1936 memdelete_arr(thread_stack.octantptr_stack);
1937 }
1938
_start_thread()1939 void BakedLightBaker::_start_thread() {
1940
1941 if (threads.size() != 0)
1942 return;
1943 bake_thread_exit = false;
1944
1945 int thread_count = EDITOR_DEF("light_baker/custom_bake_threads", 0);
1946 if (thread_count <= 0 || thread_count > 64)
1947 thread_count = OS::get_singleton()->get_processor_count();
1948
1949 //thread_count=1;
1950 threads.resize(thread_count);
1951 for (int i = 0; i < threads.size(); i++) {
1952 threads[i] = Thread::create(_bake_thread_func, this);
1953 }
1954 }
1955
_stop_thread()1956 void BakedLightBaker::_stop_thread() {
1957
1958 if (threads.size() == 0)
1959 return;
1960 bake_thread_exit = true;
1961 for (int i = 0; i < threads.size(); i++) {
1962 Thread::wait_to_finish(threads[i]);
1963 memdelete(threads[i]);
1964 }
1965 threads.clear();
1966 }
1967
_plot_pixel_to_lightmap(int x,int y,int width,int height,uint8_t * image,const Vector3 & p_pos,const Vector3 & p_normal,double * p_norm_ptr,float mult,float gamma)1968 void BakedLightBaker::_plot_pixel_to_lightmap(int x, int y, int width, int height, uint8_t *image, const Vector3 &p_pos, const Vector3 &p_normal, double *p_norm_ptr, float mult, float gamma) {
1969
1970 uint8_t *ptr = &image[(y * width + x) * 4];
1971 //int lc = lights.size();
1972 double norm = 1.0 / double(total_rays);
1973
1974 Color color;
1975
1976 Octant *octants = octant_pool.ptr();
1977
1978 int octant_idx = 0;
1979
1980 while (true) {
1981
1982 Octant &octant = octants[octant_idx];
1983
1984 if (octant.leaf) {
1985
1986 Vector3 lpos = p_pos - octant.aabb.pos;
1987 lpos /= octant.aabb.size;
1988
1989 Vector3 cols[8];
1990
1991 for (int i = 0; i < 8; i++) {
1992
1993 cols[i].x += octant.light_accum[i][0] * norm;
1994 cols[i].y += octant.light_accum[i][1] * norm;
1995 cols[i].z += octant.light_accum[i][2] * norm;
1996 }
1997
1998 /*Vector3 final = (cols[0] + (cols[1] - cols[0]) * lpos.y);
1999 final = final + ((cols[2] + (cols[3] - cols[2]) * lpos.y) - final)*lpos.x;
2000
2001 Vector3 final2 = (cols[4+0] + (cols[4+1] - cols[4+0]) * lpos.y);
2002 final2 = final2 + ((cols[4+2] + (cols[4+3] - cols[4+2]) * lpos.y) - final2)*lpos.x;*/
2003
2004 Vector3 finala = cols[0].linear_interpolate(cols[1], lpos.x);
2005 Vector3 finalb = cols[2].linear_interpolate(cols[3], lpos.x);
2006 Vector3 final = finala.linear_interpolate(finalb, lpos.y);
2007
2008 Vector3 final2a = cols[4 + 0].linear_interpolate(cols[4 + 1], lpos.x);
2009 Vector3 final2b = cols[4 + 2].linear_interpolate(cols[4 + 3], lpos.x);
2010 Vector3 final2 = final2a.linear_interpolate(final2b, lpos.y);
2011
2012 final = final.linear_interpolate(final2, lpos.z);
2013 if (baked_light->get_format() == BakedLight::FORMAT_HDR8)
2014 final *= 8.0;
2015
2016 color.r = pow(final.x * mult, gamma);
2017 color.g = pow(final.y * mult, gamma);
2018 color.b = pow(final.z * mult, gamma);
2019 color.a = 1.0;
2020
2021 int lc = lights.size();
2022 LightData *lv = lights.ptr();
2023 for (int i = 0; i < lc; i++) {
2024 //shadow baking
2025 if (!lv[i].bake_shadow)
2026 continue;
2027 Vector3 from = p_pos + p_normal * 0.01;
2028 Vector3 to;
2029 float att = 0;
2030 switch (lv[i].type) {
2031 case VS::LIGHT_DIRECTIONAL: {
2032 to = from - lv[i].dir * lv[i].length;
2033 } break;
2034 case VS::LIGHT_OMNI: {
2035 to = lv[i].pos;
2036 float d = MIN(lv[i].radius, to.distance_to(from)) / lv[i].radius;
2037 att = d; //1.0-d;
2038 } break;
2039 default: continue;
2040 }
2041
2042 uint32_t *stack = ray_stack;
2043 BVH **bstack = bvh_stack;
2044
2045 enum {
2046 TEST_RAY_BIT = 0,
2047 VISIT_LEFT_BIT = 1,
2048 VISIT_RIGHT_BIT = 2,
2049 VISIT_DONE_BIT = 3,
2050
2051 };
2052
2053 bool intersected = false;
2054
2055 int level = 0;
2056
2057 Vector3 n = (to - from);
2058 float len = n.length();
2059 if (len == 0)
2060 continue;
2061 n /= len;
2062
2063 bstack[0] = bvh;
2064 stack[0] = TEST_RAY_BIT;
2065
2066 while (!intersected) {
2067
2068 uint32_t mode = stack[level];
2069 const BVH &b = *bstack[level];
2070 bool done = false;
2071
2072 switch (mode) {
2073 case TEST_RAY_BIT: {
2074
2075 if (b.leaf) {
2076
2077 Face3 f3(b.leaf->vertices[0], b.leaf->vertices[1], b.leaf->vertices[2]);
2078
2079 Vector3 res;
2080
2081 if (f3.intersects_segment(from, to)) {
2082 intersected = true;
2083 done = true;
2084 }
2085
2086 stack[level] = VISIT_DONE_BIT;
2087 } else {
2088
2089 bool valid = b.aabb.smits_intersect_ray(from, n, 0, len);
2090 //bool valid = b.aabb.intersects_segment(p_begin,p_end);
2091 // bool valid = b.aabb.intersects(ray_aabb);
2092
2093 if (!valid) {
2094
2095 stack[level] = VISIT_DONE_BIT;
2096
2097 } else {
2098
2099 stack[level] = VISIT_LEFT_BIT;
2100 }
2101 }
2102 }
2103 continue;
2104 case VISIT_LEFT_BIT: {
2105
2106 stack[level] = VISIT_RIGHT_BIT;
2107 bstack[level + 1] = b.children[0];
2108 stack[level + 1] = TEST_RAY_BIT;
2109 level++;
2110 }
2111 continue;
2112 case VISIT_RIGHT_BIT: {
2113
2114 stack[level] = VISIT_DONE_BIT;
2115 bstack[level + 1] = b.children[1];
2116 stack[level + 1] = TEST_RAY_BIT;
2117 level++;
2118 }
2119 continue;
2120 case VISIT_DONE_BIT: {
2121
2122 if (level == 0) {
2123 done = true;
2124 break;
2125 } else
2126 level--;
2127 }
2128 continue;
2129 }
2130
2131 if (done)
2132 break;
2133 }
2134
2135 if (intersected) {
2136
2137 color.a = Math::lerp(MAX(0.01, lv[i].darkening), 1.0, att);
2138 }
2139 }
2140
2141 break;
2142 } else {
2143
2144 Vector3 lpos = p_pos - octant.aabb.pos;
2145 Vector3 half = octant.aabb.size * 0.5;
2146
2147 int ofs = 0;
2148
2149 if (lpos.x >= half.x)
2150 ofs |= 1;
2151 if (lpos.y >= half.y)
2152 ofs |= 2;
2153 if (lpos.z >= half.z)
2154 ofs |= 4;
2155
2156 octant_idx = octant.children[ofs];
2157
2158 if (octant_idx == 0)
2159 return;
2160 }
2161 }
2162
2163 ptr[0] = CLAMP(color.r * 255.0, 0, 255);
2164 ptr[1] = CLAMP(color.g * 255.0, 0, 255);
2165 ptr[2] = CLAMP(color.b * 255.0, 0, 255);
2166 ptr[3] = CLAMP(color.a * 255.0, 0, 255);
2167 }
2168
transfer_to_lightmaps()2169 Error BakedLightBaker::transfer_to_lightmaps() {
2170
2171 if (!triangles.size() || baked_textures.size() == 0)
2172 return ERR_UNCONFIGURED;
2173
2174 EditorProgress ep("transfer_to_lightmaps", TTR("Transfer to Lightmaps:"), baked_textures.size() * 2 + triangles.size());
2175
2176 for (int i = 0; i < baked_textures.size(); i++) {
2177
2178 ERR_FAIL_COND_V(baked_textures[i].width <= 0 || baked_textures[i].height <= 0, ERR_UNCONFIGURED);
2179
2180 baked_textures[i].data.resize(baked_textures[i].width * baked_textures[i].height * 4);
2181 zeromem(baked_textures[i].data.ptr(), baked_textures[i].data.size());
2182 ep.step(TTR("Allocating Texture #") + itos(i + 1), i);
2183 }
2184
2185 Vector<double> norm_arr;
2186 norm_arr.resize(lights.size());
2187
2188 for (int i = 0; i < lights.size(); i++) {
2189 norm_arr[i] = 1.0 / get_normalization(i);
2190 }
2191 float gamma = baked_light->get_gamma_adjust();
2192 float mult = baked_light->get_energy_multiplier();
2193
2194 for (int i = 0; i < triangles.size(); i++) {
2195
2196 if (i % 200 == 0) {
2197 ep.step(TTR("Baking Triangle #") + itos(i), i + baked_textures.size());
2198 }
2199 Triangle &t = triangles[i];
2200 if (t.baked_texture < 0 || t.baked_texture >= baked_textures.size())
2201 continue;
2202
2203 BakeTexture &bt = baked_textures[t.baked_texture];
2204 Vector3 normal = Plane(t.vertices[0], t.vertices[1], t.vertices[2]).normal;
2205
2206 int x[3];
2207 int y[3];
2208
2209 Vector3 vertices[3] = {
2210 t.vertices[0],
2211 t.vertices[1],
2212 t.vertices[2]
2213 };
2214
2215 for (int j = 0; j < 3; j++) {
2216
2217 x[j] = t.bake_uvs[j].x * bt.width;
2218 y[j] = t.bake_uvs[j].y * bt.height;
2219 x[j] = CLAMP(x[j], 0, bt.width - 1);
2220 y[j] = CLAMP(y[j], 0, bt.height - 1);
2221 }
2222
2223 {
2224
2225 // sort the points vertically
2226 if (y[1] > y[2]) {
2227 SWAP(x[1], x[2]);
2228 SWAP(y[1], y[2]);
2229 SWAP(vertices[1], vertices[2]);
2230 }
2231 if (y[0] > y[1]) {
2232 SWAP(x[0], x[1]);
2233 SWAP(y[0], y[1]);
2234 SWAP(vertices[0], vertices[1]);
2235 }
2236 if (y[1] > y[2]) {
2237 SWAP(x[1], x[2]);
2238 SWAP(y[1], y[2]);
2239 SWAP(vertices[1], vertices[2]);
2240 }
2241
2242 double dx_far = double(x[2] - x[0]) / (y[2] - y[0] + 1);
2243 double dx_upper = double(x[1] - x[0]) / (y[1] - y[0] + 1);
2244 double dx_low = double(x[2] - x[1]) / (y[2] - y[1] + 1);
2245 double xf = x[0];
2246 double xt = x[0] + dx_upper; // if y[0] == y[1], special case
2247 for (int yi = y[0]; yi <= (y[2] > bt.height - 1 ? bt.height - 1 : y[2]); yi++) {
2248 if (yi >= 0) {
2249 for (int xi = (xf > 0 ? int(xf) : 0); xi <= (xt < bt.width ? xt : bt.width - 1); xi++) {
2250 //pixels[int(x + y * width)] = color;
2251
2252 Vector2 v0 = Vector2(x[1] - x[0], y[1] - y[0]);
2253 Vector2 v1 = Vector2(x[2] - x[0], y[2] - y[0]);
2254 //vertices[2] - vertices[0];
2255 Vector2 v2 = Vector2(xi - x[0], yi - y[0]);
2256 float d00 = v0.dot(v0);
2257 float d01 = v0.dot(v1);
2258 float d11 = v1.dot(v1);
2259 float d20 = v2.dot(v0);
2260 float d21 = v2.dot(v1);
2261 float denom = (d00 * d11 - d01 * d01);
2262 Vector3 pos;
2263 if (denom == 0) {
2264 pos = t.vertices[0];
2265 } else {
2266 float v = (d11 * d20 - d01 * d21) / denom;
2267 float w = (d00 * d21 - d01 * d20) / denom;
2268 float u = 1.0f - v - w;
2269 pos = vertices[0] * u + vertices[1] * v + vertices[2] * w;
2270 }
2271 _plot_pixel_to_lightmap(xi, yi, bt.width, bt.height, bt.data.ptr(), pos, normal, norm_arr.ptr(), mult, gamma);
2272 }
2273
2274 for (int xi = (xf < bt.width ? int(xf) : bt.width - 1); xi >= (xt > 0 ? xt : 0); xi--) {
2275 //pixels[int(x + y * width)] = color;
2276 Vector2 v0 = Vector2(x[1] - x[0], y[1] - y[0]);
2277 Vector2 v1 = Vector2(x[2] - x[0], y[2] - y[0]);
2278 //vertices[2] - vertices[0];
2279 Vector2 v2 = Vector2(xi - x[0], yi - y[0]);
2280 float d00 = v0.dot(v0);
2281 float d01 = v0.dot(v1);
2282 float d11 = v1.dot(v1);
2283 float d20 = v2.dot(v0);
2284 float d21 = v2.dot(v1);
2285 float denom = (d00 * d11 - d01 * d01);
2286 Vector3 pos;
2287 if (denom == 0) {
2288 pos = t.vertices[0];
2289 } else {
2290 float v = (d11 * d20 - d01 * d21) / denom;
2291 float w = (d00 * d21 - d01 * d20) / denom;
2292 float u = 1.0f - v - w;
2293 pos = vertices[0] * u + vertices[1] * v + vertices[2] * w;
2294 }
2295
2296 _plot_pixel_to_lightmap(xi, yi, bt.width, bt.height, bt.data.ptr(), pos, normal, norm_arr.ptr(), mult, gamma);
2297 }
2298 }
2299 xf += dx_far;
2300 if (yi < y[1])
2301 xt += dx_upper;
2302 else
2303 xt += dx_low;
2304 }
2305 }
2306 }
2307
2308 for (int i = 0; i < baked_textures.size(); i++) {
2309
2310 {
2311
2312 ep.step(TTR("Post-Processing Texture #") + itos(i), i + baked_textures.size() + triangles.size());
2313
2314 BakeTexture &bt = baked_textures[i];
2315
2316 Vector<uint8_t> copy_data = bt.data;
2317 uint8_t *data = bt.data.ptr();
2318 const int max_radius = 8;
2319 const int shadow_radius = 2;
2320 const int max_dist = 0x7FFFFFFF;
2321
2322 for (int x = 0; x < bt.width; x++) {
2323
2324 for (int y = 0; y < bt.height; y++) {
2325
2326 uint8_t a = copy_data[(y * bt.width + x) * 4 + 3];
2327
2328 if (a > 0) {
2329 //blur shadow
2330
2331 int from_x = MAX(0, x - shadow_radius);
2332 int to_x = MIN(bt.width - 1, x + shadow_radius);
2333 int from_y = MAX(0, y - shadow_radius);
2334 int to_y = MIN(bt.height - 1, y + shadow_radius);
2335
2336 int sum = 0;
2337 int sumc = 0;
2338
2339 for (int k = from_y; k <= to_y; k++) {
2340 for (int l = from_x; l <= to_x; l++) {
2341
2342 const uint8_t *rp = ©_data[(k * bt.width + l) << 2];
2343
2344 sum += rp[3];
2345 sumc++;
2346 }
2347 }
2348
2349 sum /= sumc;
2350 data[(y * bt.width + x) * 4 + 3] = sum;
2351
2352 } else {
2353
2354 int closest_dist = max_dist;
2355 uint8_t closest_color[4];
2356
2357 int from_x = MAX(0, x - max_radius);
2358 int to_x = MIN(bt.width - 1, x + max_radius);
2359 int from_y = MAX(0, y - max_radius);
2360 int to_y = MIN(bt.height - 1, y + max_radius);
2361
2362 for (int k = from_y; k <= to_y; k++) {
2363 for (int l = from_x; l <= to_x; l++) {
2364
2365 int dy = y - k;
2366 int dx = x - l;
2367 int dist = dy * dy + dx * dx;
2368 if (dist >= closest_dist)
2369 continue;
2370
2371 const uint8_t *rp = ©_data[(k * bt.width + l) << 2];
2372
2373 if (rp[3] == 0)
2374 continue;
2375
2376 closest_dist = dist;
2377 closest_color[0] = rp[0];
2378 closest_color[1] = rp[1];
2379 closest_color[2] = rp[2];
2380 closest_color[3] = rp[3];
2381 }
2382 }
2383
2384 if (closest_dist != max_dist) {
2385
2386 data[(y * bt.width + x) * 4 + 0] = closest_color[0];
2387 data[(y * bt.width + x) * 4 + 1] = closest_color[1];
2388 data[(y * bt.width + x) * 4 + 2] = closest_color[2];
2389 data[(y * bt.width + x) * 4 + 3] = closest_color[3];
2390 }
2391 }
2392 }
2393 }
2394 }
2395
2396 DVector<uint8_t> dv;
2397 dv.resize(baked_textures[i].data.size());
2398 {
2399 DVector<uint8_t>::Write w = dv.write();
2400 copymem(w.ptr(), baked_textures[i].data.ptr(), baked_textures[i].data.size());
2401 }
2402
2403 Image img(baked_textures[i].width, baked_textures[i].height, 0, Image::FORMAT_RGBA, dv);
2404 Ref<ImageTexture> tex = memnew(ImageTexture);
2405 tex->create_from_image(img);
2406 baked_light->set_lightmap_texture(i, tex);
2407 }
2408
2409 return OK;
2410 }
2411
clear()2412 void BakedLightBaker::clear() {
2413
2414 _stop_thread();
2415
2416 if (bvh)
2417 _free_bvh(bvh);
2418
2419 if (ray_stack)
2420 memdelete_arr(ray_stack);
2421 if (octant_stack)
2422 memdelete_arr(octant_stack);
2423 if (octantptr_stack)
2424 memdelete_arr(octantptr_stack);
2425 if (bvh_stack)
2426 memdelete_arr(bvh_stack);
2427 /*
2428 * ???
2429 for(int i=0;i<octant_pool.size();i++) {
2430 //if (octant_pool[i].leaf) {
2431 // memdelete_arr( octant_pool[i].light );
2432 //} Vector<double> norm_arr;
2433 //norm_arr.resize(lights.size());
2434
2435 for(int i=0;i<lights.size();i++) {
2436 norm_arr[i] = 1.0/get_normalization(i);
2437 }
2438
2439 const double *normptr=norm_arr.ptr();
2440 }
2441 */
2442 octant_pool.clear();
2443 octant_pool_size = 0;
2444 bvh = NULL;
2445 leaf_list = 0;
2446 cell_count = 0;
2447 ray_stack = NULL;
2448 octant_stack = NULL;
2449 octantptr_stack = NULL;
2450 bvh_stack = NULL;
2451 materials.clear();
2452 materials.clear();
2453 textures.clear();
2454 lights.clear();
2455 triangles.clear();
2456 endpoint_normal.clear();
2457 endpoint_normal_bits.clear();
2458 baked_octree_texture_w = 0;
2459 baked_octree_texture_h = 0;
2460 paused = false;
2461 baking = false;
2462
2463 bake_thread_exit = false;
2464 first_bake_to_map = true;
2465 baked_light = Ref<BakedLight>();
2466 total_rays = 0;
2467 }
2468
BakedLightBaker()2469 BakedLightBaker::BakedLightBaker() {
2470 octree_depth = 9;
2471 lattice_size = 4;
2472 octant_pool.clear();
2473 octant_pool_size = 0;
2474 bvh = NULL;
2475 leaf_list = 0;
2476 cell_count = 0;
2477 ray_stack = NULL;
2478 bvh_stack = NULL;
2479 octant_stack = NULL;
2480 octantptr_stack = NULL;
2481 plot_size = 2.5;
2482 max_bounces = 2;
2483 materials.clear();
2484 baked_octree_texture_w = 0;
2485 baked_octree_texture_h = 0;
2486 paused = false;
2487 baking = false;
2488
2489 bake_thread_exit = false;
2490 total_rays = 0;
2491 first_bake_to_map = true;
2492 linear_color = false;
2493 }
2494
~BakedLightBaker()2495 BakedLightBaker::~BakedLightBaker() {
2496
2497 clear();
2498 }
2499