Merge branch 'master' into blender2.8
[blender.git] / intern / cycles / render / light.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "render/background.h"
18 #include "device/device.h"
19 #include "render/integrator.h"
20 #include "render/film.h"
21 #include "render/light.h"
22 #include "render/mesh.h"
23 #include "render/object.h"
24 #include "render/scene.h"
25 #include "render/shader.h"
26
27 #include "util/util_foreach.h"
28 #include "util/util_hash.h"
29 #include "util/util_path.h"
30 #include "util/util_progress.h"
31 #include "util/util_logging.h"
32
33 CCL_NAMESPACE_BEGIN
34
35 static void shade_background_pixels(Device *device, DeviceScene *dscene, int res, vector<float3>& pixels, Progress& progress)
36 {
37         /* create input */
38         int width = res;
39         int height = res;
40
41         device_vector<uint4> d_input(device, "background_input", MEM_READ_ONLY);
42         device_vector<float4> d_output(device, "background_output", MEM_READ_WRITE);
43
44         uint4 *d_input_data = d_input.alloc(width*height);
45
46         for(int y = 0; y < height; y++) {
47                 for(int x = 0; x < width; x++) {
48                         float u = (x + 0.5f)/width;
49                         float v = (y + 0.5f)/height;
50
51                         uint4 in = make_uint4(__float_as_int(u), __float_as_int(v), 0, 0);
52                         d_input_data[x + y*width] = in;
53                 }
54         }
55
56         /* compute on device */
57         d_output.alloc(width*height);
58         d_output.zero_to_device();
59         d_input.copy_to_device();
60
61         device->const_copy_to("__data", &dscene->data, sizeof(dscene->data));
62
63         DeviceTask main_task(DeviceTask::SHADER);
64         main_task.shader_input = d_input.device_pointer;
65         main_task.shader_output = d_output.device_pointer;
66         main_task.shader_eval_type = SHADER_EVAL_BACKGROUND;
67         main_task.shader_x = 0;
68         main_task.shader_w = width*height;
69         main_task.num_samples = 1;
70         main_task.get_cancel = function_bind(&Progress::get_cancel, &progress);
71
72         /* disabled splitting for now, there's an issue with multi-GPU mem_copy_from */
73         list<DeviceTask> split_tasks;
74         main_task.split(split_tasks, 1, 128*128);
75
76         foreach(DeviceTask& task, split_tasks) {
77                 device->task_add(task);
78                 device->task_wait();
79                 d_output.copy_from_device(task.shader_x, 1, task.shader_w);
80         }
81
82         d_input.free();
83
84         float4 *d_output_data = d_output.data();
85
86         pixels.resize(width*height);
87
88         for(int y = 0; y < height; y++) {
89                 for(int x = 0; x < width; x++) {
90                         pixels[y*width + x].x = d_output_data[y*width + x].x;
91                         pixels[y*width + x].y = d_output_data[y*width + x].y;
92                         pixels[y*width + x].z = d_output_data[y*width + x].z;
93                 }
94         }
95
96         d_output.free();
97 }
98
99 /* Light */
100
101 NODE_DEFINE(Light)
102 {
103         NodeType* type = NodeType::add("light", create);
104
105         static NodeEnum type_enum;
106         type_enum.insert("point", LIGHT_POINT);
107         type_enum.insert("distant", LIGHT_DISTANT);
108         type_enum.insert("background", LIGHT_BACKGROUND);
109         type_enum.insert("area", LIGHT_AREA);
110         type_enum.insert("spot", LIGHT_SPOT);
111         SOCKET_ENUM(type, "Type", type_enum, LIGHT_POINT);
112
113         SOCKET_POINT(co, "Co", make_float3(0.0f, 0.0f, 0.0f));
114
115         SOCKET_VECTOR(dir, "Dir", make_float3(0.0f, 0.0f, 0.0f));
116         SOCKET_FLOAT(size, "Size", 0.0f);
117
118         SOCKET_VECTOR(axisu, "Axis U", make_float3(0.0f, 0.0f, 0.0f));
119         SOCKET_FLOAT(sizeu, "Size U", 1.0f);
120         SOCKET_VECTOR(axisv, "Axis V", make_float3(0.0f, 0.0f, 0.0f));
121         SOCKET_FLOAT(sizev, "Size V", 1.0f);
122         SOCKET_BOOLEAN(round, "Round", false);
123
124         SOCKET_INT(map_resolution, "Map Resolution", 512);
125
126         SOCKET_FLOAT(spot_angle, "Spot Angle", M_PI_4_F);
127         SOCKET_FLOAT(spot_smooth, "Spot Smooth", 0.0f);
128
129         SOCKET_TRANSFORM(tfm, "Transform", transform_identity());
130
131         SOCKET_BOOLEAN(cast_shadow, "Cast Shadow", true);
132         SOCKET_BOOLEAN(use_mis, "Use Mis", false);
133         SOCKET_BOOLEAN(use_diffuse, "Use Diffuse", true);
134         SOCKET_BOOLEAN(use_glossy, "Use Glossy", true);
135         SOCKET_BOOLEAN(use_transmission, "Use Transmission", true);
136         SOCKET_BOOLEAN(use_scatter, "Use Scatter", true);
137
138         SOCKET_INT(samples, "Samples", 1);
139         SOCKET_INT(max_bounces, "Max Bounces", 1024);
140         SOCKET_UINT(random_id, "Random ID", 0);
141
142         SOCKET_BOOLEAN(is_portal, "Is Portal", false);
143         SOCKET_BOOLEAN(is_enabled, "Is Enabled", true);
144
145         SOCKET_NODE(shader, "Shader", &Shader::node_type);
146
147         return type;
148 }
149
150 Light::Light()
151 : Node(node_type)
152 {
153 }
154
155 void Light::tag_update(Scene *scene)
156 {
157         scene->light_manager->need_update = true;
158 }
159
160 bool Light::has_contribution(Scene *scene)
161 {
162         if(is_portal) {
163                 return false;
164         }
165         if(type == LIGHT_BACKGROUND) {
166                 return true;
167         }
168         return (shader) ? shader->has_surface_emission : scene->default_light->has_surface_emission;
169 }
170
171 /* Light Manager */
172
173 LightManager::LightManager()
174 {
175         need_update = true;
176         use_light_visibility = false;
177 }
178
179 LightManager::~LightManager()
180 {
181         foreach(IESSlot *slot, ies_slots) {
182                 delete slot;
183         }
184 }
185
186 bool LightManager::has_background_light(Scene *scene)
187 {
188         foreach(Light *light, scene->lights) {
189                 if(light->type == LIGHT_BACKGROUND) {
190                         return true;
191                 }
192         }
193         return false;
194 }
195
196 void LightManager::disable_ineffective_light(Device *device, Scene *scene)
197 {
198         /* Make all lights enabled by default, and perform some preliminary checks
199          * needed for finer-tuning of settings (for example, check whether we've
200          * got portals or not).
201          */
202         bool has_portal = false, has_background = false;
203         foreach(Light *light, scene->lights) {
204                 light->is_enabled = light->has_contribution(scene);
205                 has_portal |= light->is_portal;
206                 has_background |= light->type == LIGHT_BACKGROUND;
207         }
208
209         if(has_background) {
210                 /* Ignore background light if:
211                  * - If unsupported on a device
212                  * - If we don't need it (no HDRs etc.)
213                  */
214                 Shader *shader = (scene->background->shader) ? scene->background->shader : scene->default_background;
215                 bool disable_mis = !(has_portal || shader->has_surface_spatial_varying) ||
216                                    !(device->info.advanced_shading);
217                 if(disable_mis) {
218                         VLOG(1) << "Background MIS has been disabled.\n";
219                         foreach(Light *light, scene->lights) {
220                                 if(light->type == LIGHT_BACKGROUND) {
221                                         light->is_enabled = false;
222                                 }
223                         }
224                 }
225         }
226 }
227
228 bool LightManager::object_usable_as_light(Object *object) {
229         Mesh *mesh = object->mesh;
230         /* Skip objects with NaNs */
231         if(!object->bounds.valid()) {
232                 return false;
233         }
234         /* Skip if we are not visible for BSDFs. */
235         if(!(object->visibility & (PATH_RAY_DIFFUSE|PATH_RAY_GLOSSY|PATH_RAY_TRANSMIT))) {
236                 return false;
237         }
238         /* Skip if we have no emission shaders. */
239         /* TODO(sergey): Ideally we want to avoid such duplicated loop, since it'll
240          * iterate all mesh shaders twice (when counting and when calculating
241          * triangle area.
242          */
243         foreach(const Shader *shader, mesh->used_shaders) {
244                 if(shader->use_mis && shader->has_surface_emission) {
245                         return true;
246                 }
247         }
248         return false;
249 }
250
251 void LightManager::device_update_distribution(Device *, DeviceScene *dscene, Scene *scene, Progress& progress)
252 {
253         progress.set_status("Updating Lights", "Computing distribution");
254
255         /* count */
256         size_t num_lights = 0;
257         size_t num_portals = 0;
258         size_t num_background_lights = 0;
259         size_t num_triangles = 0;
260
261         bool background_mis = false;
262
263         foreach(Light *light, scene->lights) {
264                 if(light->is_enabled) {
265                         num_lights++;
266                 }
267                 if(light->is_portal) {
268                         num_portals++;
269                 }
270         }
271
272         foreach(Object *object, scene->objects) {
273                 if(progress.get_cancel()) return;
274
275                 if(!object_usable_as_light(object)) {
276                         continue;
277                 }
278                 /* Count triangles. */
279                 Mesh *mesh = object->mesh;
280                 size_t mesh_num_triangles = mesh->num_triangles();
281                 for(size_t i = 0; i < mesh_num_triangles; i++) {
282                         int shader_index = mesh->shader[i];
283                         Shader *shader = (shader_index < mesh->used_shaders.size())
284                                                  ? mesh->used_shaders[shader_index]
285                                                  : scene->default_surface;
286
287                         if(shader->use_mis && shader->has_surface_emission) {
288                                 num_triangles++;
289                         }
290                 }
291         }
292
293         size_t num_distribution = num_triangles + num_lights;
294         VLOG(1) << "Total " << num_distribution << " of light distribution primitives.";
295
296         /* emission area */
297         KernelLightDistribution *distribution = dscene->light_distribution.alloc(num_distribution + 1);
298         float totarea = 0.0f;
299
300         /* triangles */
301         size_t offset = 0;
302         int j = 0;
303
304         foreach(Object *object, scene->objects) {
305                 if(progress.get_cancel()) return;
306
307                 if(!object_usable_as_light(object)) {
308                         j++;
309                         continue;
310                 }
311                 /* Sum area. */
312                 Mesh *mesh = object->mesh;
313                 bool transform_applied = mesh->transform_applied;
314                 Transform tfm = object->tfm;
315                 int object_id = j;
316                 int shader_flag = 0;
317
318                 if(!(object->visibility & PATH_RAY_DIFFUSE)) {
319                         shader_flag |= SHADER_EXCLUDE_DIFFUSE;
320                         use_light_visibility = true;
321                 }
322                 if(!(object->visibility & PATH_RAY_GLOSSY)) {
323                         shader_flag |= SHADER_EXCLUDE_GLOSSY;
324                         use_light_visibility = true;
325                 }
326                 if(!(object->visibility & PATH_RAY_TRANSMIT)) {
327                         shader_flag |= SHADER_EXCLUDE_TRANSMIT;
328                         use_light_visibility = true;
329                 }
330                 if(!(object->visibility & PATH_RAY_VOLUME_SCATTER)) {
331                         shader_flag |= SHADER_EXCLUDE_SCATTER;
332                         use_light_visibility = true;
333                 }
334
335                 size_t mesh_num_triangles = mesh->num_triangles();
336                 for(size_t i = 0; i < mesh_num_triangles; i++) {
337                         int shader_index = mesh->shader[i];
338                         Shader *shader = (shader_index < mesh->used_shaders.size())
339                                                  ? mesh->used_shaders[shader_index]
340                                                  : scene->default_surface;
341
342                         if(shader->use_mis && shader->has_surface_emission) {
343                                 distribution[offset].totarea = totarea;
344                                 distribution[offset].prim = i + mesh->tri_offset;
345                                 distribution[offset].mesh_light.shader_flag = shader_flag;
346                                 distribution[offset].mesh_light.object_id = object_id;
347                                 offset++;
348
349                                 Mesh::Triangle t = mesh->get_triangle(i);
350                                 if(!t.valid(&mesh->verts[0])) {
351                                         continue;
352                                 }
353                                 float3 p1 = mesh->verts[t.v[0]];
354                                 float3 p2 = mesh->verts[t.v[1]];
355                                 float3 p3 = mesh->verts[t.v[2]];
356
357                                 if(!transform_applied) {
358                                         p1 = transform_point(&tfm, p1);
359                                         p2 = transform_point(&tfm, p2);
360                                         p3 = transform_point(&tfm, p3);
361                                 }
362
363                                 totarea += triangle_area(p1, p2, p3);
364                         }
365                 }
366
367                 j++;
368         }
369
370         float trianglearea = totarea;
371
372         /* point lights */
373         float lightarea = (totarea > 0.0f) ? totarea / num_lights : 1.0f;
374         bool use_lamp_mis = false;
375
376         int light_index = 0;
377         foreach(Light *light, scene->lights) {
378                 if(!light->is_enabled)
379                         continue;
380
381                 distribution[offset].totarea = totarea;
382                 distribution[offset].prim = ~light_index;
383                 distribution[offset].lamp.pad = 1.0f;
384                 distribution[offset].lamp.size = light->size;
385                 totarea += lightarea;
386
387                 if(light->size > 0.0f && light->use_mis)
388                         use_lamp_mis = true;
389                 if(light->type == LIGHT_BACKGROUND) {
390                         num_background_lights++;
391                         background_mis = light->use_mis;
392                 }
393
394                 light_index++;
395                 offset++;
396         }
397
398         /* normalize cumulative distribution functions */
399         distribution[num_distribution].totarea = totarea;
400         distribution[num_distribution].prim = 0.0f;
401         distribution[num_distribution].lamp.pad = 0.0f;
402         distribution[num_distribution].lamp.size = 0.0f;
403
404         if(totarea > 0.0f) {
405                 for(size_t i = 0; i < num_distribution; i++)
406                         distribution[i].totarea /= totarea;
407                 distribution[num_distribution].totarea = 1.0f;
408         }
409
410         if(progress.get_cancel()) return;
411
412         /* update device */
413         KernelIntegrator *kintegrator = &dscene->data.integrator;
414         KernelFilm *kfilm = &dscene->data.film;
415         kintegrator->use_direct_light = (totarea > 0.0f);
416
417         if(kintegrator->use_direct_light) {
418                 /* number of emissives */
419                 kintegrator->num_distribution = num_distribution;
420
421                 /* precompute pdfs */
422                 kintegrator->pdf_triangles = 0.0f;
423                 kintegrator->pdf_lights = 0.0f;
424
425                 /* sample one, with 0.5 probability of light or triangle */
426                 kintegrator->num_all_lights = num_lights;
427
428                 if(trianglearea > 0.0f) {
429                         kintegrator->pdf_triangles = 1.0f/trianglearea;
430                         if(num_lights)
431                                 kintegrator->pdf_triangles *= 0.5f;
432                 }
433
434                 if(num_lights) {
435                         kintegrator->pdf_lights = 1.0f/num_lights;
436                         if(trianglearea > 0.0f)
437                                 kintegrator->pdf_lights *= 0.5f;
438                 }
439
440                 kintegrator->use_lamp_mis = use_lamp_mis;
441
442                 /* bit of an ugly hack to compensate for emitting triangles influencing
443                  * amount of samples we get for this pass */
444                 kfilm->pass_shadow_scale = 1.0f;
445
446                 if(kintegrator->pdf_triangles != 0.0f)
447                         kfilm->pass_shadow_scale *= 0.5f;
448
449                 if(num_background_lights < num_lights)
450                         kfilm->pass_shadow_scale *= (float)(num_lights - num_background_lights)/(float)num_lights;
451
452                 /* CDF */
453                 dscene->light_distribution.copy_to_device();
454
455                 /* Portals */
456                 if(num_portals > 0) {
457                         kintegrator->portal_offset = light_index;
458                         kintegrator->num_portals = num_portals;
459                         kintegrator->portal_pdf = background_mis? 0.5f: 1.0f;
460                 }
461                 else {
462                         kintegrator->num_portals = 0;
463                         kintegrator->portal_offset = 0;
464                         kintegrator->portal_pdf = 0.0f;
465                 }
466         }
467         else {
468                 dscene->light_distribution.free();
469
470                 kintegrator->num_distribution = 0;
471                 kintegrator->num_all_lights = 0;
472                 kintegrator->pdf_triangles = 0.0f;
473                 kintegrator->pdf_lights = 0.0f;
474                 kintegrator->use_lamp_mis = false;
475                 kintegrator->num_portals = 0;
476                 kintegrator->portal_offset = 0;
477                 kintegrator->portal_pdf = 0.0f;
478
479                 kfilm->pass_shadow_scale = 1.0f;
480         }
481 }
482
483 static void background_cdf(int start,
484                            int end,
485                            int res,
486                            int cdf_count,
487                            const vector<float3> *pixels,
488                            float2 *cond_cdf)
489 {
490         /* Conditional CDFs (rows, U direction). */
491         for(int i = start; i < end; i++) {
492                 float sin_theta = sinf(M_PI_F * (i + 0.5f) / res);
493                 float3 env_color = (*pixels)[i * res];
494                 float ave_luminance = average(env_color);
495
496                 cond_cdf[i * cdf_count].x = ave_luminance * sin_theta;
497                 cond_cdf[i * cdf_count].y = 0.0f;
498
499                 for(int j = 1; j < res; j++) {
500                         env_color = (*pixels)[i * res + j];
501                         ave_luminance = average(env_color);
502
503                         cond_cdf[i * cdf_count + j].x = ave_luminance * sin_theta;
504                         cond_cdf[i * cdf_count + j].y = cond_cdf[i * cdf_count + j - 1].y + cond_cdf[i * cdf_count + j - 1].x / res;
505                 }
506
507                 float cdf_total = cond_cdf[i * cdf_count + res - 1].y + cond_cdf[i * cdf_count + res - 1].x / res;
508                 float cdf_total_inv = 1.0f / cdf_total;
509
510                 /* stuff the total into the brightness value for the last entry, because
511                  * we are going to normalize the CDFs to 0.0 to 1.0 afterwards */
512                 cond_cdf[i * cdf_count + res].x = cdf_total;
513
514                 if(cdf_total > 0.0f)
515                         for(int j = 1; j < res; j++)
516                                 cond_cdf[i * cdf_count + j].y *= cdf_total_inv;
517
518                 cond_cdf[i * cdf_count + res].y = 1.0f;
519         }
520 }
521
522 void LightManager::device_update_background(Device *device,
523                                             DeviceScene *dscene,
524                                             Scene *scene,
525                                             Progress& progress)
526 {
527         KernelIntegrator *kintegrator = &dscene->data.integrator;
528         Light *background_light = NULL;
529
530         /* find background light */
531         foreach(Light *light, scene->lights) {
532                 if(light->type == LIGHT_BACKGROUND) {
533                         background_light = light;
534                         break;
535                 }
536         }
537
538         /* no background light found, signal renderer to skip sampling */
539         if(!background_light || !background_light->is_enabled) {
540                 kintegrator->pdf_background_res = 0;
541                 return;
542         }
543
544         progress.set_status("Updating Lights", "Importance map");
545
546         assert(kintegrator->use_direct_light);
547
548         /* get the resolution from the light's size (we stuff it in there) */
549         int res = background_light->map_resolution;
550         kintegrator->pdf_background_res = res;
551
552         assert(res > 0);
553
554         vector<float3> pixels;
555         shade_background_pixels(device, dscene, res, pixels, progress);
556
557         if(progress.get_cancel())
558                 return;
559
560         /* build row distributions and column distribution for the infinite area environment light */
561         int cdf_count = res + 1;
562         float2 *marg_cdf = dscene->light_background_marginal_cdf.alloc(cdf_count);
563         float2 *cond_cdf = dscene->light_background_conditional_cdf.alloc(cdf_count * cdf_count);
564
565         double time_start = time_dt();
566         if(res < 512) {
567                 /* Small enough resolution, faster to do single-threaded. */
568                 background_cdf(0, res, res, cdf_count, &pixels, cond_cdf);
569         }
570         else {
571                 /* Threaded evaluation for large resolution. */
572                 const int num_blocks = TaskScheduler::num_threads();
573                 const int chunk_size = res / num_blocks;
574                 int start_row = 0;
575                 TaskPool pool;
576                 for(int i = 0; i < num_blocks; ++i) {
577                         const int current_chunk_size =
578                             (i != num_blocks - 1) ? chunk_size
579                                                   : (res - i * chunk_size);
580                         pool.push(function_bind(&background_cdf,
581                                                 start_row, start_row + current_chunk_size,
582                                                 res,
583                                                 cdf_count,
584                                                 &pixels,
585                                                 cond_cdf));
586                         start_row += current_chunk_size;
587                 }
588                 pool.wait_work();
589         }
590
591         /* marginal CDFs (column, V direction, sum of rows) */
592         marg_cdf[0].x = cond_cdf[res].x;
593         marg_cdf[0].y = 0.0f;
594
595         for(int i = 1; i < res; i++) {
596                 marg_cdf[i].x = cond_cdf[i * cdf_count + res].x;
597                 marg_cdf[i].y = marg_cdf[i - 1].y + marg_cdf[i - 1].x / res;
598         }
599
600         float cdf_total = marg_cdf[res - 1].y + marg_cdf[res - 1].x / res;
601         marg_cdf[res].x = cdf_total;
602
603         if(cdf_total > 0.0f)
604                 for(int i = 1; i < res; i++)
605                         marg_cdf[i].y /= cdf_total;
606
607         marg_cdf[res].y = 1.0f;
608
609         VLOG(2) << "Background MIS build time " << time_dt() - time_start << "\n";
610
611         /* update device */
612         dscene->light_background_marginal_cdf.copy_to_device();
613         dscene->light_background_conditional_cdf.copy_to_device();
614 }
615
616 void LightManager::device_update_points(Device *,
617                                         DeviceScene *dscene,
618                                         Scene *scene)
619 {
620         int num_scene_lights = scene->lights.size();
621
622         int num_lights = 0;
623         foreach(Light *light, scene->lights) {
624                 if(light->is_enabled || light->is_portal) {
625                         num_lights++;
626                 }
627         }
628
629         KernelLight *klights = dscene->lights.alloc(num_lights);
630
631         if(num_lights == 0) {
632                 VLOG(1) << "No effective light, ignoring points update.";
633                 return;
634         }
635
636         int light_index = 0;
637
638         foreach(Light *light, scene->lights) {
639                 if(!light->is_enabled) {
640                         continue;
641                 }
642
643                 float3 co = light->co;
644                 Shader *shader = (light->shader) ? light->shader : scene->default_light;
645                 int shader_id = scene->shader_manager->get_shader_id(shader);
646                 int samples = light->samples;
647                 int max_bounces = light->max_bounces;
648                 float random = (float)light->random_id * (1.0f/(float)0xFFFFFFFF);
649
650                 if(!light->cast_shadow)
651                         shader_id &= ~SHADER_CAST_SHADOW;
652
653                 if(!light->use_diffuse) {
654                         shader_id |= SHADER_EXCLUDE_DIFFUSE;
655                         use_light_visibility = true;
656                 }
657                 if(!light->use_glossy) {
658                         shader_id |= SHADER_EXCLUDE_GLOSSY;
659                         use_light_visibility = true;
660                 }
661                 if(!light->use_transmission) {
662                         shader_id |= SHADER_EXCLUDE_TRANSMIT;
663                         use_light_visibility = true;
664                 }
665                 if(!light->use_scatter) {
666                         shader_id |= SHADER_EXCLUDE_SCATTER;
667                         use_light_visibility = true;
668                 }
669
670                 klights[light_index].type = light->type;
671                 klights[light_index].samples = samples;
672
673                 if(light->type == LIGHT_POINT) {
674                         shader_id &= ~SHADER_AREA_LIGHT;
675
676                         float radius = light->size;
677                         float invarea = (radius > 0.0f)? 1.0f/(M_PI_F*radius*radius): 1.0f;
678
679                         if(light->use_mis && radius > 0.0f)
680                                 shader_id |= SHADER_USE_MIS;
681
682                         klights[light_index].co[0] = co.x;
683                         klights[light_index].co[1] = co.y;
684                         klights[light_index].co[2] = co.z;
685
686                         klights[light_index].spot.radius = radius;
687                         klights[light_index].spot.invarea = invarea;
688                 }
689                 else if(light->type == LIGHT_DISTANT) {
690                         shader_id &= ~SHADER_AREA_LIGHT;
691
692                         float radius = light->size;
693                         float angle = atanf(radius);
694                         float cosangle = cosf(angle);
695                         float area = M_PI_F*radius*radius;
696                         float invarea = (area > 0.0f)? 1.0f/area: 1.0f;
697                         float3 dir = light->dir;
698
699                         dir = safe_normalize(dir);
700
701                         if(light->use_mis && area > 0.0f)
702                                 shader_id |= SHADER_USE_MIS;
703
704                         klights[light_index].co[0] = dir.x;
705                         klights[light_index].co[1] = dir.y;
706                         klights[light_index].co[2] = dir.z;
707
708                         klights[light_index].distant.invarea = invarea;
709                         klights[light_index].distant.radius = radius;
710                         klights[light_index].distant.cosangle = cosangle;
711                 }
712                 else if(light->type == LIGHT_BACKGROUND) {
713                         uint visibility = scene->background->visibility;
714
715                         shader_id &= ~SHADER_AREA_LIGHT;
716                         shader_id |= SHADER_USE_MIS;
717
718                         if(!(visibility & PATH_RAY_DIFFUSE)) {
719                                 shader_id |= SHADER_EXCLUDE_DIFFUSE;
720                                 use_light_visibility = true;
721                         }
722                         if(!(visibility & PATH_RAY_GLOSSY)) {
723                                 shader_id |= SHADER_EXCLUDE_GLOSSY;
724                                 use_light_visibility = true;
725                         }
726                         if(!(visibility & PATH_RAY_TRANSMIT)) {
727                                 shader_id |= SHADER_EXCLUDE_TRANSMIT;
728                                 use_light_visibility = true;
729                         }
730                         if(!(visibility & PATH_RAY_VOLUME_SCATTER)) {
731                                 shader_id |= SHADER_EXCLUDE_SCATTER;
732                                 use_light_visibility = true;
733                         }
734                 }
735                 else if(light->type == LIGHT_AREA) {
736                         float3 axisu = light->axisu*(light->sizeu*light->size);
737                         float3 axisv = light->axisv*(light->sizev*light->size);
738                         float area = len(axisu)*len(axisv);
739                         if(light->round) {
740                                 area *= -M_PI_4_F;
741                         }
742                         float invarea = (area != 0.0f)? 1.0f/area: 1.0f;
743                         float3 dir = light->dir;
744                         
745                         dir = safe_normalize(dir);
746
747                         if(light->use_mis && area != 0.0f)
748                                 shader_id |= SHADER_USE_MIS;
749
750                         klights[light_index].co[0] = co.x;
751                         klights[light_index].co[1] = co.y;
752                         klights[light_index].co[2] = co.z;
753
754                         klights[light_index].area.axisu[0] = axisu.x;
755                         klights[light_index].area.axisu[1] = axisu.y;
756                         klights[light_index].area.axisu[2] = axisu.z;
757                         klights[light_index].area.axisv[0] = axisv.x;
758                         klights[light_index].area.axisv[1] = axisv.y;
759                         klights[light_index].area.axisv[2] = axisv.z;
760                         klights[light_index].area.invarea = invarea;
761                         klights[light_index].area.dir[0] = dir.x;
762                         klights[light_index].area.dir[1] = dir.y;
763                         klights[light_index].area.dir[2] = dir.z;
764                 }
765                 else if(light->type == LIGHT_SPOT) {
766                         shader_id &= ~SHADER_AREA_LIGHT;
767
768                         float radius = light->size;
769                         float invarea = (radius > 0.0f)? 1.0f/(M_PI_F*radius*radius): 1.0f;
770                         float spot_angle = cosf(light->spot_angle*0.5f);
771                         float spot_smooth = (1.0f - spot_angle)*light->spot_smooth;
772                         float3 dir = light->dir;
773                         
774                         dir = safe_normalize(dir);
775
776                         if(light->use_mis && radius > 0.0f)
777                                 shader_id |= SHADER_USE_MIS;
778
779                         klights[light_index].co[0] = co.x;
780                         klights[light_index].co[1] = co.y;
781                         klights[light_index].co[2] = co.z;
782
783                         klights[light_index].spot.radius = radius;
784                         klights[light_index].spot.invarea = invarea;
785                         klights[light_index].spot.spot_angle = spot_angle;
786                         klights[light_index].spot.spot_smooth = spot_smooth;
787                         klights[light_index].spot.dir[0] = dir.x;
788                         klights[light_index].spot.dir[1] = dir.y;
789                         klights[light_index].spot.dir[2] = dir.z;
790                 }
791
792                 klights[light_index].shader_id = shader_id;
793
794                 klights[light_index].max_bounces = max_bounces;
795                 klights[light_index].random = random;
796
797                 klights[light_index].tfm = light->tfm;
798                 klights[light_index].itfm = transform_inverse(light->tfm);
799
800                 light_index++;
801         }
802
803         /* TODO(sergey): Consider moving portals update to their own function
804          * keeping this one more manageable.
805          */
806         foreach(Light *light, scene->lights) {
807                 if(!light->is_portal)
808                         continue;
809                 assert(light->type == LIGHT_AREA);
810
811                 float3 co = light->co;
812                 float3 axisu = light->axisu*(light->sizeu*light->size);
813                 float3 axisv = light->axisv*(light->sizev*light->size);
814                 float area = len(axisu)*len(axisv);
815                 if(light->round) {
816                         area *= -M_PI_4_F;
817                 }
818                 float invarea = (area != 0.0f)? 1.0f/area: 1.0f;
819                 float3 dir = light->dir;
820
821                 dir = safe_normalize(dir);
822
823                 klights[light_index].co[0] = co.x;
824                 klights[light_index].co[1] = co.y;
825                 klights[light_index].co[2] = co.z;
826
827                 klights[light_index].area.axisu[0] = axisu.x;
828                 klights[light_index].area.axisu[1] = axisu.y;
829                 klights[light_index].area.axisu[2] = axisu.z;
830                 klights[light_index].area.axisv[0] = axisv.x;
831                 klights[light_index].area.axisv[1] = axisv.y;
832                 klights[light_index].area.axisv[2] = axisv.z;
833                 klights[light_index].area.invarea = invarea;
834                 klights[light_index].area.dir[0] = dir.x;
835                 klights[light_index].area.dir[1] = dir.y;
836                 klights[light_index].area.dir[2] = dir.z;
837                 klights[light_index].tfm = light->tfm;
838                 klights[light_index].itfm = transform_inverse(light->tfm);
839
840                 light_index++;
841         }
842
843         VLOG(1) << "Number of lights sent to the device: " << light_index;
844
845         VLOG(1) << "Number of lights without contribution: "
846                 << num_scene_lights - light_index;
847
848         dscene->lights.copy_to_device();
849 }
850
851 void LightManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
852 {
853         if(!need_update)
854                 return;
855
856         VLOG(1) << "Total " << scene->lights.size() << " lights.";
857
858         device_free(device, dscene);
859
860         use_light_visibility = false;
861
862         disable_ineffective_light(device, scene);
863
864         device_update_points(device, dscene, scene);
865         if(progress.get_cancel()) return;
866
867         device_update_distribution(device, dscene, scene, progress);
868         if(progress.get_cancel()) return;
869
870         device_update_background(device, dscene, scene, progress);
871         if(progress.get_cancel()) return;
872
873         device_update_ies(dscene);
874         if(progress.get_cancel()) return;
875
876         if(use_light_visibility != scene->film->use_light_visibility) {
877                 scene->film->use_light_visibility = use_light_visibility;
878                 scene->film->tag_update(scene);
879         }
880
881         need_update = false;
882 }
883
884 void LightManager::device_free(Device *, DeviceScene *dscene)
885 {
886         dscene->light_distribution.free();
887         dscene->lights.free();
888         dscene->light_background_marginal_cdf.free();
889         dscene->light_background_conditional_cdf.free();
890         dscene->ies_lights.free();
891 }
892
893 void LightManager::tag_update(Scene * /*scene*/)
894 {
895         need_update = true;
896 }
897
898 int LightManager::add_ies_from_file(ustring filename)
899 {
900         string content;
901         /* If the file can't be opened, call with an empty string */
902         path_read_text(filename.c_str(), content);
903
904         return add_ies(ustring(content));
905 }
906
907 int LightManager::add_ies(ustring content)
908 {
909         uint hash = hash_string(content.c_str());
910
911         thread_scoped_lock ies_lock(ies_mutex);
912
913         /* Check whether this IES already has a slot. */
914         size_t slot;
915         for(slot = 0; slot < ies_slots.size(); slot++) {
916                 if(ies_slots[slot]->hash == hash) {
917                         ies_slots[slot]->users++;
918                         return slot;
919                 }
920         }
921
922         /* Try to find an empty slot for the new IES. */
923         for(slot = 0; slot < ies_slots.size(); slot++) {
924                 if(ies_slots[slot]->users == 0 && ies_slots[slot]->hash == 0) {
925                         break;
926                 }
927         }
928
929         /* If there's no free slot, add one. */
930         if(slot == ies_slots.size()) {
931                 ies_slots.push_back(new IESSlot());
932         }
933
934         ies_slots[slot]->ies.load(content);
935         ies_slots[slot]->users = 1;
936         ies_slots[slot]->hash = hash;
937
938         need_update = true;
939
940         return slot;
941 }
942
943 void LightManager::remove_ies(int slot)
944 {
945         thread_scoped_lock ies_lock(ies_mutex);
946
947         if(slot < 0 || slot >= ies_slots.size()) {
948                 assert(false);
949                 return;
950         }
951
952         assert(ies_slots[slot]->users > 0);
953         ies_slots[slot]->users--;
954
955         /* If the slot has no more users, update the device to remove it. */
956         need_update |= (ies_slots[slot]->users == 0);
957 }
958
959 void LightManager::device_update_ies(DeviceScene *dscene)
960 {
961         /* Clear empty slots. */
962         foreach(IESSlot *slot, ies_slots) {
963                 if(slot->users == 0) {
964                         slot->hash = 0;
965                         slot->ies.clear();
966                 }
967         }
968
969         /* Shrink the slot table by removing empty slots at the end. */
970         int slot_end;
971         for(slot_end = ies_slots.size(); slot_end; slot_end--) {
972                 if(ies_slots[slot_end-1]->users > 0) {
973                         /* If the preceding slot has users, we found the new end of the table. */
974                         break;
975                 }
976                 else {
977                         /* The slot will be past the new end of the table, so free it. */
978                         delete ies_slots[slot_end-1];
979                 }
980         }
981         ies_slots.resize(slot_end);
982
983         if(ies_slots.size() > 0) {
984                 int packed_size = 0;
985                 foreach(IESSlot *slot, ies_slots) {
986                         packed_size += slot->ies.packed_size();
987                 }
988
989                 /* ies_lights starts with an offset table that contains the offset of every slot,
990                  * or -1 if the slot is invalid.
991                  * Following that table, the packed valid IES lights are stored. */
992                 float *data = dscene->ies_lights.alloc(ies_slots.size() + packed_size);
993
994                 int offset = ies_slots.size();
995                 for(int i = 0; i < ies_slots.size(); i++) {
996                         int size = ies_slots[i]->ies.packed_size();
997                         if(size > 0) {
998                                 data[i] = __int_as_float(offset);
999                                 ies_slots[i]->ies.pack(data + offset);
1000                                 offset += size;
1001                         }
1002                         else {
1003                                 data[i] = __int_as_float(-1);
1004                         }
1005                 }
1006
1007                 dscene->ies_lights.copy_to_device();
1008         }
1009 }
1010
1011 CCL_NAMESPACE_END
1012