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