Cycles: Query XYZ to/from Scene Linear conversion from OCIO instead of assuming sRGB
[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
122         SOCKET_INT(map_resolution, "Map Resolution", 0);
123
124         SOCKET_FLOAT(spot_angle, "Spot Angle", M_PI_4_F);
125         SOCKET_FLOAT(spot_smooth, "Spot Smooth", 0.0f);
126
127         SOCKET_TRANSFORM(tfm, "Transform", transform_identity());
128
129         SOCKET_BOOLEAN(cast_shadow, "Cast Shadow", true);
130         SOCKET_BOOLEAN(use_mis, "Use Mis", false);
131         SOCKET_BOOLEAN(use_diffuse, "Use Diffuse", true);
132         SOCKET_BOOLEAN(use_glossy, "Use Glossy", true);
133         SOCKET_BOOLEAN(use_transmission, "Use Transmission", true);
134         SOCKET_BOOLEAN(use_scatter, "Use Scatter", true);
135
136         SOCKET_INT(samples, "Samples", 1);
137         SOCKET_INT(max_bounces, "Max Bounces", 1024);
138         SOCKET_UINT(random_id, "Random ID", 0);
139
140         SOCKET_BOOLEAN(is_portal, "Is Portal", false);
141         SOCKET_BOOLEAN(is_enabled, "Is Enabled", true);
142
143         SOCKET_NODE(shader, "Shader", &Shader::node_type);
144
145         return type;
146 }
147
148 Light::Light()
149 : Node(node_type)
150 {
151 }
152
153 void Light::tag_update(Scene *scene)
154 {
155         scene->light_manager->need_update = true;
156 }
157
158 bool Light::has_contribution(Scene *scene)
159 {
160         if(is_portal) {
161                 return false;
162         }
163         if(type == LIGHT_BACKGROUND) {
164                 return true;
165         }
166         return (shader) ? shader->has_surface_emission : scene->default_light->has_surface_emission;
167 }
168
169 /* Light Manager */
170
171 LightManager::LightManager()
172 {
173         need_update = true;
174         use_light_visibility = false;
175 }
176
177 LightManager::~LightManager()
178 {
179         foreach(IESSlot *slot, ies_slots) {
180                 delete slot;
181         }
182 }
183
184 bool LightManager::has_background_light(Scene *scene)
185 {
186         foreach(Light *light, scene->lights) {
187                 if(light->type == LIGHT_BACKGROUND) {
188                         return true;
189                 }
190         }
191         return false;
192 }
193
194 void LightManager::disable_ineffective_light(Device *device, Scene *scene)
195 {
196         /* Make all lights enabled by default, and perform some preliminary checks
197          * needed for finer-tuning of settings (for example, check whether we've
198          * got portals or not).
199          */
200         bool has_portal = false, has_background = false;
201         foreach(Light *light, scene->lights) {
202                 light->is_enabled = light->has_contribution(scene);
203                 has_portal |= light->is_portal;
204                 has_background |= light->type == LIGHT_BACKGROUND;
205         }
206
207         if(has_background) {
208                 /* Ignore background light if:
209                  * - If unsupported on a device
210                  * - If we don't need it (no HDRs etc.)
211                  */
212                 Shader *shader = (scene->background->shader) ? scene->background->shader : scene->default_background;
213                 bool disable_mis = !(has_portal || shader->has_surface_spatial_varying) ||
214                                    !(device->info.advanced_shading);
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.x, 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                         float invarea = (area > 0.0f)? 1.0f/area: 1.0f;
761                         float3 dir = light->dir;
762                         
763                         dir = safe_normalize(dir);
764
765                         if(light->use_mis && area > 0.0f)
766                                 shader_id |= SHADER_USE_MIS;
767
768                         klights[light_index].co[0] = co.x;
769                         klights[light_index].co[1] = co.y;
770                         klights[light_index].co[2] = co.z;
771
772                         klights[light_index].area.axisu[0] = axisu.x;
773                         klights[light_index].area.axisu[1] = axisu.y;
774                         klights[light_index].area.axisu[2] = axisu.z;
775                         klights[light_index].area.axisv[0] = axisv.x;
776                         klights[light_index].area.axisv[1] = axisv.y;
777                         klights[light_index].area.axisv[2] = axisv.z;
778                         klights[light_index].area.invarea = invarea;
779                         klights[light_index].area.dir[0] = dir.x;
780                         klights[light_index].area.dir[1] = dir.y;
781                         klights[light_index].area.dir[2] = dir.z;
782                 }
783                 else if(light->type == LIGHT_SPOT) {
784                         shader_id &= ~SHADER_AREA_LIGHT;
785
786                         float radius = light->size;
787                         float invarea = (radius > 0.0f)? 1.0f/(M_PI_F*radius*radius): 1.0f;
788                         float spot_angle = cosf(light->spot_angle*0.5f);
789                         float spot_smooth = (1.0f - spot_angle)*light->spot_smooth;
790                         float3 dir = light->dir;
791                         
792                         dir = safe_normalize(dir);
793
794                         if(light->use_mis && radius > 0.0f)
795                                 shader_id |= SHADER_USE_MIS;
796
797                         klights[light_index].co[0] = co.x;
798                         klights[light_index].co[1] = co.y;
799                         klights[light_index].co[2] = co.z;
800
801                         klights[light_index].spot.radius = radius;
802                         klights[light_index].spot.invarea = invarea;
803                         klights[light_index].spot.spot_angle = spot_angle;
804                         klights[light_index].spot.spot_smooth = spot_smooth;
805                         klights[light_index].spot.dir[0] = dir.x;
806                         klights[light_index].spot.dir[1] = dir.y;
807                         klights[light_index].spot.dir[2] = dir.z;
808                 }
809
810                 klights[light_index].shader_id = shader_id;
811
812                 klights[light_index].max_bounces = max_bounces;
813                 klights[light_index].random = random;
814
815                 klights[light_index].tfm = light->tfm;
816                 klights[light_index].itfm = transform_inverse(light->tfm);
817
818                 light_index++;
819         }
820
821         /* TODO(sergey): Consider moving portals update to their own function
822          * keeping this one more manageable.
823          */
824         foreach(Light *light, scene->lights) {
825                 if(!light->is_portal)
826                         continue;
827                 assert(light->type == LIGHT_AREA);
828
829                 float3 co = light->co;
830                 float3 axisu = light->axisu*(light->sizeu*light->size);
831                 float3 axisv = light->axisv*(light->sizev*light->size);
832                 float area = len(axisu)*len(axisv);
833                 float invarea = (area > 0.0f)? 1.0f/area: 1.0f;
834                 float3 dir = light->dir;
835
836                 dir = safe_normalize(dir);
837
838                 klights[light_index].co[0] = co.x;
839                 klights[light_index].co[1] = co.y;
840                 klights[light_index].co[2] = co.z;
841
842                 klights[light_index].area.axisu[0] = axisu.x;
843                 klights[light_index].area.axisu[1] = axisu.y;
844                 klights[light_index].area.axisu[2] = axisu.z;
845                 klights[light_index].area.axisv[0] = axisv.x;
846                 klights[light_index].area.axisv[1] = axisv.y;
847                 klights[light_index].area.axisv[2] = axisv.z;
848                 klights[light_index].area.invarea = invarea;
849                 klights[light_index].area.dir[0] = dir.x;
850                 klights[light_index].area.dir[1] = dir.y;
851                 klights[light_index].area.dir[2] = dir.z;
852                 klights[light_index].tfm = light->tfm;
853                 klights[light_index].itfm = transform_inverse(light->tfm);
854
855                 light_index++;
856         }
857
858         VLOG(1) << "Number of lights sent to the device: " << light_index;
859
860         VLOG(1) << "Number of lights without contribution: "
861                 << num_scene_lights - light_index;
862
863         dscene->lights.copy_to_device();
864 }
865
866 void LightManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
867 {
868         if(!need_update)
869                 return;
870
871         VLOG(1) << "Total " << scene->lights.size() << " lights.";
872
873         device_free(device, dscene);
874
875         use_light_visibility = false;
876
877         disable_ineffective_light(device, scene);
878
879         device_update_points(device, dscene, scene);
880         if(progress.get_cancel()) return;
881
882         device_update_distribution(device, dscene, scene, progress);
883         if(progress.get_cancel()) return;
884
885         device_update_background(device, dscene, scene, progress);
886         if(progress.get_cancel()) return;
887
888         device_update_ies(dscene);
889         if(progress.get_cancel()) return;
890
891         if(use_light_visibility != scene->film->use_light_visibility) {
892                 scene->film->use_light_visibility = use_light_visibility;
893                 scene->film->tag_update(scene);
894         }
895
896         need_update = false;
897 }
898
899 void LightManager::device_free(Device *, DeviceScene *dscene)
900 {
901         dscene->light_distribution.free();
902         dscene->lights.free();
903         dscene->light_background_marginal_cdf.free();
904         dscene->light_background_conditional_cdf.free();
905         dscene->ies_lights.free();
906 }
907
908 void LightManager::tag_update(Scene * /*scene*/)
909 {
910         need_update = true;
911 }
912
913 int LightManager::add_ies_from_file(ustring filename)
914 {
915         string content;
916
917         /* If the file can't be opened, call with an empty line */
918         if(filename.empty() || !path_read_text(filename.c_str(), content)) {
919                 content = "\n";
920         }
921
922         return add_ies(ustring(content));
923 }
924
925 int LightManager::add_ies(ustring content)
926 {
927         uint hash = hash_string(content.c_str());
928
929         thread_scoped_lock ies_lock(ies_mutex);
930
931         /* Check whether this IES already has a slot. */
932         size_t slot;
933         for(slot = 0; slot < ies_slots.size(); slot++) {
934                 if(ies_slots[slot]->hash == hash) {
935                         ies_slots[slot]->users++;
936                         return slot;
937                 }
938         }
939
940         /* Try to find an empty slot for the new IES. */
941         for(slot = 0; slot < ies_slots.size(); slot++) {
942                 if(ies_slots[slot]->users == 0 && ies_slots[slot]->hash == 0) {
943                         break;
944                 }
945         }
946
947         /* If there's no free slot, add one. */
948         if(slot == ies_slots.size()) {
949                 ies_slots.push_back(new IESSlot());
950         }
951
952         ies_slots[slot]->ies.load(content);
953         ies_slots[slot]->users = 1;
954         ies_slots[slot]->hash = hash;
955
956         need_update = true;
957
958         return slot;
959 }
960
961 void LightManager::remove_ies(int slot)
962 {
963         thread_scoped_lock ies_lock(ies_mutex);
964
965         if(slot < 0 || slot >= ies_slots.size()) {
966                 assert(false);
967                 return;
968         }
969
970         assert(ies_slots[slot]->users > 0);
971         ies_slots[slot]->users--;
972
973         /* If the slot has no more users, update the device to remove it. */
974         need_update |= (ies_slots[slot]->users == 0);
975 }
976
977 void LightManager::device_update_ies(DeviceScene *dscene)
978 {
979         /* Clear empty slots. */
980         foreach(IESSlot *slot, ies_slots) {
981                 if(slot->users == 0) {
982                         slot->hash = 0;
983                         slot->ies.clear();
984                 }
985         }
986
987         /* Shrink the slot table by removing empty slots at the end. */
988         int slot_end;
989         for(slot_end = ies_slots.size(); slot_end; slot_end--) {
990                 if(ies_slots[slot_end-1]->users > 0) {
991                         /* If the preceding slot has users, we found the new end of the table. */
992                         break;
993                 }
994                 else {
995                         /* The slot will be past the new end of the table, so free it. */
996                         delete ies_slots[slot_end-1];
997                 }
998         }
999         ies_slots.resize(slot_end);
1000
1001         if(ies_slots.size() > 0) {
1002                 int packed_size = 0;
1003                 foreach(IESSlot *slot, ies_slots) {
1004                         packed_size += slot->ies.packed_size();
1005                 }
1006
1007                 /* ies_lights starts with an offset table that contains the offset of every slot,
1008                  * or -1 if the slot is invalid.
1009                  * Following that table, the packed valid IES lights are stored. */
1010                 float *data = dscene->ies_lights.alloc(ies_slots.size() + packed_size);
1011
1012                 int offset = ies_slots.size();
1013                 for(int i = 0; i < ies_slots.size(); i++) {
1014                         int size = ies_slots[i]->ies.packed_size();
1015                         if(size > 0) {
1016                                 data[i] = __int_as_float(offset);
1017                                 ies_slots[i]->ies.pack(data + offset);
1018                                 offset += size;
1019                         }
1020                         else {
1021                                 data[i] = __int_as_float(-1);
1022                         }
1023                 }
1024
1025                 dscene->ies_lights.copy_to_device();
1026         }
1027 }
1028
1029 CCL_NAMESPACE_END
1030