Merge branch 'blender2.7'
[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 && light->is_enabled) {
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                 if(disable_mis) {
216                         VLOG(1) << "Background MIS has been disabled.\n";
217                         foreach(Light *light, scene->lights) {
218                                 if(light->type == LIGHT_BACKGROUND) {
219                                         light->is_enabled = false;
220                                 }
221                         }
222                 }
223         }
224 }
225
226 bool LightManager::object_usable_as_light(Object *object) {
227         Mesh *mesh = object->mesh;
228         /* Skip objects with NaNs */
229         if(!object->bounds.valid()) {
230                 return false;
231         }
232         /* Skip if we are not visible for BSDFs. */
233         if(!(object->visibility & (PATH_RAY_DIFFUSE|PATH_RAY_GLOSSY|PATH_RAY_TRANSMIT))) {
234                 return false;
235         }
236         /* Skip if we have no emission shaders. */
237         /* TODO(sergey): Ideally we want to avoid such duplicated loop, since it'll
238          * iterate all mesh shaders twice (when counting and when calculating
239          * triangle area.
240          */
241         foreach(const Shader *shader, mesh->used_shaders) {
242                 if(shader->use_mis && shader->has_surface_emission) {
243                         return true;
244                 }
245         }
246         return false;
247 }
248
249 void LightManager::device_update_distribution(Device *, DeviceScene *dscene, Scene *scene, Progress& progress)
250 {
251         progress.set_status("Updating Lights", "Computing distribution");
252
253         /* count */
254         size_t num_lights = 0;
255         size_t num_portals = 0;
256         size_t num_background_lights = 0;
257         size_t num_triangles = 0;
258
259         bool background_mis = false;
260
261         foreach(Light *light, scene->lights) {
262                 if(light->is_enabled) {
263                         num_lights++;
264                 }
265                 if(light->is_portal) {
266                         num_portals++;
267                 }
268         }
269
270         foreach(Object *object, scene->objects) {
271                 if(progress.get_cancel()) return;
272
273                 if(!object_usable_as_light(object)) {
274                         continue;
275                 }
276                 /* Count triangles. */
277                 Mesh *mesh = object->mesh;
278                 size_t mesh_num_triangles = mesh->num_triangles();
279                 for(size_t i = 0; i < mesh_num_triangles; i++) {
280                         int shader_index = mesh->shader[i];
281                         Shader *shader = (shader_index < mesh->used_shaders.size())
282                                                  ? mesh->used_shaders[shader_index]
283                                                  : scene->default_surface;
284
285                         if(shader->use_mis && shader->has_surface_emission) {
286                                 num_triangles++;
287                         }
288                 }
289         }
290
291         size_t num_distribution = num_triangles + num_lights;
292         VLOG(1) << "Total " << num_distribution << " of light distribution primitives.";
293
294         /* emission area */
295         KernelLightDistribution *distribution = dscene->light_distribution.alloc(num_distribution + 1);
296         float totarea = 0.0f;
297
298         /* triangles */
299         size_t offset = 0;
300         int j = 0;
301
302         foreach(Object *object, scene->objects) {
303                 if(progress.get_cancel()) return;
304
305                 if(!object_usable_as_light(object)) {
306                         j++;
307                         continue;
308                 }
309                 /* Sum area. */
310                 Mesh *mesh = object->mesh;
311                 bool transform_applied = mesh->transform_applied;
312                 Transform tfm = object->tfm;
313                 int object_id = j;
314                 int shader_flag = 0;
315
316                 if(!(object->visibility & PATH_RAY_DIFFUSE)) {
317                         shader_flag |= SHADER_EXCLUDE_DIFFUSE;
318                         use_light_visibility = true;
319                 }
320                 if(!(object->visibility & PATH_RAY_GLOSSY)) {
321                         shader_flag |= SHADER_EXCLUDE_GLOSSY;
322                         use_light_visibility = true;
323                 }
324                 if(!(object->visibility & PATH_RAY_TRANSMIT)) {
325                         shader_flag |= SHADER_EXCLUDE_TRANSMIT;
326                         use_light_visibility = true;
327                 }
328                 if(!(object->visibility & PATH_RAY_VOLUME_SCATTER)) {
329                         shader_flag |= SHADER_EXCLUDE_SCATTER;
330                         use_light_visibility = true;
331                 }
332
333                 size_t mesh_num_triangles = mesh->num_triangles();
334                 for(size_t i = 0; i < mesh_num_triangles; i++) {
335                         int shader_index = mesh->shader[i];
336                         Shader *shader = (shader_index < mesh->used_shaders.size())
337                                                  ? mesh->used_shaders[shader_index]
338                                                  : scene->default_surface;
339
340                         if(shader->use_mis && shader->has_surface_emission) {
341                                 distribution[offset].totarea = totarea;
342                                 distribution[offset].prim = i + mesh->tri_offset;
343                                 distribution[offset].mesh_light.shader_flag = shader_flag;
344                                 distribution[offset].mesh_light.object_id = object_id;
345                                 offset++;
346
347                                 Mesh::Triangle t = mesh->get_triangle(i);
348                                 if(!t.valid(&mesh->verts[0])) {
349                                         continue;
350                                 }
351                                 float3 p1 = mesh->verts[t.v[0]];
352                                 float3 p2 = mesh->verts[t.v[1]];
353                                 float3 p3 = mesh->verts[t.v[2]];
354
355                                 if(!transform_applied) {
356                                         p1 = transform_point(&tfm, p1);
357                                         p2 = transform_point(&tfm, p2);
358                                         p3 = transform_point(&tfm, p3);
359                                 }
360
361                                 totarea += triangle_area(p1, p2, p3);
362                         }
363                 }
364
365                 j++;
366         }
367
368         float trianglearea = totarea;
369
370         /* point lights */
371         float lightarea = (totarea > 0.0f) ? totarea / num_lights : 1.0f;
372         bool use_lamp_mis = false;
373
374         int light_index = 0;
375         foreach(Light *light, scene->lights) {
376                 if(!light->is_enabled)
377                         continue;
378
379                 distribution[offset].totarea = totarea;
380                 distribution[offset].prim = ~light_index;
381                 distribution[offset].lamp.pad = 1.0f;
382                 distribution[offset].lamp.size = light->size;
383                 totarea += lightarea;
384
385                 if(light->size > 0.0f && light->use_mis)
386                         use_lamp_mis = true;
387                 if(light->type == LIGHT_BACKGROUND) {
388                         num_background_lights++;
389                         background_mis = light->use_mis;
390                 }
391
392                 light_index++;
393                 offset++;
394         }
395
396         /* normalize cumulative distribution functions */
397         distribution[num_distribution].totarea = totarea;
398         distribution[num_distribution].prim = 0.0f;
399         distribution[num_distribution].lamp.pad = 0.0f;
400         distribution[num_distribution].lamp.size = 0.0f;
401
402         if(totarea > 0.0f) {
403                 for(size_t i = 0; i < num_distribution; i++)
404                         distribution[i].totarea /= totarea;
405                 distribution[num_distribution].totarea = 1.0f;
406         }
407
408         if(progress.get_cancel()) return;
409
410         /* update device */
411         KernelIntegrator *kintegrator = &dscene->data.integrator;
412         KernelFilm *kfilm = &dscene->data.film;
413         kintegrator->use_direct_light = (totarea > 0.0f);
414
415         if(kintegrator->use_direct_light) {
416                 /* number of emissives */
417                 kintegrator->num_distribution = num_distribution;
418
419                 /* precompute pdfs */
420                 kintegrator->pdf_triangles = 0.0f;
421                 kintegrator->pdf_lights = 0.0f;
422
423                 /* sample one, with 0.5 probability of light or triangle */
424                 kintegrator->num_all_lights = num_lights;
425
426                 if(trianglearea > 0.0f) {
427                         kintegrator->pdf_triangles = 1.0f/trianglearea;
428                         if(num_lights)
429                                 kintegrator->pdf_triangles *= 0.5f;
430                 }
431
432                 if(num_lights) {
433                         kintegrator->pdf_lights = 1.0f/num_lights;
434                         if(trianglearea > 0.0f)
435                                 kintegrator->pdf_lights *= 0.5f;
436                 }
437
438                 kintegrator->use_lamp_mis = use_lamp_mis;
439
440                 /* bit of an ugly hack to compensate for emitting triangles influencing
441                  * amount of samples we get for this pass */
442                 kfilm->pass_shadow_scale = 1.0f;
443
444                 if(kintegrator->pdf_triangles != 0.0f)
445                         kfilm->pass_shadow_scale *= 0.5f;
446
447                 if(num_background_lights < num_lights)
448                         kfilm->pass_shadow_scale *= (float)(num_lights - num_background_lights)/(float)num_lights;
449
450                 /* CDF */
451                 dscene->light_distribution.copy_to_device();
452
453                 /* Portals */
454                 if(num_portals > 0) {
455                         kintegrator->portal_offset = light_index;
456                         kintegrator->num_portals = num_portals;
457                         kintegrator->portal_pdf = background_mis? 0.5f: 1.0f;
458                 }
459                 else {
460                         kintegrator->num_portals = 0;
461                         kintegrator->portal_offset = 0;
462                         kintegrator->portal_pdf = 0.0f;
463                 }
464         }
465         else {
466                 dscene->light_distribution.free();
467
468                 kintegrator->num_distribution = 0;
469                 kintegrator->num_all_lights = 0;
470                 kintegrator->pdf_triangles = 0.0f;
471                 kintegrator->pdf_lights = 0.0f;
472                 kintegrator->use_lamp_mis = false;
473                 kintegrator->num_portals = 0;
474                 kintegrator->portal_offset = 0;
475                 kintegrator->portal_pdf = 0.0f;
476
477                 kfilm->pass_shadow_scale = 1.0f;
478         }
479 }
480
481 static void background_cdf(int start,
482                            int end,
483                            int res_x,
484                            int res_y,
485                            const vector<float3> *pixels,
486                            float2 *cond_cdf)
487 {
488         int cdf_width = res_x+1;
489         /* Conditional CDFs (rows, U direction). */
490         for(int i = start; i < end; i++) {
491                 float sin_theta = sinf(M_PI_F * (i + 0.5f) / res_y);
492                 float3 env_color = (*pixels)[i * res_x];
493                 float ave_luminance = average(env_color);
494
495                 cond_cdf[i * cdf_width].x = ave_luminance * sin_theta;
496                 cond_cdf[i * cdf_width].y = 0.0f;
497
498                 for(int j = 1; j < res_x; j++) {
499                         env_color = (*pixels)[i * res_x + j];
500                         ave_luminance = average(env_color);
501
502                         cond_cdf[i * cdf_width + j].x = ave_luminance * sin_theta;
503                         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;
504                 }
505
506                 float cdf_total = cond_cdf[i * cdf_width + res_x - 1].y + cond_cdf[i * cdf_width + res_x - 1].x / res_x;
507                 float cdf_total_inv = 1.0f / cdf_total;
508
509                 /* stuff the total into the brightness value for the last entry, because
510                  * we are going to normalize the CDFs to 0.0 to 1.0 afterwards */
511                 cond_cdf[i * cdf_width + res_x].x = cdf_total;
512
513                 if(cdf_total > 0.0f)
514                         for(int j = 1; j < res_x; j++)
515                                 cond_cdf[i * cdf_width + j].y *= cdf_total_inv;
516
517                 cond_cdf[i * cdf_width + res_x].y = 1.0f;
518         }
519 }
520
521 void LightManager::device_update_background(Device *device,
522                                             DeviceScene *dscene,
523                                             Scene *scene,
524                                             Progress& progress)
525 {
526         KernelIntegrator *kintegrator = &dscene->data.integrator;
527         Light *background_light = NULL;
528
529         /* find background light */
530         foreach(Light *light, scene->lights) {
531                 if(light->type == LIGHT_BACKGROUND) {
532                         background_light = light;
533                         break;
534                 }
535         }
536
537         /* no background light found, signal renderer to skip sampling */
538         if(!background_light || !background_light->is_enabled) {
539                 kintegrator->pdf_background_res_x = 0;
540                 kintegrator->pdf_background_res_y = 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         int2 res = make_int2(background_light->map_resolution, background_light->map_resolution/2);
550         /* If the resolution isn't set manually, try to find an environment texture. */
551         if(res.x == 0) {
552                 Shader *shader = (scene->background->shader) ? scene->background->shader : scene->default_background;
553                 foreach(ShaderNode *node, shader->graph->nodes) {
554                         if(node->type == EnvironmentTextureNode::node_type) {
555                                 EnvironmentTextureNode *env = (EnvironmentTextureNode*) node;
556                                 ImageMetaData metadata;
557                                 if(env->image_manager && env->image_manager->get_image_metadata(env->slot, metadata)) {
558                                         res.x = max(res.x, metadata.width);
559                                         res.y = max(res.y, metadata.height);
560                                 }
561                         }
562                 }
563                 if(res.x > 0 && res.y > 0) {
564                         VLOG(2) << "Automatically set World MIS resolution to " << res.x << " by " << res.y << "\n";
565                 }
566         }
567         /* If it's still unknown, just use the default. */
568         if(res.x == 0 || res.y == 0) {
569                 res = make_int2(1024, 512);
570                 VLOG(2) << "Setting World MIS resolution to default\n";
571         }
572         kintegrator->pdf_background_res_x = res.x;
573         kintegrator->pdf_background_res_y = res.y;
574
575         vector<float3> pixels;
576         shade_background_pixels(device, dscene, res.x, res.y, pixels, progress);
577
578         if(progress.get_cancel())
579                 return;
580
581         /* build row distributions and column distribution for the infinite area environment light */
582         int cdf_width = res.x+1;
583         float2 *marg_cdf = dscene->light_background_marginal_cdf.alloc(res.y + 1);
584         float2 *cond_cdf = dscene->light_background_conditional_cdf.alloc(cdf_width * res.y);
585
586         double time_start = time_dt();
587         if(max(res.x, res.y) < 512) {
588                 /* Small enough resolution, faster to do single-threaded. */
589                 background_cdf(0, res.y, res.x, res.y, &pixels, cond_cdf);
590         }
591         else {
592                 /* Threaded evaluation for large resolution. */
593                 const int num_blocks = TaskScheduler::num_threads();
594                 const int chunk_size = res.y / num_blocks;
595                 int start_row = 0;
596                 TaskPool pool;
597                 for(int i = 0; i < num_blocks; ++i) {
598                         const int current_chunk_size =
599                             (i != num_blocks - 1) ? chunk_size
600                                                   : (res.y - i * chunk_size);
601                         pool.push(function_bind(&background_cdf,
602                                                 start_row, start_row + current_chunk_size,
603                                                 res.x,
604                                                 res.y,
605                                                 &pixels,
606                                                 cond_cdf));
607                         start_row += current_chunk_size;
608                 }
609                 pool.wait_work();
610         }
611
612         /* marginal CDFs (column, V direction, sum of rows) */
613         marg_cdf[0].x = cond_cdf[res.x].x;
614         marg_cdf[0].y = 0.0f;
615
616         for(int i = 1; i < res.y; i++) {
617                 marg_cdf[i].x = cond_cdf[i * cdf_width + res.x].x;
618                 marg_cdf[i].y = marg_cdf[i - 1].y + marg_cdf[i - 1].x / res.y;
619         }
620
621         float cdf_total = marg_cdf[res.y - 1].y + marg_cdf[res.y - 1].x / res.y;
622         marg_cdf[res.y].x = cdf_total;
623
624         if(cdf_total > 0.0f)
625                 for(int i = 1; i < res.y; i++)
626                         marg_cdf[i].y /= cdf_total;
627
628         marg_cdf[res.y].y = 1.0f;
629
630         VLOG(2) << "Background MIS build time " << time_dt() - time_start << "\n";
631
632         /* update device */
633         dscene->light_background_marginal_cdf.copy_to_device();
634         dscene->light_background_conditional_cdf.copy_to_device();
635 }
636
637 void LightManager::device_update_points(Device *,
638                                         DeviceScene *dscene,
639                                         Scene *scene)
640 {
641         int num_scene_lights = scene->lights.size();
642
643         int num_lights = 0;
644         foreach(Light *light, scene->lights) {
645                 if(light->is_enabled || light->is_portal) {
646                         num_lights++;
647                 }
648         }
649
650         KernelLight *klights = dscene->lights.alloc(num_lights);
651
652         if(num_lights == 0) {
653                 VLOG(1) << "No effective light, ignoring points update.";
654                 return;
655         }
656
657         int light_index = 0;
658
659         foreach(Light *light, scene->lights) {
660                 if(!light->is_enabled) {
661                         continue;
662                 }
663
664                 float3 co = light->co;
665                 Shader *shader = (light->shader) ? light->shader : scene->default_light;
666                 int shader_id = scene->shader_manager->get_shader_id(shader);
667                 int samples = light->samples;
668                 int max_bounces = light->max_bounces;
669                 float random = (float)light->random_id * (1.0f/(float)0xFFFFFFFF);
670
671                 if(!light->cast_shadow)
672                         shader_id &= ~SHADER_CAST_SHADOW;
673
674                 if(!light->use_diffuse) {
675                         shader_id |= SHADER_EXCLUDE_DIFFUSE;
676                         use_light_visibility = true;
677                 }
678                 if(!light->use_glossy) {
679                         shader_id |= SHADER_EXCLUDE_GLOSSY;
680                         use_light_visibility = true;
681                 }
682                 if(!light->use_transmission) {
683                         shader_id |= SHADER_EXCLUDE_TRANSMIT;
684                         use_light_visibility = true;
685                 }
686                 if(!light->use_scatter) {
687                         shader_id |= SHADER_EXCLUDE_SCATTER;
688                         use_light_visibility = true;
689                 }
690
691                 klights[light_index].type = light->type;
692                 klights[light_index].samples = samples;
693
694                 if(light->type == LIGHT_POINT) {
695                         shader_id &= ~SHADER_AREA_LIGHT;
696
697                         float radius = light->size;
698                         float invarea = (radius > 0.0f)? 1.0f/(M_PI_F*radius*radius): 1.0f;
699
700                         if(light->use_mis && radius > 0.0f)
701                                 shader_id |= SHADER_USE_MIS;
702
703                         klights[light_index].co[0] = co.x;
704                         klights[light_index].co[1] = co.y;
705                         klights[light_index].co[2] = co.z;
706
707                         klights[light_index].spot.radius = radius;
708                         klights[light_index].spot.invarea = invarea;
709                 }
710                 else if(light->type == LIGHT_DISTANT) {
711                         shader_id &= ~SHADER_AREA_LIGHT;
712
713                         float radius = light->size;
714                         float angle = atanf(radius);
715                         float cosangle = cosf(angle);
716                         float area = M_PI_F*radius*radius;
717                         float invarea = (area > 0.0f)? 1.0f/area: 1.0f;
718                         float3 dir = light->dir;
719
720                         dir = safe_normalize(dir);
721
722                         if(light->use_mis && area > 0.0f)
723                                 shader_id |= SHADER_USE_MIS;
724
725                         klights[light_index].co[0] = dir.x;
726                         klights[light_index].co[1] = dir.y;
727                         klights[light_index].co[2] = dir.z;
728
729                         klights[light_index].distant.invarea = invarea;
730                         klights[light_index].distant.radius = radius;
731                         klights[light_index].distant.cosangle = cosangle;
732                 }
733                 else if(light->type == LIGHT_BACKGROUND) {
734                         uint visibility = scene->background->visibility;
735
736                         shader_id &= ~SHADER_AREA_LIGHT;
737                         shader_id |= SHADER_USE_MIS;
738
739                         if(!(visibility & PATH_RAY_DIFFUSE)) {
740                                 shader_id |= SHADER_EXCLUDE_DIFFUSE;
741                                 use_light_visibility = true;
742                         }
743                         if(!(visibility & PATH_RAY_GLOSSY)) {
744                                 shader_id |= SHADER_EXCLUDE_GLOSSY;
745                                 use_light_visibility = true;
746                         }
747                         if(!(visibility & PATH_RAY_TRANSMIT)) {
748                                 shader_id |= SHADER_EXCLUDE_TRANSMIT;
749                                 use_light_visibility = true;
750                         }
751                         if(!(visibility & PATH_RAY_VOLUME_SCATTER)) {
752                                 shader_id |= SHADER_EXCLUDE_SCATTER;
753                                 use_light_visibility = true;
754                         }
755                 }
756                 else if(light->type == LIGHT_AREA) {
757                         float3 axisu = light->axisu*(light->sizeu*light->size);
758                         float3 axisv = light->axisv*(light->sizev*light->size);
759                         float area = len(axisu)*len(axisv);
760                         if(light->round) {
761                                 area *= -M_PI_4_F;
762                         }
763                         float invarea = (area != 0.0f)? 1.0f/area: 1.0f;
764                         float3 dir = light->dir;
765
766                         dir = safe_normalize(dir);
767
768                         if(light->use_mis && area != 0.0f)
769                                 shader_id |= SHADER_USE_MIS;
770
771                         klights[light_index].co[0] = co.x;
772                         klights[light_index].co[1] = co.y;
773                         klights[light_index].co[2] = co.z;
774
775                         klights[light_index].area.axisu[0] = axisu.x;
776                         klights[light_index].area.axisu[1] = axisu.y;
777                         klights[light_index].area.axisu[2] = axisu.z;
778                         klights[light_index].area.axisv[0] = axisv.x;
779                         klights[light_index].area.axisv[1] = axisv.y;
780                         klights[light_index].area.axisv[2] = axisv.z;
781                         klights[light_index].area.invarea = invarea;
782                         klights[light_index].area.dir[0] = dir.x;
783                         klights[light_index].area.dir[1] = dir.y;
784                         klights[light_index].area.dir[2] = dir.z;
785                 }
786                 else if(light->type == LIGHT_SPOT) {
787                         shader_id &= ~SHADER_AREA_LIGHT;
788
789                         float radius = light->size;
790                         float invarea = (radius > 0.0f)? 1.0f/(M_PI_F*radius*radius): 1.0f;
791                         float spot_angle = cosf(light->spot_angle*0.5f);
792                         float spot_smooth = (1.0f - spot_angle)*light->spot_smooth;
793                         float3 dir = light->dir;
794
795                         dir = safe_normalize(dir);
796
797                         if(light->use_mis && radius > 0.0f)
798                                 shader_id |= SHADER_USE_MIS;
799
800                         klights[light_index].co[0] = co.x;
801                         klights[light_index].co[1] = co.y;
802                         klights[light_index].co[2] = co.z;
803
804                         klights[light_index].spot.radius = radius;
805                         klights[light_index].spot.invarea = invarea;
806                         klights[light_index].spot.spot_angle = spot_angle;
807                         klights[light_index].spot.spot_smooth = spot_smooth;
808                         klights[light_index].spot.dir[0] = dir.x;
809                         klights[light_index].spot.dir[1] = dir.y;
810                         klights[light_index].spot.dir[2] = dir.z;
811                 }
812
813                 klights[light_index].shader_id = shader_id;
814
815                 klights[light_index].max_bounces = max_bounces;
816                 klights[light_index].random = random;
817
818                 klights[light_index].tfm = light->tfm;
819                 klights[light_index].itfm = transform_inverse(light->tfm);
820
821                 light_index++;
822         }
823
824         /* TODO(sergey): Consider moving portals update to their own function
825          * keeping this one more manageable.
826          */
827         foreach(Light *light, scene->lights) {
828                 if(!light->is_portal)
829                         continue;
830                 assert(light->type == LIGHT_AREA);
831
832                 float3 co = light->co;
833                 float3 axisu = light->axisu*(light->sizeu*light->size);
834                 float3 axisv = light->axisv*(light->sizev*light->size);
835                 float area = len(axisu)*len(axisv);
836                 if(light->round) {
837                         area *= -M_PI_4_F;
838                 }
839                 float invarea = (area != 0.0f)? 1.0f/area: 1.0f;
840                 float3 dir = light->dir;
841
842                 dir = safe_normalize(dir);
843
844                 klights[light_index].co[0] = co.x;
845                 klights[light_index].co[1] = co.y;
846                 klights[light_index].co[2] = co.z;
847
848                 klights[light_index].area.axisu[0] = axisu.x;
849                 klights[light_index].area.axisu[1] = axisu.y;
850                 klights[light_index].area.axisu[2] = axisu.z;
851                 klights[light_index].area.axisv[0] = axisv.x;
852                 klights[light_index].area.axisv[1] = axisv.y;
853                 klights[light_index].area.axisv[2] = axisv.z;
854                 klights[light_index].area.invarea = invarea;
855                 klights[light_index].area.dir[0] = dir.x;
856                 klights[light_index].area.dir[1] = dir.y;
857                 klights[light_index].area.dir[2] = dir.z;
858                 klights[light_index].tfm = light->tfm;
859                 klights[light_index].itfm = transform_inverse(light->tfm);
860
861                 light_index++;
862         }
863
864         VLOG(1) << "Number of lights sent to the device: " << light_index;
865
866         VLOG(1) << "Number of lights without contribution: "
867                 << num_scene_lights - light_index;
868
869         dscene->lights.copy_to_device();
870 }
871
872 void LightManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
873 {
874         if(!need_update)
875                 return;
876
877         VLOG(1) << "Total " << scene->lights.size() << " lights.";
878
879         device_free(device, dscene);
880
881         use_light_visibility = false;
882
883         disable_ineffective_light(device, scene);
884
885         device_update_points(device, dscene, scene);
886         if(progress.get_cancel()) return;
887
888         device_update_distribution(device, dscene, scene, progress);
889         if(progress.get_cancel()) return;
890
891         device_update_background(device, dscene, scene, progress);
892         if(progress.get_cancel()) return;
893
894         device_update_ies(dscene);
895         if(progress.get_cancel()) return;
896
897         if(use_light_visibility != scene->film->use_light_visibility) {
898                 scene->film->use_light_visibility = use_light_visibility;
899                 scene->film->tag_update(scene);
900         }
901
902         need_update = false;
903 }
904
905 void LightManager::device_free(Device *, DeviceScene *dscene)
906 {
907         dscene->light_distribution.free();
908         dscene->lights.free();
909         dscene->light_background_marginal_cdf.free();
910         dscene->light_background_conditional_cdf.free();
911         dscene->ies_lights.free();
912 }
913
914 void LightManager::tag_update(Scene * /*scene*/)
915 {
916         need_update = true;
917 }
918
919 int LightManager::add_ies_from_file(ustring filename)
920 {
921         string content;
922
923         /* If the file can't be opened, call with an empty line */
924         if(filename.empty() || !path_read_text(filename.c_str(), content)) {
925                 content = "\n";
926         }
927
928         return add_ies(ustring(content));
929 }
930
931 int LightManager::add_ies(ustring content)
932 {
933         uint hash = hash_string(content.c_str());
934
935         thread_scoped_lock ies_lock(ies_mutex);
936
937         /* Check whether this IES already has a slot. */
938         size_t slot;
939         for(slot = 0; slot < ies_slots.size(); slot++) {
940                 if(ies_slots[slot]->hash == hash) {
941                         ies_slots[slot]->users++;
942                         return slot;
943                 }
944         }
945
946         /* Try to find an empty slot for the new IES. */
947         for(slot = 0; slot < ies_slots.size(); slot++) {
948                 if(ies_slots[slot]->users == 0 && ies_slots[slot]->hash == 0) {
949                         break;
950                 }
951         }
952
953         /* If there's no free slot, add one. */
954         if(slot == ies_slots.size()) {
955                 ies_slots.push_back(new IESSlot());
956         }
957
958         ies_slots[slot]->ies.load(content);
959         ies_slots[slot]->users = 1;
960         ies_slots[slot]->hash = hash;
961
962         need_update = true;
963
964         return slot;
965 }
966
967 void LightManager::remove_ies(int slot)
968 {
969         thread_scoped_lock ies_lock(ies_mutex);
970
971         if(slot < 0 || slot >= ies_slots.size()) {
972                 assert(false);
973                 return;
974         }
975
976         assert(ies_slots[slot]->users > 0);
977         ies_slots[slot]->users--;
978
979         /* If the slot has no more users, update the device to remove it. */
980         need_update |= (ies_slots[slot]->users == 0);
981 }
982
983 void LightManager::device_update_ies(DeviceScene *dscene)
984 {
985         /* Clear empty slots. */
986         foreach(IESSlot *slot, ies_slots) {
987                 if(slot->users == 0) {
988                         slot->hash = 0;
989                         slot->ies.clear();
990                 }
991         }
992
993         /* Shrink the slot table by removing empty slots at the end. */
994         int slot_end;
995         for(slot_end = ies_slots.size(); slot_end; slot_end--) {
996                 if(ies_slots[slot_end-1]->users > 0) {
997                         /* If the preceding slot has users, we found the new end of the table. */
998                         break;
999                 }
1000                 else {
1001                         /* The slot will be past the new end of the table, so free it. */
1002                         delete ies_slots[slot_end-1];
1003                 }
1004         }
1005         ies_slots.resize(slot_end);
1006
1007         if(ies_slots.size() > 0) {
1008                 int packed_size = 0;
1009                 foreach(IESSlot *slot, ies_slots) {
1010                         packed_size += slot->ies.packed_size();
1011                 }
1012
1013                 /* ies_lights starts with an offset table that contains the offset of every slot,
1014                  * or -1 if the slot is invalid.
1015                  * Following that table, the packed valid IES lights are stored. */
1016                 float *data = dscene->ies_lights.alloc(ies_slots.size() + packed_size);
1017
1018                 int offset = ies_slots.size();
1019                 for(int i = 0; i < ies_slots.size(); i++) {
1020                         int size = ies_slots[i]->ies.packed_size();
1021                         if(size > 0) {
1022                                 data[i] = __int_as_float(offset);
1023                                 ies_slots[i]->ies.pack(data + offset);
1024                                 offset += size;
1025                         }
1026                         else {
1027                                 data[i] = __int_as_float(-1);
1028                         }
1029                 }
1030
1031                 dscene->ies_lights.copy_to_device();
1032         }
1033 }
1034
1035 CCL_NAMESPACE_END