Cycles microdisplacement: Move displacement options from mesh to material settings
[blender.git] / intern / cycles / render / shader.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 "background.h"
18 #include "camera.h"
19 #include "device.h"
20 #include "graph.h"
21 #include "integrator.h"
22 #include "light.h"
23 #include "mesh.h"
24 #include "nodes.h"
25 #include "object.h"
26 #include "osl.h"
27 #include "scene.h"
28 #include "shader.h"
29 #include "svm.h"
30 #include "tables.h"
31
32 #include "util_foreach.h"
33
34 CCL_NAMESPACE_BEGIN
35
36 vector<float> ShaderManager::beckmann_table;
37
38 /* Beckmann sampling precomputed table, see bsdf_microfacet.h */
39
40 /* 2D slope distribution (alpha = 1.0) */
41 static float beckmann_table_P22(const float slope_x, const float slope_y)
42 {
43         return expf(-(slope_x*slope_x + slope_y*slope_y));
44 }
45
46 /* maximal slope amplitude (range that contains 99.99% of the distribution) */
47 static float beckmann_table_slope_max()
48 {
49         return 6.0;
50 }
51
52 /* Paper used: Importance Sampling Microfacet-Based BSDFs with the
53  * Distribution of Visible Normals. Supplemental Material 2/2.
54  *
55  * http://hal.inria.fr/docs/01/00/66/20/ANNEX/supplemental2.pdf
56  */
57 static void beckmann_table_rows(float *table, int row_from, int row_to)
58 {
59         /* allocate temporary data */
60         const int DATA_TMP_SIZE = 512;
61         vector<double> slope_x(DATA_TMP_SIZE);
62         vector<double> CDF_P22_omega_i(DATA_TMP_SIZE);
63
64         /* loop over incident directions */
65         for(int index_theta = row_from; index_theta < row_to; index_theta++) {
66                 /* incident vector */
67                 const float cos_theta = index_theta / (BECKMANN_TABLE_SIZE - 1.0f);
68                 const float sin_theta = safe_sqrtf(1.0f - cos_theta*cos_theta);
69
70                 /* for a given incident vector
71                  * integrate P22_{omega_i}(x_slope, 1, 1), Eq. (10) */
72                 slope_x[0] = (double)-beckmann_table_slope_max();
73                 CDF_P22_omega_i[0] = 0;
74
75                 for(int index_slope_x = 1; index_slope_x < DATA_TMP_SIZE; ++index_slope_x) {
76                         /* slope_x */
77                         slope_x[index_slope_x] = (double)(-beckmann_table_slope_max() + 2.0f * beckmann_table_slope_max() * index_slope_x/(DATA_TMP_SIZE - 1.0f));
78
79                         /* dot product with incident vector */
80                         float dot_product = fmaxf(0.0f, -(float)slope_x[index_slope_x]*sin_theta + cos_theta);
81                         /* marginalize P22_{omega_i}(x_slope, 1, 1), Eq. (10) */
82                         float P22_omega_i = 0.0f;
83
84                         for(int j = 0; j < 100; ++j) {
85                                 float slope_y = -beckmann_table_slope_max() + 2.0f * beckmann_table_slope_max() * j * (1.0f/99.0f);
86                                 P22_omega_i += dot_product * beckmann_table_P22((float)slope_x[index_slope_x], slope_y);
87                         }
88
89                         /* CDF of P22_{omega_i}(x_slope, 1, 1), Eq. (10) */
90                         CDF_P22_omega_i[index_slope_x] = CDF_P22_omega_i[index_slope_x - 1] + (double)P22_omega_i;
91                 }
92
93                 /* renormalize CDF_P22_omega_i */
94                 for(int index_slope_x = 1; index_slope_x < DATA_TMP_SIZE; ++index_slope_x)
95                         CDF_P22_omega_i[index_slope_x] /= CDF_P22_omega_i[DATA_TMP_SIZE - 1];
96
97                 /* loop over random number U1 */
98                 int index_slope_x = 0;
99
100                 for(int index_U = 0; index_U < BECKMANN_TABLE_SIZE; ++index_U) {
101                         const double U = 0.0000001 + 0.9999998 * index_U / (double)(BECKMANN_TABLE_SIZE - 1);
102
103                         /* inverse CDF_P22_omega_i, solve Eq.(11) */
104                         while(CDF_P22_omega_i[index_slope_x] <= U)
105                                 ++index_slope_x;
106
107                         const double interp =
108                                 (CDF_P22_omega_i[index_slope_x] - U) /
109                                 (CDF_P22_omega_i[index_slope_x] - CDF_P22_omega_i[index_slope_x - 1]);
110
111                         /* store value */
112                         table[index_U + index_theta*BECKMANN_TABLE_SIZE] = (float)(
113                                 interp * slope_x[index_slope_x - 1] +
114                                     (1.0 - interp) * slope_x[index_slope_x]);
115                 }
116         }
117 }
118
119 static void beckmann_table_build(vector<float>& table)
120 {
121         table.resize(BECKMANN_TABLE_SIZE*BECKMANN_TABLE_SIZE);
122
123         /* multithreaded build */
124         TaskPool pool;
125
126         for(int i = 0; i < BECKMANN_TABLE_SIZE; i+=8)
127                 pool.push(function_bind(&beckmann_table_rows, &table[0], i, i+8));
128
129         pool.wait_work();
130 }
131
132 /* Shader */
133
134 NODE_DEFINE(Shader)
135 {
136         NodeType* type = NodeType::add("shader", create);
137
138         SOCKET_BOOLEAN(use_mis, "Use MIS", true);
139         SOCKET_BOOLEAN(use_transparent_shadow, "Use Transparent Shadow", true);
140         SOCKET_BOOLEAN(heterogeneous_volume, "Heterogeneous Volume", true);
141
142         static NodeEnum volume_sampling_method_enum;
143         volume_sampling_method_enum.insert("distance", VOLUME_SAMPLING_DISTANCE);
144         volume_sampling_method_enum.insert("equiangular", VOLUME_SAMPLING_EQUIANGULAR);
145         volume_sampling_method_enum.insert("multiple_importance", VOLUME_SAMPLING_MULTIPLE_IMPORTANCE);
146         SOCKET_ENUM(volume_sampling_method, "Volume Sampling Method", volume_sampling_method_enum, VOLUME_SAMPLING_DISTANCE);
147
148         static NodeEnum volume_interpolation_method_enum;
149         volume_interpolation_method_enum.insert("linear", VOLUME_INTERPOLATION_LINEAR);
150         volume_interpolation_method_enum.insert("cubic", VOLUME_INTERPOLATION_CUBIC);
151         SOCKET_ENUM(volume_interpolation_method, "Volume Interpolation Method", volume_interpolation_method_enum, VOLUME_INTERPOLATION_LINEAR);
152
153         static NodeEnum displacement_method_enum;
154         displacement_method_enum.insert("bump", DISPLACE_BUMP);
155         displacement_method_enum.insert("true", DISPLACE_TRUE);
156         displacement_method_enum.insert("both", DISPLACE_BOTH);
157         SOCKET_ENUM(displacement_method, "Displacement Method", displacement_method_enum, DISPLACE_BUMP);
158
159         return type;
160 }
161
162 Shader::Shader()
163 : Node(node_type)
164 {
165         pass_id = 0;
166
167         graph = NULL;
168         graph_bump = NULL;
169
170         has_surface = false;
171         has_surface_transparent = false;
172         has_surface_emission = false;
173         has_surface_bssrdf = false;
174         has_volume = false;
175         has_displacement = false;
176         has_bssrdf_bump = false;
177         has_surface_spatial_varying = false;
178         has_volume_spatial_varying = false;
179         has_object_dependency = false;
180         has_integrator_dependency = false;
181
182         displacement_method = DISPLACE_BUMP;
183
184         id = -1;
185         used = false;
186
187         need_update = true;
188         need_update_attributes = true;
189 }
190
191 Shader::~Shader()
192 {
193         delete graph;
194         delete graph_bump;
195 }
196
197 void Shader::set_graph(ShaderGraph *graph_)
198 {
199         /* do this here already so that we can detect if mesh or object attributes
200          * are needed, since the node attribute callbacks check if their sockets
201          * are connected but proxy nodes should not count */
202         if(graph_)
203                 graph_->remove_proxy_nodes();
204
205         /* assign graph */
206         delete graph;
207         delete graph_bump;
208         graph = graph_;
209         graph_bump = NULL;
210 }
211
212 void Shader::tag_update(Scene *scene)
213 {
214         /* update tag */
215         need_update = true;
216         scene->shader_manager->need_update = true;
217
218         /* if the shader previously was emissive, update light distribution,
219          * if the new shader is emissive, a light manager update tag will be
220          * done in the shader manager device update. */
221         if(use_mis && has_surface_emission)
222                 scene->light_manager->need_update = true;
223
224         /* quick detection of which kind of shaders we have to avoid loading
225          * e.g. surface attributes when there is only a volume shader. this could
226          * be more fine grained but it's better than nothing */
227         OutputNode *output = graph->output();
228         bool prev_has_volume = has_volume;
229         has_surface = has_surface || output->input("Surface")->link;
230         has_volume = has_volume || output->input("Volume")->link;
231         has_displacement = has_displacement || output->input("Displacement")->link;
232
233         /* get requested attributes. this could be optimized by pruning unused
234          * nodes here already, but that's the job of the shader manager currently,
235          * and may not be so great for interactive rendering where you temporarily
236          * disconnect a node */
237
238         AttributeRequestSet prev_attributes = attributes;
239
240         attributes.clear();
241         foreach(ShaderNode *node, graph->nodes)
242                 node->attributes(this, &attributes);
243         
244         /* compare if the attributes changed, mesh manager will check
245          * need_update_attributes, update the relevant meshes and clear it. */
246         if(attributes.modified(prev_attributes)) {
247                 need_update_attributes = true;
248                 scene->mesh_manager->need_update = true;
249         }
250
251         if(has_volume != prev_has_volume) {
252                 scene->mesh_manager->need_flags_update = true;
253                 scene->object_manager->need_flags_update = true;
254         }
255 }
256
257 void Shader::tag_used(Scene *scene)
258 {
259         /* if an unused shader suddenly gets used somewhere, it needs to be
260          * recompiled because it was skipped for compilation before */
261         if(!used) {
262                 need_update = true;
263                 scene->shader_manager->need_update = true;
264         }
265 }
266
267 /* Shader Manager */
268
269 ShaderManager::ShaderManager()
270 {
271         need_update = true;
272         beckmann_table_offset = TABLE_OFFSET_INVALID;
273 }
274
275 ShaderManager::~ShaderManager()
276 {
277 }
278
279 ShaderManager *ShaderManager::create(Scene *scene, int shadingsystem)
280 {
281         ShaderManager *manager;
282
283         (void)shadingsystem;  /* Ignored when built without OSL. */
284
285 #ifdef WITH_OSL
286         if(shadingsystem == SHADINGSYSTEM_OSL)
287                 manager = new OSLShaderManager();
288         else
289 #endif
290                 manager = new SVMShaderManager();
291         
292         add_default(scene);
293
294         return manager;
295 }
296
297 uint ShaderManager::get_attribute_id(ustring name)
298 {
299         /* get a unique id for each name, for SVM attribute lookup */
300         AttributeIDMap::iterator it = unique_attribute_id.find(name);
301
302         if(it != unique_attribute_id.end())
303                 return it->second;
304         
305         uint id = (uint)ATTR_STD_NUM + unique_attribute_id.size();
306         unique_attribute_id[name] = id;
307         return id;
308 }
309
310 uint ShaderManager::get_attribute_id(AttributeStandard std)
311 {
312         return (uint)std;
313 }
314
315 int ShaderManager::get_shader_id(Shader *shader, Mesh *mesh, bool smooth)
316 {
317         /* get a shader id to pass to the kernel */
318         int id = shader->id*2;
319         
320         /* index depends bump since this setting is not in the shader */
321         if(mesh && shader->displacement_method != DISPLACE_TRUE)
322                 id += 1;
323         /* smooth flag */
324         if(smooth)
325                 id |= SHADER_SMOOTH_NORMAL;
326         
327         /* default flags */
328         id |= SHADER_CAST_SHADOW|SHADER_AREA_LIGHT;
329         
330         return id;
331 }
332
333 void ShaderManager::device_update_shaders_used(Scene *scene)
334 {
335         /* figure out which shaders are in use, so SVM/OSL can skip compiling them
336          * for speed and avoid loading image textures into memory */
337         uint id = 0;
338         foreach(Shader *shader, scene->shaders) {
339                 shader->used = false;
340                 shader->id = id++;
341         }
342
343         scene->default_surface->used = true;
344         scene->default_light->used = true;
345         scene->default_background->used = true;
346         scene->default_empty->used = true;
347
348         if(scene->background->shader)
349                 scene->background->shader->used = true;
350
351         foreach(Mesh *mesh, scene->meshes)
352                 foreach(Shader *shader, mesh->used_shaders)
353                         shader->used = true;
354
355         foreach(Light *light, scene->lights)
356                 if(light->shader)
357                         light->shader->used = true;
358 }
359
360 void ShaderManager::device_update_common(Device *device,
361                                          DeviceScene *dscene,
362                                          Scene *scene,
363                                          Progress& /*progress*/)
364 {
365         device->tex_free(dscene->shader_flag);
366         dscene->shader_flag.clear();
367
368         if(scene->shaders.size() == 0)
369                 return;
370
371         uint shader_flag_size = scene->shaders.size()*4;
372         uint *shader_flag = dscene->shader_flag.resize(shader_flag_size);
373         uint i = 0;
374         bool has_volumes = false;
375         bool has_transparent_shadow = false;
376
377         foreach(Shader *shader, scene->shaders) {
378                 uint flag = 0;
379
380                 if(shader->use_mis)
381                         flag |= SD_USE_MIS;
382                 if(shader->has_surface_transparent && shader->use_transparent_shadow)
383                         flag |= SD_HAS_TRANSPARENT_SHADOW;
384                 if(shader->has_volume) {
385                         flag |= SD_HAS_VOLUME;
386                         has_volumes = true;
387
388                         /* in this case we can assume transparent surface */
389                         if(!shader->has_surface)
390                                 flag |= SD_HAS_ONLY_VOLUME;
391
392                         /* todo: this could check more fine grained, to skip useless volumes
393                          * enclosed inside an opaque bsdf.
394                          */
395                         flag |= SD_HAS_TRANSPARENT_SHADOW;
396                 }
397                 if(shader->heterogeneous_volume && shader->has_volume_spatial_varying)
398                         flag |= SD_HETEROGENEOUS_VOLUME;
399                 if(shader->has_bssrdf_bump)
400                         flag |= SD_HAS_BSSRDF_BUMP;
401                 if(shader->volume_sampling_method == VOLUME_SAMPLING_EQUIANGULAR)
402                         flag |= SD_VOLUME_EQUIANGULAR;
403                 if(shader->volume_sampling_method == VOLUME_SAMPLING_MULTIPLE_IMPORTANCE)
404                         flag |= SD_VOLUME_MIS;
405                 if(shader->volume_interpolation_method == VOLUME_INTERPOLATION_CUBIC)
406                         flag |= SD_VOLUME_CUBIC;
407                 if(shader->graph_bump)
408                         flag |= SD_HAS_BUMP;
409
410                 /* regular shader */
411                 shader_flag[i++] = flag;
412                 shader_flag[i++] = shader->pass_id;
413
414                 /* shader with bump mapping */
415                 if(shader->graph_bump)
416                         flag |= SD_HAS_BSSRDF_BUMP;
417
418                 shader_flag[i++] = flag;
419                 shader_flag[i++] = shader->pass_id;
420
421                 has_transparent_shadow |= (flag & SD_HAS_TRANSPARENT_SHADOW) != 0;
422         }
423
424         device->tex_alloc("__shader_flag", dscene->shader_flag);
425
426         /* lookup tables */
427         KernelTables *ktables = &dscene->data.tables;
428
429         /* beckmann lookup table */
430         if(beckmann_table_offset == TABLE_OFFSET_INVALID) {
431                 if(beckmann_table.size() == 0) {
432                         thread_scoped_lock lock(lookup_table_mutex);
433                         if(beckmann_table.size() == 0) {
434                                 beckmann_table_build(beckmann_table);
435                         }
436                 }
437                 beckmann_table_offset = scene->lookup_tables->add_table(dscene, beckmann_table);
438         }
439         ktables->beckmann_offset = (int)beckmann_table_offset;
440
441         /* integrator */
442         KernelIntegrator *kintegrator = &dscene->data.integrator;
443         kintegrator->use_volumes = has_volumes;
444         /* TODO(sergey): De-duplicate with flags set in integrator.cpp. */
445         if(scene->integrator->transparent_shadows) {
446                 kintegrator->transparent_shadows = has_transparent_shadow;
447         }
448 }
449
450 void ShaderManager::device_free_common(Device *device, DeviceScene *dscene, Scene *scene)
451 {
452         scene->lookup_tables->remove_table(&beckmann_table_offset);
453
454         device->tex_free(dscene->shader_flag);
455         dscene->shader_flag.clear();
456 }
457
458 void ShaderManager::add_default(Scene *scene)
459 {
460         /* default surface */
461         {
462                 ShaderGraph *graph = new ShaderGraph();
463
464                 DiffuseBsdfNode *diffuse = new DiffuseBsdfNode();
465                 diffuse->color = make_float3(0.8f, 0.8f, 0.8f);
466                 graph->add(diffuse);
467
468                 graph->connect(diffuse->output("BSDF"), graph->output()->input("Surface"));
469
470                 Shader *shader = new Shader();
471                 shader->name = "default_surface";
472                 shader->graph = graph;
473                 scene->shaders.push_back(shader);
474                 scene->default_surface = shader;
475         }
476
477         /* default light */
478         {
479                 ShaderGraph *graph = new ShaderGraph();
480
481                 EmissionNode *emission = new EmissionNode();
482                 emission->color = make_float3(0.8f, 0.8f, 0.8f);
483                 emission->strength = 0.0f;
484                 graph->add(emission);
485
486                 graph->connect(emission->output("Emission"), graph->output()->input("Surface"));
487
488                 Shader *shader = new Shader();
489                 shader->name = "default_light";
490                 shader->graph = graph;
491                 scene->shaders.push_back(shader);
492                 scene->default_light = shader;
493         }
494
495         /* default background */
496         {
497                 ShaderGraph *graph = new ShaderGraph();
498
499                 Shader *shader = new Shader();
500                 shader->name = "default_background";
501                 shader->graph = graph;
502                 scene->shaders.push_back(shader);
503                 scene->default_background = shader;
504         }
505
506         /* default empty */
507         {
508                 ShaderGraph *graph = new ShaderGraph();
509
510                 Shader *shader = new Shader();
511                 shader->name = "default_empty";
512                 shader->graph = graph;
513                 scene->shaders.push_back(shader);
514                 scene->default_empty = shader;
515         }
516 }
517
518 void ShaderManager::get_requested_graph_features(ShaderGraph *graph,
519                                                  DeviceRequestedFeatures *requested_features)
520 {
521         foreach(ShaderNode *node, graph->nodes) {
522                 requested_features->max_nodes_group = max(requested_features->max_nodes_group,
523                                                           node->get_group());
524                 requested_features->nodes_features |= node->get_feature();
525                 if(node->special_type == SHADER_SPECIAL_TYPE_CLOSURE) {
526                         BsdfNode *bsdf_node = static_cast<BsdfNode*>(node);
527                         if(CLOSURE_IS_VOLUME(bsdf_node->closure)) {
528                                 requested_features->nodes_features |= NODE_FEATURE_VOLUME;
529                         }
530                 }
531                 if(node->has_surface_bssrdf()) {
532                         requested_features->use_subsurface = true;
533                 }
534         }
535 }
536
537 void ShaderManager::get_requested_features(Scene *scene,
538                                            DeviceRequestedFeatures *requested_features)
539 {
540         requested_features->max_nodes_group = NODE_GROUP_LEVEL_0;
541         requested_features->nodes_features = 0;
542         for(int i = 0; i < scene->shaders.size(); i++) {
543                 Shader *shader = scene->shaders[i];
544                 /* Gather requested features from all the nodes from the graph nodes. */
545                 get_requested_graph_features(shader->graph, requested_features);
546                 /* Gather requested features from the graph itself. */
547                 if(shader->graph_bump) {
548                         get_requested_graph_features(shader->graph_bump,
549                                                      requested_features);
550                 }
551                 ShaderNode *output_node = shader->graph->output();
552                 if(output_node->input("Displacement")->link != NULL) {
553                         requested_features->nodes_features |= NODE_FEATURE_BUMP;
554                 }
555                 /* On top of volume nodes, also check if we need volume sampling because
556                  * e.g. an Emission node would slip through the NODE_FEATURE_VOLUME check */
557                 if(shader->has_volume)
558                         requested_features->use_volume |= true;
559         }
560 }
561
562 void ShaderManager::free_memory()
563 {
564         beckmann_table.free_memory();
565 }
566
567 CCL_NAMESPACE_END
568