Blender V5.3
scene/light.cpp
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2011-2022 Blender Foundation
2 *
3 * SPDX-License-Identifier: Apache-2.0 */
4
5#include "device/device.h"
6
7#include "scene/background.h"
8#include "scene/film.h"
9#include "scene/integrator.h"
10#include "scene/light.h"
11#include "scene/light_tree.h"
12#include "scene/mesh.h"
13#include "scene/object.h"
14#include "scene/scene.h"
15#include "scene/shader.h"
16#include "scene/shader_graph.h"
17#include "scene/shader_nodes.h"
18#include "scene/stats.h"
19
21
22#include "util/hash.h"
23#include "util/log.h"
24#include "util/path.h"
25#include "util/progress.h"
26
28
29static void shade_background_pixels(Device *device,
30 DeviceScene *dscene,
31 const int width,
32 const int height,
33 vector<float3> &pixels,
34 Progress &progress)
35{
36 /* Needs to be up to data for attribute access. */
37 device->const_copy_to("data", &dscene->data, sizeof(dscene->data));
38
39 const int size = width * height;
40 const int num_channels = 3;
41 pixels.resize(size);
42
43 /* Evaluate shader on device. */
44 ShaderEval shader_eval(device, progress);
45 shader_eval.eval(
47 size,
48 num_channels,
50 /* Fill coordinates for shading. */
51 KernelShaderEvalInput *d_input_data = d_input.data();
52
53 for (int y = 0; y < height; y++) {
54 for (int x = 0; x < width; x++) {
55 float const u = (x + 0.5f) / width;
56 float const v = (y + 0.5f) / height;
57
59 /* Repurpose object and prim to pass resolution for ray differential. */
60 in.object = width;
61 in.prim = height;
62 in.u = u;
63 in.v = v;
64 d_input_data[x + y * width] = in;
65 }
66 }
67
68 return size;
69 },
70 [&](device_vector<float> &d_output) {
71 /* Copy output to pixel buffer. */
72 float *d_output_data = d_output.data();
73
74 for (int y = 0; y < height; y++) {
75 for (int x = 0; x < width; x++) {
76 pixels[y * width + x].x = d_output_data[(y * width + x) * num_channels + 0];
77 pixels[y * width + x].y = d_output_data[(y * width + x) * num_channels + 1];
78 pixels[y * width + x].z = d_output_data[(y * width + x) * num_channels + 2];
79 }
80 }
81 });
82}
83
84/* Light */
85
87{
88 NodeType *type = NodeType::add("light", nullptr, NodeType::NONE, Geometry::get_node_base_type());
89
90 static NodeEnum type_enum;
91 type_enum.insert("point", LIGHT_POINT);
92 type_enum.insert("sun", LIGHT_SUN);
93 type_enum.insert("background", LIGHT_BACKGROUND);
94 type_enum.insert("area", LIGHT_AREA);
95 type_enum.insert("spot", LIGHT_SPOT);
96 SOCKET_ENUM(light_type, "Type", type_enum, LIGHT_POINT);
97
98 SOCKET_COLOR(strength, "Strength", one_float3());
99
100 SOCKET_BOOLEAN(cast_shadow, "Cast Shadow", true);
101 SOCKET_BOOLEAN(use_mis, "Use Mis", false);
102 SOCKET_BOOLEAN(use_caustics, "Shadow Caustics", false);
103
104 SOCKET_INT(max_bounces, "Max Bounces", 1024);
105
106 SOCKET_BOOLEAN(is_enabled, "Is Enabled", true);
107
108 SOCKET_BOOLEAN(normalize, "Normalize", true);
109
110 return type;
111}
112
113Light::Light(const NodeType *node_type, const Geometry::Type type) : Geometry(node_type, type) {}
114
116{
117 NodeType *type = NodeType::add(
118 "pointlight", create, NodeType::NONE, Light::get_node_base_type());
119
120 SOCKET_FLOAT(radius, "Radius", 0.0f);
121 SOCKET_BOOLEAN(is_sphere, "Is Sphere", true);
122
123 return type;
124}
125
127{
128 light_type = LIGHT_POINT;
129}
130
131float PointLight::area(const Transform & /*tfm*/) const
132{
133 /* Sphere area. */
134 const float area = 4.0f * M_PI_F * sqr(radius);
135 return (area == 0.0f) ? 4.0f : area;
136}
137
139 const Scene *scene,
140 const Object *object) const
141{
142 const float invarea = normalize ? 1.0f / area(object->get_tfm()) : 1.0f;
143
144 /* Convert radiant flux to radiance or radiant intensity. */
145 const float eval_fac = invarea * M_1_PI_F;
146
147 uint shader_flags = 0;
148 if (use_mis && radius > 0.0f) {
149 shader_flags |= SHADER_USE_MIS;
150 }
151
152 klight->co = transform_get_translation(&object->get_tfm());
153 klight->spot.radius = radius;
154 klight->spot.eval_fac = eval_fac;
155 klight->spot.is_sphere = is_sphere && radius != 0.0f;
156
157 Light::copy_to_kernel(klight, scene, object, shader_flags);
158}
159
161{
162 NodeType *type = NodeType::add("spotlight", create, NodeType::NONE, PointLight::get_node_type());
163
164 SOCKET_FLOAT(angle, "Angle", M_PI_4_F);
165 SOCKET_FLOAT(smooth, "Smooth", 0.0f);
166
167 return type;
168}
169
171{
172 light_type = LIGHT_SPOT;
173}
174
175void SpotLight::copy_to_kernel(KernelLight *klight, const Scene *scene, const Object *object) const
176{
177 const float cos_half_spot_angle = cosf(angle * 0.5f);
178 const float spot_smooth = 1.0f / ((1.0f - cos_half_spot_angle) * smooth);
179 const float tan_half_spot_angle = tanf(angle * 0.5f);
180
181 const float3 dir = -transform_get_column(&object->get_tfm(), 2);
182 const float len_w_sq = len_squared(dir);
183 const float len_u_sq = len_squared(transform_get_column(&object->get_tfm(), 0));
184 const float len_v_sq = len_squared(transform_get_column(&object->get_tfm(), 1));
185 const float tan_sq = sqr(tan_half_spot_angle);
186
187 klight->spot.dir = safe_normalize(dir);
188 klight->spot.cos_half_spot_angle = cos_half_spot_angle;
189 klight->spot.half_cot_half_spot_angle = 0.5f / tan_half_spot_angle;
190 klight->spot.spot_smooth = spot_smooth;
191 /* Choose the angle which spans a larger cone. */
192 klight->spot.cos_half_larger_spread = inversesqrtf(1.0f + tan_sq * fmaxf(len_u_sq, len_v_sq) /
193 len_w_sq);
194 /* radius / sin(half_angle_small) */
195 klight->spot.ray_segment_dp = radius *
196 sqrtf(1.0f + len_w_sq / (tan_sq * fminf(len_u_sq, len_v_sq)));
197 PointLight::copy_to_kernel(klight, scene, object);
198}
199
201{
202 NodeType *type = NodeType::add("arealight", create, NodeType::NONE, Light::get_node_base_type());
203
204 SOCKET_FLOAT(sizeu, "Size U", 1.0f);
205 SOCKET_FLOAT(sizev, "Size V", 1.0f);
206 SOCKET_BOOLEAN(ellipse, "Ellipse", false);
207 SOCKET_FLOAT(spread, "Spread", M_PI_F);
208 SOCKET_BOOLEAN(is_portal, "Is Portal", false);
209
210 return type;
211}
212
214{
215 light_type = LIGHT_AREA;
216}
217
218float AreaLight::area(const Transform &tfm) const
219{
220 const float3 axisu = transform_get_column(&tfm, 0);
221 const float3 axisv = transform_get_column(&tfm, 1);
222
223 /* Rectangle area. */
224 const float area = len(axisu * sizeu) * len(axisv * sizev);
225 return ellipse ? area * M_PI_4_F : area;
226}
227
228void AreaLight::copy_to_kernel(KernelLight *klight, const Scene *scene, const Object *object) const
229{
230 const float3 extentu = transform_get_column(&object->get_tfm(), 0) * sizeu;
231 const float3 extentv = transform_get_column(&object->get_tfm(), 1) * sizev;
232
233 float len_u;
234 float len_v;
235 const float3 axis_u = normalize_len(extentu, &len_u);
236 const float3 axis_v = normalize_len(extentv, &len_v);
237 const float area_ = area(object->get_tfm());
238 float invarea = ((normalize || is_portal) && area_ != 0.0f) ? 1.0f / area_ : 1.0f;
239
240 if (ellipse) {
241 /* Negative inverse area indicates ellipse. */
242 invarea = -invarea;
243 }
244
245 klight->co = transform_get_translation(&object->get_tfm());
246 klight->area.axis_u = axis_u;
247 klight->area.len_u = len_u;
248 klight->area.axis_v = axis_v;
249 klight->area.len_v = len_v;
250 klight->area.invarea = invarea;
251 klight->area.dir = safe_normalize(-transform_get_column(&object->get_tfm(), 2));
252 klight->object_id = object->index;
253
254 if (is_portal) {
255 return;
256 }
257
258 const float half_spread = 0.5f * fmaxf(spread, 0.0f);
259 const float tan_half_spread = spread == M_PI_F ? FLT_MAX : tanf(half_spread);
260 /* Normalization computed using:
261 * integrate cos(x) * (1 - tan(x) / tan(a)) * sin(x) from x = 0 to a, a being half_spread.
262 * Divided by tan_half_spread to simplify the attenuation computation in `area.h`. */
263 /* Using third-order Taylor expansion at small angles for better accuracy. */
264 const float normalize_spread = (half_spread > 0.0f) ?
265 (half_spread > 0.05f ?
266 1.0f / (tan_half_spread - half_spread) :
267 3.0f / powf(half_spread, 3.0f)) :
268 FLT_MAX;
269
270 uint shader_flags = 0;
271 if (use_mis && area_ != 0.0f && spread > 0.0f) {
272 shader_flags |= SHADER_USE_MIS;
273 }
274
275 klight->area.tan_half_spread = tan_half_spread;
276 klight->area.normalize_spread = normalize_spread;
277
278 Light::copy_to_kernel(klight, scene, object, shader_flags);
279}
280
282{
283 NodeType *type = NodeType::add("sunlight", create, NodeType::NONE, Light::get_node_base_type());
284
285 SOCKET_FLOAT(angle, "Angle", 0.0f);
286
287 return type;
288}
289
291{
292 light_type = LIGHT_SUN;
293}
294
295float SunLight::area(const Transform & /*tfm*/) const
296{
297 /* Sun disk area. */
298 return (angle > 0.0f) ? M_PI_F * sqr(sinf(angle * 0.5f)) : 1.0f;
299}
300
301void SunLight::copy_to_kernel(KernelLight *klight, const Scene *scene, const Object *object) const
302{
303 uint shader_flags = 0;
304 const float half_angle = angle / 2.0f;
305 if (use_mis && half_angle > 0.0f) {
306 shader_flags |= SHADER_USE_MIS;
307 }
308
309 const float one_minus_cosangle = 2.0f * sqr(sinf(0.5f * half_angle));
310 const float pdf = (half_angle > 0.0f) ? (M_1_2PI_F / one_minus_cosangle) : 1.0f;
311
312 klight->co = safe_normalize(-transform_get_column(&object->get_tfm(), 2));
313 klight->sun.angle = half_angle;
314 klight->sun.one_minus_cosangle = one_minus_cosangle;
315 klight->sun.pdf = pdf;
316 klight->sun.eval_fac = normalize ? 1.0f / area(object->get_tfm()) : 1.0f;
317 klight->sun.half_inv_sin_half_angle = (half_angle == 0.0f) ? 0.0f :
318 0.5f / sinf(0.5f * half_angle);
319
320 Light::copy_to_kernel(klight, scene, object, shader_flags);
321}
322
324{
325 NodeType *type = NodeType::add(
326 "backgroundlight", create, NodeType::NONE, Light::get_node_base_type());
327
328 SOCKET_INT(map_resolution, "Map Resolution", 0);
329 SOCKET_FLOAT(average_radiance, "Average Radiance", 0.0f);
330
331 return type;
332}
333
335{
336 light_type = LIGHT_BACKGROUND;
337}
338
339float BackgroundLight::area(const Transform & /*tfm*/) const
340{
341 return 1.0f;
342}
343
345 const Scene *scene,
346 const Object *object) const
347{
348 const uint visibility = scene->background->get_visibility();
349
350 uint shader_flags = SHADER_USE_MIS;
351
352 if (!(visibility & PATH_RAY_VISIBILITY_DIFFUSE)) {
353 shader_flags |= SHADER_EXCLUDE_DIFFUSE;
354 }
355 if (!(visibility & PATH_RAY_VISIBILITY_GLOSSY)) {
356 shader_flags |= SHADER_EXCLUDE_GLOSSY;
357 }
358 if (!(visibility & PATH_RAY_VISIBILITY_TRANSMIT)) {
359 shader_flags |= SHADER_EXCLUDE_TRANSMIT;
360 }
361 if (!(visibility & PATH_RAY_VISIBILITY_VOLUME_SCATTER)) {
362 shader_flags |= SHADER_EXCLUDE_SCATTER;
363 }
364 Light::copy_to_kernel(klight, scene, object, shader_flags);
365}
366
368{
369 if (is_modified()) {
370 scene->light_manager->tag_update(scene, LightManager::LIGHT_MODIFIED);
371 }
372 else {
373 for (const Node *node : get_used_shaders()) {
374 if (node->is_modified()) {
375 /* If the light shader is modified, the number of lights in the scene might change.
376 * Tag light manager for update. */
377 scene->light_manager->tag_update(scene, LightManager::LIGHT_MODIFIED);
378 break;
379 }
380 }
381 }
382}
383
384bool Light::has_contribution(const Scene *scene, const Object *object)
385{
386 if (strength == zero_float3()) {
387 return false;
388 }
389 if (is_portal_light()) {
390 return false;
391 }
392 if (is_background_light()) {
393 /* Will be determined after finishing processing all the lights. */
394 return true;
395 }
396 if (is_area_light()) {
397 const AreaLight *light = static_cast<AreaLight *>(this);
398 if ((light->get_sizeu() * light->get_sizev() == 0.0f) ||
399 is_zero(transform_get_column(&object->get_tfm(), 0)) ||
400 is_zero(transform_get_column(&object->get_tfm(), 1)))
401 {
402 /* Area light with a size of zero does not contribute to the scene. */
403 return false;
404 }
405 }
406
407 const Shader *effective_shader = (get_shader()) ? get_shader() : scene->default_light;
408 return !is_zero(effective_shader->emission_estimate);
409}
410
412{
413 return (used_shaders.empty()) ? nullptr : static_cast<Shader *>(used_shaders[0]);
414}
415
417{
418 /* TODO: implement when this becomes actual geometry. */
419}
420
421void Light::apply_transform(const Transform & /*tfm*/, const bool /*apply_to_motion*/)
422{
423 /* TODO: implement when this becomes actual geometry. */
424}
425
426void Light::get_uv_tiles(ustring /*map*/, unordered_set<int> & /*tiles*/)
427{
428 /* TODO: implement when this becomes actual geometry. */
429}
430
435
436static uint light_object_visibility_flags(const Object *object)
437{
438 const uint visibility = object->get_visibility();
439 uint visibility_flag = 0;
440
441 if (!(visibility & PATH_RAY_VISIBILITY_CAMERA)) {
442 visibility_flag |= SHADER_EXCLUDE_CAMERA;
443 }
444 if (!(visibility & PATH_RAY_VISIBILITY_DIFFUSE)) {
445 visibility_flag |= SHADER_EXCLUDE_DIFFUSE;
446 }
447 if (!(visibility & PATH_RAY_VISIBILITY_GLOSSY)) {
448 visibility_flag |= SHADER_EXCLUDE_GLOSSY;
449 }
450 if (!(visibility & PATH_RAY_VISIBILITY_TRANSMIT)) {
451 visibility_flag |= SHADER_EXCLUDE_TRANSMIT;
452 }
453 if (!(visibility & PATH_RAY_VISIBILITY_VOLUME_SCATTER)) {
454 visibility_flag |= SHADER_EXCLUDE_SCATTER;
455 }
456 if (!(object->get_is_shadow_catcher())) {
457 visibility_flag |= SHADER_EXCLUDE_SHADOW_CATCHER;
458 }
459
460 return visibility_flag;
461}
462
464 const Scene *scene,
465 const Object *object,
466 const uint shader_flags) const
467{
468 klight->type = light_type;
469
470 const Shader *shader = (get_shader()) ? get_shader() : scene->default_light;
471 int shader_id = scene->shader_manager->get_shader_id(shader);
472
473 if (!cast_shadow) {
474 shader_id &= ~SHADER_CAST_SHADOW;
475 }
476
477 shader_id |= light_object_visibility_flags(object);
478
479 klight->shader_id = shader_id | shader_flags;
480 klight->object_id = object->index;
481 klight->max_bounces = max_bounces;
482 copy_v3_v3(klight->strength, strength);
483 klight->use_caustics = use_caustics;
484}
485
486/* Light Manager */
487
495
497{
498 for (Object *object : scene->objects) {
499 if (!object->get_geometry()->is_light()) {
500 continue;
501 }
502
503 Light *light = static_cast<Light *>(object->get_geometry());
504 if (light->is_background_light() && light->is_enabled) {
505 return true;
506 }
507 }
508 return false;
509}
510
512{
513 /* Make all lights enabled by default, and perform some preliminary checks
514 * needed for finer-tuning of settings (for example, check whether we've
515 * got portals or not).
516 */
517 vector<BackgroundLight *> background_lights;
518 size_t num_lights = 0;
519 bool has_portal = false;
520 for (Object *object : scene->objects) {
521 if (!object->get_geometry()->is_light()) {
522 continue;
523 }
524
525 Light *light = static_cast<Light *>(object->get_geometry());
526 light->is_enabled = light->has_contribution(scene, object);
527 has_portal |= light->is_portal_light();
528
529 if (light->is_background_light()) {
530 background_lights.push_back(static_cast<BackgroundLight *>(light));
531 }
532
533 num_lights += light->is_enabled;
534 }
535
536 LOG_INFO << "Total " << num_lights << " lights.";
537
538 bool background_enabled = false;
539 int background_resolution = 0;
540
541 if (!background_lights.empty()) {
542 /* Ignore background light if:
543 * - If unsupported on a device
544 * - If we don't need it (no HDRs etc.)
545 */
546 Shader *shader = scene->background->get_shader(scene);
547 for (BackgroundLight *light : background_lights) {
548 light->is_enabled = has_portal || (light->use_mis && shader->has_surface_spatial_varying);
549 if (light->is_enabled) {
550 background_enabled = true;
551 background_resolution = light->get_map_resolution();
552 }
553 }
554
555 if (!background_enabled) {
556 LOG_INFO << "Background MIS has been disabled.";
557 }
558 }
559
560 if (last_background_enabled != background_enabled ||
561 last_background_resolution != background_resolution)
562 {
563 last_background_enabled = background_enabled;
564 last_background_resolution = background_resolution;
566 }
567}
568
570 DeviceScene *dscene,
571 Scene *scene,
572 Progress &progress)
573{
574 KernelIntegrator *kintegrator = &dscene->data.integrator;
575 if (kintegrator->use_light_tree) {
576 dscene->light_distribution.free();
577 return;
578 }
579
580 /* Update CDF over lights. */
581 progress.set_status("Updating Lights", "Computing distribution");
582
583 /* Counts emissive triangles in the scene. */
584 size_t num_triangles = 0;
585
586 const int num_lights = kintegrator->num_lights;
587 const size_t max_num_triangles = std::numeric_limits<int>::max() - 1 - kintegrator->num_lights;
588 for (Object *object : scene->objects) {
589 if (progress.get_cancel()) {
590 return;
591 }
592
593 if (!object->usable_as_light()) {
594 continue;
595 }
596
597 /* Count emissive triangles. */
598 Mesh *mesh = static_cast<Mesh *>(object->get_geometry());
599 const int mesh_num_triangles = static_cast<int>(mesh->num_triangles());
600
601 for (int i = 0; i < mesh_num_triangles; i++) {
602 const int shader_index = mesh->get_shader()[i];
603 Shader *shader = (shader_index < mesh->get_used_shaders().size()) ?
604 static_cast<Shader *>(mesh->get_used_shaders()[shader_index]) :
605 scene->default_surface;
606
608 num_triangles++;
609 }
610 }
611
612 if (num_triangles > max_num_triangles) {
613 progress.set_error(
614 "Number of emissive triangles exceeds the limit, consider using Light Tree or disabling "
615 "Emission Sampling on some emissive materials");
616 }
617 }
618
619 const size_t num_distribution = num_triangles + num_lights;
620
621 /* Distribution size. */
622 kintegrator->num_distribution = num_distribution;
623
624 LOG_INFO << "Use light distribution with " << num_distribution << " emitters.";
625
626 /* Emission area. */
627 KernelLightDistribution *distribution = dscene->light_distribution.alloc(num_distribution + 1);
628 float totarea = 0.0f;
629
630 /* Triangles. */
631 size_t offset = 0;
632
633 for (Object *object : scene->objects) {
634 if (progress.get_cancel()) {
635 return;
636 }
637
638 if (!object->usable_as_light()) {
639 continue;
640 }
641 /* Sum area. */
642 Mesh *mesh = static_cast<Mesh *>(object->get_geometry());
643 const bool transform_applied = mesh->transform_applied;
644 const Transform tfm = object->get_tfm();
645 const int visibility_flag = light_object_visibility_flags(object);
646
647 const size_t mesh_num_triangles = mesh->num_triangles();
648 const packed_float3 *mesh_positions = mesh->get_position();
649 for (size_t i = 0; i < mesh_num_triangles; i++) {
650 const int shader_index = mesh->get_shader()[i];
651 Shader *shader = (shader_index < mesh->get_used_shaders().size()) ?
652 static_cast<Shader *>(mesh->get_used_shaders()[shader_index]) :
653 scene->default_surface;
654
656 distribution[offset].totarea = totarea;
657 distribution[offset].prim = i + mesh->prim_offset;
658 distribution[offset].visibility_flag = visibility_flag;
659 distribution[offset].object_id = object->index;
660 offset++;
661
662 const Mesh::Triangle t = mesh->get_triangle(i);
663 if (!t.valid(mesh_positions)) {
664 continue;
665 }
666 float3 p1 = mesh_positions[t.v[0]];
667 float3 p2 = mesh_positions[t.v[1]];
668 float3 p3 = mesh_positions[t.v[2]];
669
670 if (!transform_applied) {
671 p1 = transform_point(&tfm, p1);
672 p2 = transform_point(&tfm, p2);
673 p3 = transform_point(&tfm, p3);
674 }
675
676 totarea += triangle_area(p1, p2, p3);
677 }
678 }
679 }
680
681 const float trianglearea = totarea;
682
683 /* Lights. */
684 int light_index = 0;
685
686 if (num_lights > 0) {
687 const float lightarea = (totarea > 0.0f) ? totarea / num_lights : 1.0f;
688 for (Object *object : scene->objects) {
689 if (!object->get_geometry()->is_light()) {
690 continue;
691 }
692
693 Light *light = static_cast<Light *>(object->get_geometry());
694 if (!light->is_enabled) {
695 continue;
696 }
697
698 distribution[offset].totarea = totarea;
699 distribution[offset].prim = ~light_index;
700 distribution[offset].object_id = object->index;
701 distribution[offset].visibility_flag = 0;
702 totarea += lightarea;
703
704 light_index++;
705 offset++;
706 }
707 }
708
709 /* normalize cumulative distribution functions */
710 distribution[num_distribution].totarea = totarea;
711 distribution[num_distribution].prim = 0;
712 distribution[num_distribution].object_id = OBJECT_NONE;
713 distribution[num_distribution].visibility_flag = 0;
714
715 if (totarea > 0.0f) {
716 for (size_t i = 0; i < num_distribution; i++) {
717 distribution[i].totarea /= totarea;
718 }
719 distribution[num_distribution].totarea = 1.0f;
720 }
721
722 if (progress.get_cancel()) {
723 return;
724 }
725
726 /* Update integrator state. */
727 kintegrator->use_direct_light = (totarea > 0.0f);
728
729 /* Precompute pdfs for distribution sampling.
730 * Sample one, with 0.5 probability of light or triangle. */
731 kintegrator->distribution_pdf_triangles = 0.0f;
732 kintegrator->distribution_pdf_lights = 0.0f;
733
734 if (trianglearea > 0.0f) {
735 kintegrator->distribution_pdf_triangles = 1.0f / trianglearea;
736 if (num_lights) {
737 kintegrator->distribution_pdf_triangles *= 0.5f;
738 }
739 }
740
741 if (num_lights) {
742 kintegrator->distribution_pdf_lights = 1.0f / num_lights;
743 if (trianglearea > 0.0f) {
744 kintegrator->distribution_pdf_lights *= 0.5f;
745 }
746 }
747
748 /* Copy distribution to device. */
750}
751
752/* Arguments for functions to convert the light tree to the kernel representation. */
754 const Scene *scene;
759
760 /* Map from instance node to its node index. */
761 std::unordered_map<LightTreeNode *, int> instances;
762};
763
765 const LightTreeNode &node,
766 const int left_child,
767 const int right_child)
768{
769 /* Convert node to kernel representation. */
770 knode.energy = node.measure.energy;
771
772 knode.bbox.min = node.measure.bbox.min;
773 knode.bbox.max = node.measure.bbox.max;
774
775 knode.bcone.axis = node.measure.bcone.axis;
776 knode.bcone.theta_o = node.measure.bcone.theta_o;
777 knode.bcone.theta_e = node.measure.bcone.theta_e;
778
779 knode.bit_trail = node.bit_trail;
780 knode.bit_skip = 0;
781 knode.type = static_cast<LightTreeNodeType>(node.type);
782
783 if (node.is_leaf() || node.is_distant()) {
784 knode.num_emitters = node.get_leaf().num_emitters;
785 knode.leaf.first_emitter = node.get_leaf().first_emitter_index;
786 }
787 else if (node.is_inner()) {
788 knode.num_emitters = -1;
789 knode.inner.left_child = left_child;
790 knode.inner.right_child = right_child;
791 }
792}
793
794static int light_tree_flatten(LightTreeFlatten &flatten,
795 const LightTreeNode *node,
796 KernelLightTreeNode *knodes,
797 KernelLightTreeEmitter *kemitters,
798 int &next_node_index);
799
801 const LightTreeNode &node,
802 KernelLightTreeNode *knodes,
803 KernelLightTreeEmitter *kemitters,
804 int &next_node_index)
805{
806 /* Convert emitters to kernel representation. */
807 for (int i = 0; i < node.get_leaf().num_emitters; i++) {
808 const int emitter_index = i + node.get_leaf().first_emitter_index;
809 const LightTreeEmitter &emitter = flatten.emitters[emitter_index];
810 KernelLightTreeEmitter &kemitter = kemitters[emitter_index];
811
812 kemitter.energy = emitter.measure.energy;
813 kemitter.theta_o = emitter.measure.bcone.theta_o;
814 kemitter.theta_e = emitter.measure.bcone.theta_e;
815
816 if (emitter.is_triangle()) {
817 /* Triangle. */
818 Object *object = flatten.scene->objects[emitter.object_id];
819 Mesh *mesh = static_cast<Mesh *>(object->get_geometry());
820 Shader *shader = static_cast<Shader *>(
821 mesh->get_used_shaders()[mesh->get_shader()[emitter.prim_id]]);
822
823 kemitter.triangle.id = emitter.prim_id + mesh->prim_offset;
825 kemitter.object_id = emitter.object_id;
826 kemitter.triangle.emission_sampling = shader->emission_sampling;
827 flatten.triangle_array[emitter.prim_id + flatten.object_lookup_offset[emitter.object_id]] =
828 emitter_index;
829 }
830 else if (emitter.is_light()) {
831 /* Light object. */
832 kemitter.light.id = emitter.prim_id;
833 kemitter.visibility_flag = 0;
834 kemitter.object_id = emitter.object_id;
835 flatten.light_array[emitter.object_id] = emitter_index;
836 }
837 else {
838 /* Mesh instance. */
839 assert(emitter.is_mesh());
840 kemitter.mesh.object_id = emitter.object_id;
841 kemitter.visibility_flag = 0;
842 kemitter.object_id = OBJECT_NONE;
843 flatten.light_array[emitter.object_id] = emitter_index;
844
845 /* Create instance node. One instance node will be the same as the
846 * reference node, and for that it will recursively build the subtree. */
847 LightTreeNode *instance_node = emitter.root.get();
848 LightTreeNode *reference_node = instance_node->get_reference();
849
850 auto map_it = flatten.instances.find(reference_node);
851 if (map_it == flatten.instances.end()) {
852 if (instance_node != reference_node) {
853 /* Flatten the node with the subtree first so the subsequent instances know the index.
854 */
855 std::swap(instance_node->type, reference_node->type);
856 std::swap(instance_node->variant_type, reference_node->variant_type);
857 }
858 instance_node->type &= ~LIGHT_TREE_INSTANCE;
859 }
860
861 kemitter.mesh.node_id = light_tree_flatten(
862 flatten, instance_node, knodes, kemitters, next_node_index);
863
864 KernelLightTreeNode &kinstance_node = knodes[kemitter.mesh.node_id];
865 kinstance_node.bit_trail = node.bit_trail;
866
867 if (map_it != flatten.instances.end()) {
868 kinstance_node.instance.reference = map_it->second;
869 }
870 else {
871 flatten.instances[reference_node] = kemitter.mesh.node_id;
872 }
873 }
874 kemitter.bit_trail = node.bit_trail;
875 }
876}
877
879 const LightTreeNode *node,
880 KernelLightTreeNode *knodes,
881 KernelLightTreeEmitter *kemitters,
882 int &next_node_index)
883{
884 /* Convert both inner nodes and primitives to device representation. */
885 const int node_index = next_node_index++;
886 int left_child = -1;
887 int right_child = -1;
888
889 if (node->is_leaf() || node->is_distant()) {
890 light_tree_leaf_emitters_copy_and_flatten(flatten, *node, knodes, kemitters, next_node_index);
891 }
892 else if (node->is_inner()) {
893 left_child = light_tree_flatten(flatten,
894 node->get_inner().children[LightTree::left].get(),
895 knodes,
896 kemitters,
897 next_node_index);
898 right_child = light_tree_flatten(flatten,
899 node->get_inner().children[LightTree::right].get(),
900 knodes,
901 kemitters,
902 next_node_index);
903 }
904 else {
905 /* Instance node that is not inner or leaf, but just references another. */
906 assert(node->is_instance());
907 }
908
909 light_tree_node_copy_to_device(knodes[node_index], *node, left_child, right_child);
910
911 return node_index;
912}
913
915 const LightTreeNode *node,
916 KernelLightTreeNode *knodes,
917 KernelLightTreeEmitter *kemitters,
918 int &next_node_index)
919{
920 /* Convert only emitters to device representation. */
921 if (node->is_leaf() || node->is_distant()) {
922 light_tree_leaf_emitters_copy_and_flatten(flatten, *node, knodes, kemitters, next_node_index);
923 }
924 else {
925 assert(node->is_inner());
926
928 node->get_inner().children[LightTree::left].get(),
929 knodes,
930 kemitters,
931 next_node_index);
933 node->get_inner().children[LightTree::right].get(),
934 knodes,
935 kemitters,
936 next_node_index);
937 }
938}
939
940static std::pair<int, LightTreeMeasure> light_tree_specialize_nodes_flatten(
941 const LightTreeFlatten &flatten,
943 const uint64_t light_link_mask,
944 const int depth,
946 int &next_node_index,
947 bool can_share = true)
948{
949 assert(!node->is_instance());
950
951 /* Convert inner nodes to device representation, specialized for light linking. */
952 int node_index;
953 int left_child = -1;
954 int right_child = -1;
955
956 LightTreeNode new_node(LightTreeMeasure::empty, node->bit_trail);
957
958 if (depth == 0 && !(node->light_link.set_membership & light_link_mask)) {
959 /* Ensure there is always a root node. */
960 node_index = next_node_index++;
961 new_node.make_leaf(-1, 0);
962 }
963 else if (can_share && node->light_link.shareable && node->light_link.shared_node_index != -1) {
964 /* Share subtree already built for another light link set. */
965 return std::make_pair(node->light_link.shared_node_index, node->measure);
966 }
967 else if (node->is_leaf() || node->is_distant()) {
968 /* Specialize leaf node. */
969 node_index = next_node_index++;
970 int first_emitter = -1;
971 int num_emitters = 0;
972
973 for (int i = 0; i < node->get_leaf().num_emitters; i++) {
974 const LightTreeEmitter &emitter = flatten.emitters[node->get_leaf().first_emitter_index + i];
975 if (emitter.light_set_membership & light_link_mask) {
976 /* Assumes emitters are consecutive due to LightTree::sort_leaf. */
977 if (first_emitter == -1) {
978 first_emitter = node->get_leaf().first_emitter_index + i;
979 }
980 num_emitters++;
981 new_node.measure.add(emitter.measure);
982 }
983 }
984
985 assert(first_emitter != -1);
986
987 /* Preserve the type of the node, so that the kernel can do proper decision when sampling
988 * node with multiple distant lights in it. */
989 if (node->is_leaf()) {
990 new_node.make_leaf(first_emitter, num_emitters);
991 }
992 else {
993 new_node.make_distant(first_emitter, num_emitters);
994 }
995 }
996 else {
997 assert(node->is_inner());
998 assert(new_node.is_inner());
999
1000 /* Specialize inner node. */
1001 LightTreeNode *left_node = node->get_inner().children[LightTree::left].get();
1002 LightTreeNode *right_node = node->get_inner().children[LightTree::right].get();
1003
1004 /* Skip nodes that have only one child. We have a single bit trail for each
1005 * primitive, bit_skip is incremented in the child node to skip the bit for
1006 * this parent node. */
1007 LightTreeNode *only_node = nullptr;
1008 if (!(left_node->light_link.set_membership & light_link_mask)) {
1009 only_node = right_node;
1010 }
1011 else if (!(right_node->light_link.set_membership & light_link_mask)) {
1012 only_node = left_node;
1013 }
1014 if (only_node) {
1015 /* Can not share the node as its bit_skip will be modified.
1016 * Also don't store shareable_index so other branches of the tree that do not skip any nodes
1017 * do not share node created here. */
1018 const auto [only_index, only_measure] = light_tree_specialize_nodes_flatten(
1019 flatten, only_node, light_link_mask, depth + 1, knodes, next_node_index, false);
1020
1021 assert(only_index != -1);
1022 knodes[only_index].bit_skip++;
1023 return std::make_pair(only_index, only_measure);
1024 }
1025
1026 /* Create inner node. */
1027 node_index = next_node_index++;
1028
1029 const auto [left_index, left_measure] = light_tree_specialize_nodes_flatten(
1030 flatten, left_node, light_link_mask, depth + 1, knodes, next_node_index);
1031 const auto [right_index, right_measure] = light_tree_specialize_nodes_flatten(
1032 flatten, right_node, light_link_mask, depth + 1, knodes, next_node_index);
1033
1034 new_node.measure = left_measure;
1035 new_node.measure.add(right_measure);
1036
1037 left_child = left_index;
1038 right_child = right_index;
1039 }
1040
1041 /* Convert to kernel node. */
1042 if (knodes.size() <= node_index) {
1043 knodes.resize(node_index + 1);
1044 }
1045 light_tree_node_copy_to_device(knodes[node_index], new_node, left_child, right_child);
1046
1047 if (node->light_link.shareable) {
1048 node->light_link.shared_node_index = node_index;
1049 }
1050
1051 return std::make_pair(node_index, new_node.measure);
1052}
1053
1055 DeviceScene *dscene,
1056 Scene *scene,
1057 Progress &progress)
1058{
1059 KernelIntegrator *kintegrator = &dscene->data.integrator;
1060
1061 if (!kintegrator->use_light_tree) {
1062 return;
1063 }
1064
1065 /* Update light tree. */
1066 progress.set_status("Updating Lights", "Computing tree");
1067
1068 /* TODO: For now, we'll start with a smaller number of max lights in a node.
1069 * More benchmarking is needed to determine what number works best. */
1070 LightTree light_tree(scene, dscene, progress, 8);
1071 LightTreeNode *root = light_tree.build(scene, dscene);
1072 if (progress.get_cancel()) {
1073 return;
1074 }
1075
1076 /* Create arguments for recursive tree flatten. */
1077 LightTreeFlatten flatten;
1078 flatten.scene = scene;
1079 flatten.emitters = light_tree.get_emitters();
1081 /* We want to create separate arrays corresponding to triangles and lights,
1082 * which will be used to index back into the light tree for PDF calculations. */
1083 flatten.light_array = dscene->light_to_tree.alloc(scene->objects.size());
1084 flatten.triangle_array = dscene->triangle_to_tree.alloc(light_tree.num_triangles);
1085
1086 /* Allocate emitters */
1087 const size_t num_emitters = light_tree.num_emitters();
1088 KernelLightTreeEmitter *kemitters = dscene->light_tree_emitters.alloc(num_emitters);
1089
1090 /* Update integrator state. */
1091 kintegrator->use_direct_light = num_emitters > 0;
1092
1093 /* Test if light linking is used. */
1094 const bool use_light_linking = root && (light_tree.light_link_receiver_used != 1);
1095 KernelLightLinkSet *klight_link_sets = dscene->data.light_link_sets;
1096 memset(klight_link_sets, 0, sizeof(dscene->data.light_link_sets));
1097
1098 LOG_INFO << "Use light tree with " << num_emitters << " emitters and " << light_tree.num_nodes
1099 << " nodes.";
1100
1101 if (!use_light_linking) {
1102 /* Regular light tree without linking. */
1103 KernelLightTreeNode *knodes = dscene->light_tree_nodes.alloc(light_tree.num_nodes);
1104
1105 if (root) {
1106 int next_node_index = 0;
1107 light_tree_flatten(flatten, root, knodes, kemitters, next_node_index);
1108 }
1109 }
1110 else {
1111 int next_node_index = 0;
1112
1113 vector<KernelLightTreeNode> light_link_nodes;
1114
1115 /* Write primitives, and any subtrees for instances. */
1116 if (root) {
1117 /* Reserve enough size of all instance subtrees, then shrink back to
1118 * actual number of nodes used. */
1119 light_link_nodes.resize(light_tree.num_nodes);
1121 flatten, root, light_link_nodes.data(), kemitters, next_node_index);
1122 light_link_nodes.resize(next_node_index);
1123 }
1124
1125 /* Specialized light trees for linking. */
1126 for (uint64_t tree_index = 0; tree_index < LIGHT_LINK_SET_MAX; tree_index++) {
1127 const uint64_t tree_mask = uint64_t(1) << tree_index;
1128 if (!(light_tree.light_link_receiver_used & tree_mask)) {
1129 continue;
1130 }
1131
1132 if (root) {
1133 klight_link_sets[tree_index].light_tree_root =
1135 flatten, root, tree_mask, 0, light_link_nodes, next_node_index)
1136 .first;
1137 }
1138 }
1139
1140 /* Allocate and copy nodes into device array. */
1141 KernelLightTreeNode *knodes = dscene->light_tree_nodes.alloc(light_link_nodes.size());
1142 memcpy(knodes, light_link_nodes.data(), light_link_nodes.size() * sizeof(*knodes));
1143
1144 LOG_INFO << "Specialized light tree for light linking, with "
1145 << light_link_nodes.size() - light_tree.num_nodes << " additional nodes.";
1146 }
1147
1148 /* Copy arrays to device. */
1151 dscene->light_to_tree.copy_to_device();
1154}
1155
1156static void background_cdf(int start,
1157 const int end,
1158 const int res_x,
1159 const int res_y,
1160 const vector<float3> *pixels,
1161 float2 *cond_cdf)
1162{
1163 const int cdf_width = res_x + 1;
1164 /* Conditional CDFs (rows, U direction). */
1165 for (int i = start; i < end; i++) {
1166 const float sin_theta = sinf(M_PI_F * (i + 0.5f) / res_y);
1167 float3 env_color = (*pixels)[i * res_x];
1168 float ave_luminance = average(fabs(env_color));
1169
1170 cond_cdf[i * cdf_width].x = ave_luminance * sin_theta;
1171 cond_cdf[i * cdf_width].y = 0.0f;
1172
1173 for (int j = 1; j < res_x; j++) {
1174 env_color = (*pixels)[i * res_x + j];
1175 ave_luminance = average(fabs(env_color));
1176
1177 cond_cdf[i * cdf_width + j].x = ave_luminance * sin_theta;
1178 cond_cdf[i * cdf_width + j].y = cond_cdf[i * cdf_width + j - 1].y +
1179 cond_cdf[i * cdf_width + j - 1].x / res_x;
1180 }
1181
1182 const float cdf_total = cond_cdf[i * cdf_width + res_x - 1].y +
1183 cond_cdf[i * cdf_width + res_x - 1].x / res_x;
1184
1185 /* stuff the total into the brightness value for the last entry, because
1186 * we are going to normalize the CDFs to 0.0 to 1.0 afterwards */
1187 cond_cdf[i * cdf_width + res_x].x = cdf_total;
1188
1189 if (cdf_total > 0.0f) {
1190 const float cdf_total_inv = 1.0f / cdf_total;
1191 for (int j = 1; j < res_x; j++) {
1192 cond_cdf[i * cdf_width + j].y *= cdf_total_inv;
1193 }
1194 }
1195
1196 cond_cdf[i * cdf_width + res_x].y = 1.0f;
1197 }
1198}
1199
1201 DeviceScene *dscene,
1202 Scene *scene,
1203 Progress &progress)
1204{
1205 KernelIntegrator *kintegrator = &dscene->data.integrator;
1206 KernelBackground *kbackground = &dscene->data.background;
1207 BackgroundLight *background_light = nullptr;
1208
1209 bool background_mis = false;
1210
1211 /* find background light */
1212 for (Object *object : scene->objects) {
1213 if (!object->get_geometry()->is_light()) {
1214 continue;
1215 }
1216
1217 Light *light = static_cast<Light *>(object->get_geometry());
1218 if (light->is_background_light() && light->is_enabled) {
1219 background_light = static_cast<BackgroundLight *>(light);
1220 background_mis |= light->use_mis;
1221 }
1222 }
1223
1224 kbackground->portal_weight = kintegrator->num_portals > 0 ? 1.0f : 0.0f;
1225 kbackground->map_weight = background_mis ? 1.0f : 0.0f;
1226 kbackground->sun_weight = 0.0f;
1227
1228 /* no background light found, signal renderer to skip sampling */
1229 if (!background_light || !background_light->is_enabled) {
1230 kbackground->map_res_x = 0;
1231 kbackground->map_res_y = 0;
1232 kbackground->map_dD = FLT_MAX;
1233 kbackground->use_mis = (kbackground->portal_weight > 0.0f);
1234 return;
1235 }
1236
1237 progress.set_status("Updating Lights", "Importance map");
1238
1239 int2 environment_res = make_int2(0, 0);
1240 Shader *shader = scene->background->get_shader(scene);
1241 int num_suns = 0;
1242 float sun_average_radiance = 0.0f;
1243 for (ShaderNode *node : shader->graph->nodes) {
1244 if (node->type == EnvironmentTextureNode::get_node_type()) {
1246 if (!env->handle.empty()) {
1247 const ImageMetaData metadata = env->handle.metadata(progress);
1248 environment_res.x = max(environment_res.x, (int)metadata.width);
1249 environment_res.y = max(environment_res.y, (int)metadata.height);
1250 }
1251 }
1252 if (node->type == SkyTextureNode::get_node_type()) {
1254 if (sky->get_sun_disc()) {
1255 /* Ensure that the input coordinates aren't transformed before they reach the node.
1256 * If that is the case, the logic used for sampling the Sun's location does not work
1257 * and we have to fall back to map-based sampling. */
1258 const ShaderInput *vec_in = sky->input("Vector");
1259 if (vec_in && vec_in->link && vec_in->link->parent) {
1260 ShaderNode *vec_src = vec_in->link->parent;
1261 if ((vec_src->type != TextureCoordinateNode::get_node_type()) ||
1262 (vec_in->link != vec_src->output("Generated")))
1263 {
1264 environment_res.x = max(environment_res.x, 4096);
1265 environment_res.y = max(environment_res.y, 2048);
1266 continue;
1267 }
1268 }
1269
1270 /* Determine Sun direction from lat/long and texture mapping. */
1271 const float latitude = sky->get_sun_elevation();
1272 const float longitude = sky->get_sun_rotation() + M_PI_2_F;
1274 cosf(latitude) * cosf(longitude), cosf(latitude) * sinf(longitude), sinf(latitude));
1275 const Transform sky_transform = transform_inverse(sky->tex_mapping.compute_transform());
1277
1278 /* Pack Sun direction and size. */
1279 const float half_angle = sky->get_sun_size() * 0.5f;
1280 kbackground->sun = make_float4(sun_direction, half_angle);
1281
1282 /* Empirical value */
1283 kbackground->sun_weight = 4.0f;
1284 sun_average_radiance = sky->get_sun_average_radiance();
1285 environment_res.x = max(environment_res.x, 512);
1286 environment_res.y = max(environment_res.y, 256);
1287 num_suns++;
1288 }
1289 }
1290 }
1291
1292 /* If there's more than one Sun, fall back to map sampling instead. */
1293 kbackground->use_sun_guiding = (num_suns == 1);
1294 if (!kbackground->use_sun_guiding) {
1295 kbackground->sun_weight = 0.0f;
1296 environment_res.x = max(environment_res.x, 4096);
1297 environment_res.y = max(environment_res.y, 2048);
1298 }
1299
1300 /* Enable MIS for background sampling if any strategy is active. */
1301 kbackground->use_mis = (kbackground->portal_weight + kbackground->map_weight +
1302 kbackground->sun_weight) > 0.0f;
1303
1304 /* get the resolution from the light's size (we stuff it in there) */
1305 int2 res = make_int2(background_light->get_map_resolution(),
1306 background_light->get_map_resolution() / 2);
1307 /* If the resolution isn't set manually, try to find an environment texture. */
1308 if (res.x == 0) {
1309 res = environment_res;
1310 if (res.x > 0 && res.y > 0) {
1311 LOG_INFO << "Automatically set World MIS resolution to " << res.x << " by " << res.y;
1312 }
1313 }
1314 /* If it's still unknown, just use the default. */
1315 if (res.x == 0 || res.y == 0) {
1316 res = make_int2(1024, 512);
1317 LOG_INFO << "Setting World MIS resolution to default";
1318 }
1319 kbackground->map_res_x = res.x;
1320 kbackground->map_res_y = res.y;
1321
1322 /* Minimum ray differential for one importance map pixels, using the minimum of both
1323 * dimensions to account for non-square maps.
1324 * See #background_light_clamp_dD for motivation. */
1325 kbackground->map_dD = (kbackground->map_weight > 0.0f && res.x > 0 && res.y > 0) ?
1326 min(M_PI_F / res.y, M_2PI_F / res.x) :
1327 FLT_MAX;
1328
1329 vector<float3> pixels;
1330 shade_background_pixels(device, dscene, res.x, res.y, pixels, progress);
1331
1332 if (progress.get_cancel()) {
1333 return;
1334 }
1335
1336 /* build row distributions and column distribution for the infinite area environment light */
1337 const int cdf_width = res.x + 1;
1338 float2 *marg_cdf = dscene->light_background_marginal_cdf.alloc(res.y + 1);
1339 float2 *cond_cdf = dscene->light_background_conditional_cdf.alloc(cdf_width * res.y);
1340
1341 const double time_start = time_dt();
1342
1343 /* Create CDF in parallel. */
1344 const int rows_per_task = divide_up(10240, res.x);
1345 parallel_for(blocked_range<size_t>(0, res.y, rows_per_task),
1346 [&](const blocked_range<size_t> &r) {
1347 background_cdf(r.begin(), r.end(), res.x, res.y, &pixels, cond_cdf);
1348 });
1349
1350 /* marginal CDFs (column, V direction, sum of rows) */
1351 marg_cdf[0].x = cond_cdf[res.x].x;
1352 marg_cdf[0].y = 0.0f;
1353
1354 for (int i = 1; i < res.y; i++) {
1355 marg_cdf[i].x = cond_cdf[i * cdf_width + res.x].x;
1356 marg_cdf[i].y = marg_cdf[i - 1].y + marg_cdf[i - 1].x / res.y;
1357 }
1358
1359 const float cdf_total = marg_cdf[res.y - 1].y + marg_cdf[res.y - 1].x / res.y;
1360 marg_cdf[res.y].x = cdf_total;
1361
1362 const float map_average_radiance = cdf_total * M_PI_2_F;
1363 if (sun_average_radiance > 0.0f) {
1364 /* The weighting here is just a heuristic that was empirically determined.
1365 * The Sun's average radiance is much higher than the map's average radiance,
1366 * but we don't want to weight the background light too much because
1367 * visibility is not accounted for anyway. */
1368 background_light->set_average_radiance(0.8f * map_average_radiance +
1369 0.2f * sun_average_radiance);
1370 }
1371 else {
1372 background_light->set_average_radiance(map_average_radiance);
1373 }
1374
1375 if (cdf_total > 0.0f) {
1376 for (int i = 1; i < res.y; i++) {
1377 marg_cdf[i].y /= cdf_total;
1378 }
1379 }
1380
1381 marg_cdf[res.y].y = 1.0f;
1382
1383 LOG_DEBUG << "Background MIS build time " << time_dt() - time_start;
1384
1385 /* update device */
1388}
1389
1390void LightManager::count_lights(KernelIntegrator *kintegrator, const Scene *scene)
1391{
1392 size_t num_lights = 0;
1393 size_t num_portals = 0;
1394 size_t num_background_lights = 0;
1395 size_t num_distant_lights = 0;
1396
1397 for (const Object *object : scene->objects) {
1398 if (!object->get_geometry()->is_light()) {
1399 continue;
1400 }
1401
1402 const Light *light = static_cast<const Light *>(object->get_geometry());
1403 if (light->is_enabled) {
1404 num_lights++;
1405 num_distant_lights += light->is_distant_light();
1406 num_background_lights += light->is_background_light();
1407 }
1408 num_portals += light->is_portal_light();
1409 }
1410
1411 /* Update integrator settings. */
1412 kintegrator->num_lights = num_lights;
1413 kintegrator->num_distant_lights = num_distant_lights;
1414 kintegrator->num_background_lights = num_background_lights;
1415 kintegrator->num_portals = num_portals;
1416 kintegrator->portal_offset = num_lights;
1417}
1418
1420{
1421 KernelIntegrator *kintegrator = &dscene->data.integrator;
1422 kintegrator->use_light_tree = scene->integrator->get_use_light_tree();
1423 kintegrator->use_light_mis = scene->use_light_mis();
1424
1425 /* Create KernelLight for every portal and enabled light in the scene. */
1426 count_lights(kintegrator, scene);
1427 KernelLight *klights = dscene->lights.alloc(kintegrator->num_lights + kintegrator->num_portals);
1428
1429 int light_index = 0;
1430 int portal_index = kintegrator->num_lights;
1431
1432 for (const Object *object : scene->objects) {
1433 if (!object->get_geometry()->is_light()) {
1434 continue;
1435 }
1436
1437 const Light *light = static_cast<const Light *>(object->get_geometry());
1438 if (light->is_portal_light()) {
1439 light->copy_to_kernel(klights + portal_index, scene, object);
1440 portal_index++;
1441 }
1442 else if (light->is_enabled) {
1443 light->copy_to_kernel(klights + light_index, scene, object);
1444 light_index++;
1445 }
1446 }
1447
1448 LOG_INFO << "Number of lights sent to the device: " << kintegrator->num_lights;
1449
1450 dscene->lights.copy_to_device();
1451}
1452
1454 DeviceScene *dscene,
1455 Scene *scene,
1456 Progress &progress)
1457{
1458 if (!need_update()) {
1459 return;
1460 }
1461
1462 const scoped_callback_timer timer([scene](double time) {
1463 if (scene->update_stats) {
1464 scene->update_stats->light.times.add_entry({"device_update", time});
1465 }
1466 });
1467
1468 /* Detect which lights are enabled, also determines if we need to update the background. */
1469 test_enabled_lights(scene);
1470
1471 device_free(device, dscene, need_update_background);
1472
1473 device_update_lights(dscene, scene);
1474 if (progress.get_cancel()) {
1475 return;
1476 }
1477
1479 device_update_background(device, dscene, scene, progress);
1480 if (progress.get_cancel()) {
1481 return;
1482 }
1483 }
1484
1485 device_update_distribution(device, dscene, scene, progress);
1486 if (progress.get_cancel()) {
1487 return;
1488 }
1489
1490 device_update_tree(device, dscene, scene, progress);
1491 if (progress.get_cancel()) {
1492 return;
1493 }
1494
1495 device_update_ies(dscene);
1496 if (progress.get_cancel()) {
1497 return;
1498 }
1499
1501 need_update_background = false;
1502}
1503
1505 DeviceScene *dscene,
1506 const bool free_background)
1507{
1508 dscene->light_tree_nodes.free();
1509 dscene->light_tree_emitters.free();
1510 dscene->light_to_tree.free();
1511 dscene->object_lookup_offset.free();
1512 dscene->triangle_to_tree.free();
1513
1514 dscene->light_distribution.free();
1515 dscene->lights.free();
1516 if (free_background) {
1519 }
1520 dscene->ies_lights.free();
1521}
1522
1523void LightManager::tag_update(Scene * /*scene*/, uint32_t flag)
1524{
1525 update_flags |= flag;
1526}
1527
1529{
1530 return update_flags != UPDATE_NONE;
1531}
1532
1533int LightManager::add_ies_from_file(const string &filename)
1534{
1535 string content;
1536 bool log_parsing_error = true;
1537
1538 if (!filename.empty()) {
1539 if (!path_read_text(filename, content)) {
1540 LOG_ERROR << "Could not read IES file from " << filename;
1541 log_parsing_error = false;
1542 }
1543 }
1544 else {
1545 log_parsing_error = false;
1546 }
1547
1548 return add_ies(content, log_parsing_error);
1549}
1550
1551int LightManager::add_ies(const string &content, const bool log_parsing_error)
1552{
1553 const uint hash = hash_string(content.c_str());
1554
1555 const thread_scoped_lock ies_lock(ies_mutex);
1556
1557 /* Check whether this IES already has a slot. */
1558 size_t slot;
1559 for (slot = 0; slot < ies_slots.size(); slot++) {
1560 if (ies_slots[slot]->hash == hash) {
1561 ies_slots[slot]->users++;
1562 return slot;
1563 }
1564 }
1565
1566 /* Try to find an empty slot for the new IES. */
1567 for (slot = 0; slot < ies_slots.size(); slot++) {
1568 if (ies_slots[slot]->users == 0 && ies_slots[slot]->hash == 0) {
1569 break;
1570 }
1571 }
1572
1573 /* If there's no free slot, add one. */
1574 if (slot == ies_slots.size()) {
1575 ies_slots.push_back(make_unique<IESSlot>());
1576 }
1577
1578 const bool valid_ies = ies_slots[slot]->ies.load(content);
1579 if (!valid_ies && log_parsing_error) {
1580 LOG_ERROR << "Could not parse IES file, invalid content";
1581 }
1582
1583 ies_slots[slot]->users = 1;
1584 ies_slots[slot]->hash = hash;
1585
1588
1589 return slot;
1590}
1591
1592void LightManager::remove_ies(const int slot)
1593{
1594 const thread_scoped_lock ies_lock(ies_mutex);
1595
1596 if (slot < 0 || slot >= ies_slots.size()) {
1597 assert(false);
1598 return;
1599 }
1600
1601 assert(ies_slots[slot]->users > 0);
1602 ies_slots[slot]->users--;
1603
1604 /* If the slot has no more users, update the device to remove it. */
1605 if (ies_slots[slot]->users == 0) {
1608 }
1609}
1610
1612{
1613 /* Clear empty slots. */
1614 for (const unique_ptr<IESSlot> &slot : ies_slots) {
1615 if (slot->users == 0) {
1616 slot->hash = 0;
1617 slot->ies.clear();
1618 }
1619 }
1620
1621 /* Shrink the slot table by removing empty slots at the end. */
1622 int slot_end;
1623 for (slot_end = ies_slots.size(); slot_end; slot_end--) {
1624 if (ies_slots[slot_end - 1]->users > 0) {
1625 /* If the preceding slot has users, we found the new end of the table. */
1626 break;
1627 }
1628 }
1629 ies_slots.resize(slot_end);
1630
1631 if (!ies_slots.empty()) {
1632 int packed_size = 0;
1633 for (const unique_ptr<IESSlot> &slot : ies_slots) {
1634 packed_size += slot->ies.packed_size();
1635 }
1636
1637 /* ies_lights starts with an offset table that contains the offset of every slot,
1638 * or -1 if the slot is invalid.
1639 * Following that table, the packed valid IES lights are stored. */
1640 float *data = dscene->ies_lights.alloc(ies_slots.size() + packed_size);
1641
1642 int offset = ies_slots.size();
1643 for (int i = 0; i < ies_slots.size(); i++) {
1644 const int size = ies_slots[i]->ies.packed_size();
1645 if (size > 0) {
1646 data[i] = __int_as_float(offset);
1647 ies_slots[i]->ies.pack(data + offset);
1648 offset += size;
1649 }
1650 else {
1651 data[i] = __int_as_float(-1);
1652 }
1653 }
1654
1655 dscene->ies_lights.copy_to_device();
1656 }
1657}
1658
1660{
1661 return light_type == LIGHT_POINT;
1662}
1663
1665{
1666 return light_type == LIGHT_SPOT;
1667}
1668
1670{
1671 return light_type == LIGHT_AREA;
1672}
1673
1675{
1676 return light_type == LIGHT_SUN;
1677}
1678
1680{
1681 return light_type == LIGHT_BACKGROUND;
1682}
1683
1685{
1686 return light_type == LIGHT_BACKGROUND || light_type == LIGHT_SUN;
1687}
1688
ccl_device_inline float sin_theta(const float3 w)
unsigned long long int uint64_t
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
Definition btDbvt.cpp:52
btScalar max
SIMD_FORCE_INLINE btScalar angle(const btVector3 &v) const
Return the angle between this and another vector.
Definition btVector3.h:356
float area(const Transform &tfm) const override
void copy_to_kernel(KernelLight *klight, const Scene *scene, const Object *object) const override
float area(const Transform &tfm) const override
void copy_to_kernel(KernelLight *klight, const Scene *scene, const Object *object) const override
Shader * get_shader(const Scene *scene)
device_vector< KernelLightTreeEmitter > light_tree_emitters
Definition devicescene.h:70
device_vector< KernelLightTreeNode > light_tree_nodes
Definition devicescene.h:69
device_vector< float2 > light_background_marginal_cdf
Definition devicescene.h:65
device_vector< uint > object_lookup_offset
Definition devicescene.h:72
device_vector< float > ies_lights
Definition devicescene.h:89
device_vector< float2 > light_background_conditional_cdf
Definition devicescene.h:66
device_vector< KernelLightDistribution > light_distribution
Definition devicescene.h:63
device_vector< uint > triangle_to_tree
Definition devicescene.h:73
KernelData data
device_vector< uint > light_to_tree
Definition devicescene.h:71
device_vector< KernelLight > lights
Definition devicescene.h:64
virtual void const_copy_to(const char *name, void *host, const size_t size)=0
bool transform_applied
const packed_float3 * get_position() const
size_t prim_offset
Geometry(const NodeType *node_type, const Type type)
ImageMetaData metadata(Progress &progress)
bool empty() const
void device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress &progress)
void count_lights(KernelIntegrator *kintegrator, const Scene *scene)
void device_update_ies(DeviceScene *dscene)
void device_update_tree(Device *device, DeviceScene *dscene, Scene *scene, Progress &progress)
vector< unique_ptr< IESSlot > > ies_slots
int add_ies_from_file(const string &filename)
void device_update_lights(DeviceScene *dscene, Scene *scene)
void test_enabled_lights(Scene *scene)
uint32_t update_flags
void device_free(Device *device, DeviceScene *dscene, const bool free_background=true)
void remove_ies(const int slot)
void device_update_distribution(Device *device, DeviceScene *dscene, Scene *scene, Progress &progress)
bool need_update_background
bool need_update() const
int add_ies(const string &content, const bool log_parsing_error)
void tag_update(Scene *scene, const uint32_t flag)
void device_update_background(Device *device, DeviceScene *dscene, Scene *scene, Progress &progress)
int last_background_resolution
thread_mutex ies_mutex
bool has_background_light(Scene *scene)
bool last_background_enabled
std::atomic< int > num_nodes
Definition light_tree.h:400
const LightTreeEmitter * get_emitters() const
Definition light_tree.h:430
uint64_t light_link_receiver_used
Definition light_tree.h:404
size_t num_triangles
Definition light_tree.h:401
LightTreeNode * build(Scene *scene, DeviceScene *dscene)
size_t num_emitters() const
Definition light_tree.h:425
bool has_contribution(const Scene *scene, const Object *object)
bool is_distant_light() const
Light(const NodeType *node_type, const Geometry::Type type)
bool is_spot_light() const
void tag_update(Scene *scene)
void get_uv_tiles(ustring map, unordered_set< int > &tiles) override
bool is_sun_light() const
void copy_to_kernel(KernelLight *klight, const Scene *scene, const Object *object, const uint shader_flags) const
void compute_bounds() override
virtual bool is_portal_light() const
Definition scene/light.h:80
void apply_transform(const Transform &tfm, const bool apply_to_motion) override
PrimitiveType primitive_type() const override
Shader * get_shader() const
bool is_background_light() const
bool is_point_light() const
bool is_area_light() const
size_t num_triangles() const
Definition scene/mesh.h:73
Triangle get_triangle(const size_t i) const
Definition scene/mesh.h:67
bool usable_as_light() const
void copy_to_kernel(KernelLight *klight, const Scene *scene, const Object *object) const override
float area(const Transform &tfm) const override
bool get_cancel() const
Definition progress.h:77
void set_status(const string &status_, const string &substatus_="")
Definition progress.h:248
void set_error(const string &error_message_)
Definition progress.h:98
Definition scene.h:133
unique_ptr< LightManager > light_manager
Definition scene.h:167
Shader * default_surface
Definition scene.h:178
unique_ptr< SceneUpdateStats > update_stats
Definition scene.h:197
Background * background
Definition scene.h:148
unique_ptr< ShaderManager > shader_manager
Definition scene.h:169
bool use_light_mis() const
Definition scene.cpp:859
unique_ptr_vector< Object > objects
Definition scene.h:162
Integrator * integrator
Definition scene.h:149
Shader * default_light
Definition scene.h:180
bool eval(const ShaderEvalType type, const int max_num_inputs, const int num_channels, const std::function< int(device_vector< KernelShaderEvalInput > &)> &fill_input, const std::function< void(device_vector< float > &)> &read_output)
ShaderNode * parent
ShaderOutput * link
ShaderInput * input(const char *name)
ShaderOutput * output(const char *name)
bool has_surface_spatial_varying
float3 emission_estimate
EmissionSampling emission_sampling
NODE_DECLARE unique_ptr< ShaderGraph > graph
float get_sun_size()
float get_sun_average_radiance()
void copy_to_kernel(KernelLight *klight, const Scene *scene, const Object *object) const override
float area(const Transform &tfm) const override
void copy_to_kernel(KernelLight *klight, const Scene *scene, const Object *object) const override
Transform compute_transform()
TextureMapping tex_mapping
T * alloc(const size_t width, const size_t height=0)
size_t size() const
#define LIGHT_LINK_SET_MAX
#define M_PI_2_F
#define M_PI_4_F
#define OBJECT_NONE
#define M_1_PI_F
#define M_1_2PI_F
#define powf(x, y)
#define CCL_NAMESPACE_END
ccl_device_forceinline float3 make_float3(const float x, const float y, const float z)
#define __int_as_float(x)
ccl_device_forceinline int2 make_int2(const int x, const int y)
#define assert(assertion)
#define FLT_MAX
#define smooth
VecBase< float, D > normalize(VecOp< float, D >) RET
bool is_zero(float3x3 a)
float3 transform_direction(float3x3 mat, float3 direction)
float3 transform_point(float3x3 mat, float3 point)
float average(float2 a)
VecT safe_normalize(VecT vector)
PrimitiveType
@ PRIMITIVE_LAMP
LightTreeNodeType
@ LIGHT_TREE_INSTANCE
@ PATH_RAY_VISIBILITY_VOLUME_SCATTER
@ PATH_RAY_VISIBILITY_CAMERA
@ PATH_RAY_VISIBILITY_TRANSMIT
@ PATH_RAY_VISIBILITY_DIFFUSE
@ PATH_RAY_VISIBILITY_GLOSSY
@ EMISSION_SAMPLING_NONE
@ SHADER_EXCLUDE_SHADOW_CATCHER
@ SHADER_EXCLUDE_CAMERA
@ SHADER_EXCLUDE_DIFFUSE
@ SHADER_USE_MIS
@ SHADER_EXCLUDE_SCATTER
@ SHADER_EXCLUDE_GLOSSY
@ SHADER_EXCLUDE_TRANSMIT
@ SHADER_CAST_SHADOW
@ LIGHT_AREA
@ LIGHT_SUN
@ LIGHT_SPOT
@ LIGHT_BACKGROUND
@ LIGHT_POINT
#define LOG_DEBUG
Definition log.h:107
#define LOG_ERROR
Definition log.h:101
#define LOG_INFO
Definition log.h:106
ccl_device_inline float inversesqrtf(const float f)
Definition math_base.h:576
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
ccl_device_inline dual1 len_squared(const ccl_private dual< T > &a)
Definition math_dual.h:273
ccl_device_inline dual3 fabs(const ccl_private dual3 &a)
Definition math_dual.h:241
ccl_device_inline float2 normalize_len(const float2 a, ccl_private float *t)
ccl_device_inline void copy_v3_v3(ccl_private float *r, const float3 val)
ccl_device_inline float3 one_float3()
Definition math_float3.h:26
CCL_NAMESPACE_BEGIN ccl_device_inline float3 zero_float3()
Definition math_float3.h:17
ccl_device_inline float triangle_area(const ccl_private float3 &v1, const ccl_private float3 &v2, const ccl_private float3 &v3)
#define SOCKET_FLOAT(name, ui_name, default_value,...)
Definition node_type.h:219
#define SOCKET_INT(name, ui_name, default_value,...)
Definition node_type.h:213
#define NODE_DEFINE(structname)
Definition node_type.h:157
#define SOCKET_COLOR(name, ui_name, default_value,...)
Definition node_type.h:221
#define SOCKET_BOOLEAN(name, ui_name, default_value,...)
Definition node_type.h:211
#define NODE_ABSTRACT_DEFINE(structname)
Definition node_type.h:182
#define SOCKET_ENUM(name, ui_name, values, default_value,...)
Definition node_type.h:235
#define hash
Definition noise_c.cc:156
bool path_read_text(const string &path, string &text)
Definition path.cpp:788
#define sqr
#define sqrtf
#define M_2PI_F
#define fmaxf
#define sinf
#define tanf
#define make_float4
#define fminf
#define M_PI_F
#define cosf
static void light_tree_emitters_copy_and_flatten(LightTreeFlatten &flatten, const LightTreeNode *node, KernelLightTreeNode *knodes, KernelLightTreeEmitter *kemitters, int &next_node_index)
static CCL_NAMESPACE_BEGIN void shade_background_pixels(Device *device, DeviceScene *dscene, const int width, const int height, vector< float3 > &pixels, Progress &progress)
static int light_tree_flatten(LightTreeFlatten &flatten, const LightTreeNode *node, KernelLightTreeNode *knodes, KernelLightTreeEmitter *kemitters, int &next_node_index)
static void light_tree_leaf_emitters_copy_and_flatten(LightTreeFlatten &flatten, const LightTreeNode &node, KernelLightTreeNode *knodes, KernelLightTreeEmitter *kemitters, int &next_node_index)
static uint light_object_visibility_flags(const Object *object)
static void light_tree_node_copy_to_device(KernelLightTreeNode &knode, const LightTreeNode &node, const int left_child, const int right_child)
static void background_cdf(int start, const int end, const int res_x, const int res_y, const vector< float3 > *pixels, float2 *cond_cdf)
static std::pair< int, LightTreeMeasure > light_tree_specialize_nodes_flatten(const LightTreeFlatten &flatten, LightTreeNode *node, const uint64_t light_link_mask, const int depth, vector< KernelLightTreeNode > &knodes, int &next_node_index, bool can_share=true)
@ SHADER_EVAL_BACKGROUND
Definition shader_eval.h:20
float3 sun_direction(float sun_cos_theta)
Definition sky_math.h:457
#define min(a, b)
Definition sort.cc:38
packed_float3 min
packed_float3 max
packed_float3 axis
LightTreeNodeType type
KernelBoundingBox bbox
KernelBoundingCone bcone
float strength[3]
packed_float3 co
__forceinline bool is_mesh() const
Definition light_tree.h:203
__forceinline bool is_triangle() const
Definition light_tree.h:208
unique_ptr< LightTreeNode > root
Definition light_tree.h:186
uint64_t light_set_membership
Definition light_tree.h:193
LightTreeMeasure measure
Definition light_tree.h:195
__forceinline bool is_light() const
Definition light_tree.h:213
const uint * object_lookup_offset
const LightTreeEmitter * emitters
std::unordered_map< LightTreeNode *, int > instances
const Scene * scene
OrientationBounds bcone
Definition light_tree.h:66
__forceinline void add(const LightTreeMeasure &measure)
Definition light_tree.h:91
void make_leaf(const int first_emitter_index, const int num_emitters)
Definition light_tree.h:319
LightTreeNode * get_reference()
Definition light_tree.h:349
LightTreeMeasure measure
Definition light_tree.h:248
std::variant< Leaf, Inner, Instance > variant_type
Definition light_tree.h:273
void make_distant(const int first_emitter_index, const int num_emitters)
Definition light_tree.h:329
__forceinline bool is_inner() const
Definition light_tree.h:368
LightTreeLightLink light_link
Definition light_tree.h:249
bool valid(const packed_float3 *verts) const
void insert(const char *x, const int y)
Definition node_enum.h:21
static NodeType * add(const char *name, CreateFunc create, Type type=NONE, const NodeType *base=nullptr)
const NodeType * type
Definition graph/node.h:179
bool is_modified() const
Node(const NodeType *type, ustring name=ustring())
float x
float y
std::unique_lock< std::mutex > thread_scoped_lock
Definition thread.h:28
CCL_NAMESPACE_BEGIN double time_dt()
Definition time.cpp:31
ccl_device_inline float3 transform_get_column(const Transform *t, const int column)
Definition transform.h:387
ccl_device_inline Transform transform_inverse(const Transform tfm)
Definition transform.h:563
ccl_device_inline float3 transform_get_translation(const Transform *t)
Definition transform.h:399
ccl_device_inline size_t divide_up(const size_t x, const size_t y)
Definition types_base.h:54