Python API: add Python-defined node groups for shaders and compositing.
[blender.git] / source / blender / nodes / shader / node_shader_tree.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2007 Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup nodes
22  */
23
24
25 #include <string.h>
26
27 #include "DNA_light_types.h"
28 #include "DNA_material_types.h"
29 #include "DNA_node_types.h"
30 #include "DNA_scene_types.h"
31 #include "DNA_space_types.h"
32 #include "DNA_world_types.h"
33 #include "DNA_linestyle_types.h"
34 #include "DNA_workspace_types.h"
35
36 #include "BLI_listbase.h"
37 #include "BLI_threads.h"
38 #include "BLI_utildefines.h"
39 #include "BLI_alloca.h"
40
41 #include "BLT_translation.h"
42
43 #include "BKE_context.h"
44 #include "BKE_linestyle.h"
45 #include "BKE_node.h"
46 #include "BKE_scene.h"
47
48 #include "RNA_access.h"
49
50 #include "GPU_material.h"
51
52 #include "RE_shader_ext.h"
53
54 #include "NOD_common.h"
55
56 #include "node_common.h"
57 #include "node_exec.h"
58 #include "node_util.h"
59 #include "node_shader_util.h"
60
61
62 typedef struct nTreeTags {
63         float ssr_id, sss_id;
64 } nTreeTags;
65
66 static void ntree_shader_tag_nodes(bNodeTree *ntree, bNode *output_node, nTreeTags *tags);
67
68 static bool shader_tree_poll(const bContext *C, bNodeTreeType *UNUSED(treetype))
69 {
70         Scene *scene = CTX_data_scene(C);
71         const char *engine_id = scene->r.engine;
72
73         /* allow empty engine string too, this is from older versions that didn't have registerable engines yet */
74         return (engine_id[0] == '\0' ||
75                 STREQ(engine_id, RE_engine_id_CYCLES) ||
76                 !BKE_scene_use_shading_nodes_custom(scene));
77 }
78
79 static void shader_get_from_context(const bContext *C, bNodeTreeType *UNUSED(treetype), bNodeTree **r_ntree, ID **r_id, ID **r_from)
80 {
81         SpaceNode *snode = CTX_wm_space_node(C);
82         Scene *scene = CTX_data_scene(C);
83         ViewLayer *view_layer = CTX_data_view_layer(C);
84         Object *ob = OBACT(view_layer);
85
86         if (snode->shaderfrom == SNODE_SHADER_OBJECT) {
87                 if (ob) {
88                         *r_from = &ob->id;
89                         if (ob->type == OB_LAMP) {
90                                 *r_id = ob->data;
91                                 *r_ntree = ((Light *)ob->data)->nodetree;
92                         }
93                         else {
94                                 Material *ma = give_current_material(ob, ob->actcol);
95                                 if (ma) {
96                                         *r_id = &ma->id;
97                                         *r_ntree = ma->nodetree;
98                                 }
99                         }
100                 }
101         }
102 #ifdef WITH_FREESTYLE
103         else if (snode->shaderfrom == SNODE_SHADER_LINESTYLE) {
104                 FreestyleLineStyle *linestyle = BKE_linestyle_active_from_view_layer(view_layer);
105                 if (linestyle) {
106                         *r_from = NULL;
107                         *r_id = &linestyle->id;
108                         *r_ntree = linestyle->nodetree;
109                 }
110         }
111 #endif
112         else { /* SNODE_SHADER_WORLD */
113                 if (scene->world) {
114                         *r_from = NULL;
115                         *r_id = &scene->world->id;
116                         *r_ntree = scene->world->nodetree;
117                 }
118         }
119 }
120
121 static void foreach_nodeclass(Scene *UNUSED(scene), void *calldata, bNodeClassCallback func)
122 {
123         func(calldata, NODE_CLASS_INPUT, N_("Input"));
124         func(calldata, NODE_CLASS_OUTPUT, N_("Output"));
125         func(calldata, NODE_CLASS_SHADER, N_("Shader"));
126         func(calldata, NODE_CLASS_TEXTURE, N_("Texture"));
127         func(calldata, NODE_CLASS_OP_COLOR, N_("Color"));
128         func(calldata, NODE_CLASS_OP_VECTOR, N_("Vector"));
129         func(calldata, NODE_CLASS_CONVERTOR, N_("Convertor"));
130         func(calldata, NODE_CLASS_SCRIPT, N_("Script"));
131         func(calldata, NODE_CLASS_GROUP, N_("Group"));
132         func(calldata, NODE_CLASS_INTERFACE, N_("Interface"));
133         func(calldata, NODE_CLASS_LAYOUT, N_("Layout"));
134 }
135
136 static void localize(bNodeTree *localtree, bNodeTree *UNUSED(ntree))
137 {
138         bNode *node, *node_next;
139
140         /* replace muted nodes and reroute nodes by internal links */
141         for (node = localtree->nodes.first; node; node = node_next) {
142                 node_next = node->next;
143
144                 if (node->flag & NODE_MUTED || node->type == NODE_REROUTE) {
145                         nodeInternalRelink(localtree, node);
146                         ntreeFreeLocalNode(localtree, node);
147                 }
148         }
149 }
150
151 static void local_sync(bNodeTree *localtree, bNodeTree *ntree)
152 {
153         BKE_node_preview_sync_tree(ntree, localtree);
154 }
155
156 static void local_merge(Main *UNUSED(bmain), bNodeTree *localtree, bNodeTree *ntree)
157 {
158         BKE_node_preview_merge_tree(ntree, localtree, true);
159 }
160
161 static void update(bNodeTree *ntree)
162 {
163         ntreeSetOutput(ntree);
164
165         ntree_update_reroute_nodes(ntree);
166
167         if (ntree->update & NTREE_UPDATE_NODES) {
168                 /* clean up preview cache, in case nodes have been removed */
169                 BKE_node_preview_remove_unused(ntree);
170         }
171 }
172
173 bNodeTreeType *ntreeType_Shader;
174
175 void register_node_tree_type_sh(void)
176 {
177         bNodeTreeType *tt = ntreeType_Shader = MEM_callocN(sizeof(bNodeTreeType), "shader node tree type");
178
179         tt->type = NTREE_SHADER;
180         strcpy(tt->idname, "ShaderNodeTree");
181         strcpy(tt->ui_name, N_("Shader Editor"));
182         tt->ui_icon = 0;    /* defined in drawnode.c */
183         strcpy(tt->ui_description, N_("Shader nodes"));
184
185         tt->foreach_nodeclass = foreach_nodeclass;
186         tt->localize = localize;
187         tt->local_sync = local_sync;
188         tt->local_merge = local_merge;
189         tt->update = update;
190         tt->poll = shader_tree_poll;
191         tt->get_from_context = shader_get_from_context;
192
193         tt->ext.srna = &RNA_ShaderNodeTree;
194
195         ntreeTypeAdd(tt);
196 }
197
198 /* GPU material from shader nodes */
199
200 static void ntree_shader_link_builtin_normal(bNodeTree *ntree,
201                                              bNode *node_from,
202                                              bNodeSocket *socket_from,
203                                              bNode *displacement_node,
204                                              bNodeSocket *displacement_socket);
205
206 static bNodeSocket *ntree_shader_node_find_input(bNode *node,
207                                                  const char *identifier);
208
209 static bNode *ntree_group_output_node(bNodeTree *ntree);
210
211 static bNode *ntree_shader_relink_output_from_group(bNodeTree *ntree,
212                                                     bNode *group_node,
213                                                     bNode *sh_output_node,
214                                                     int target)
215 {
216         int i;
217         bNodeTree *group_ntree = (bNodeTree *)group_node->id;
218
219         int sock_len = BLI_listbase_count(&sh_output_node->inputs);
220         bNodeSocket **group_surface_sockets = BLI_array_alloca(group_surface_sockets, sock_len);
221
222         /* Create output sockets to plug output connection to. */
223         i = 0;
224         for (bNodeSocket *sock = sh_output_node->inputs.first; sock; sock = sock->next, ++i) {
225                 group_surface_sockets[i] =
226                         ntreeAddSocketInterface(group_ntree,
227                                                 SOCK_OUT,
228                                                 sock->typeinfo->idname,
229                                                 sock->name);
230         }
231
232         bNode *group_output_node = ntree_group_output_node(group_ntree);
233
234         /* If no group output node is present, we need to create one. */
235         if (group_output_node == NULL) {
236                 group_output_node = nodeAddStaticNode(NULL, group_ntree, NODE_GROUP_OUTPUT);
237         }
238
239         /* Need to update tree so all node instances nodes gets proper sockets. */
240         node_group_verify(ntree, group_node, &group_ntree->id);
241         node_group_output_verify(group_ntree, group_output_node, &group_ntree->id);
242         ntreeUpdateTree(G.main, group_ntree);
243
244         /* Remove other shader output nodes so that only the new one can be selected as active. */
245         for (bNode *node = ntree->nodes.first; node; node = node->next) {
246                 if (ELEM(node->type, SH_NODE_OUTPUT_MATERIAL,
247                                      SH_NODE_OUTPUT_WORLD,
248                                      SH_NODE_OUTPUT_LIGHT))
249                 {
250                         ntreeFreeLocalNode(ntree, node);
251                 }
252         }
253
254         /* Create new shader output node outside the group. */
255         bNode *new_output_node = nodeAddStaticNode(NULL, ntree, sh_output_node->type);
256         new_output_node->custom1 = target;
257
258         i = 0;
259         for (bNodeSocket *sock = sh_output_node->inputs.first; sock; sock = sock->next, ++i) {
260                 if (sock->link != NULL) {
261                         /* Link the shader output node incoming link to the group output sockets */
262                         bNodeSocket *group_output_node_surface_input_sock = nodeFindSocket(group_output_node,
263                                                                                            SOCK_IN,
264                                                                                            group_surface_sockets[i]->identifier);
265                         nodeAddLink(group_ntree,
266                                     sock->link->fromnode, sock->link->fromsock,
267                                     group_output_node, group_output_node_surface_input_sock);
268
269                         /* Link the group output sockets to the new shader output node. */
270                         bNodeSocket *group_node_surface_output = nodeFindSocket(group_node,
271                                                                                 SOCK_OUT,
272                                                                                 group_surface_sockets[i]->identifier);
273                         bNodeSocket *output_node_surface_input = ntree_shader_node_find_input(new_output_node, sock->name);
274
275                         nodeAddLink(ntree,
276                                     group_node, group_node_surface_output,
277                                     new_output_node, output_node_surface_input);
278                 }
279         }
280
281         ntreeUpdateTree(G.main, group_ntree);
282         ntreeUpdateTree(G.main, ntree);
283
284         return new_output_node;
285 }
286
287 static bNode *ntree_shader_output_node_from_group(bNodeTree *ntree, int target)
288 {
289         bNode *output_node = NULL;
290
291         /* Search if node groups do not contain valid output nodes (recursively). */
292         for (bNode *node = ntree->nodes.first; node; node = node->next) {
293                 if (!ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP)) {
294                         continue;
295                 }
296                 if (node->id != NULL) {
297                         output_node = ntree_shader_output_node_from_group((bNodeTree *)node->id, target);
298
299                         if (output_node == NULL) {
300                                 output_node = ntreeShaderOutputNode((bNodeTree *)node->id, target);
301                         }
302
303                         if (output_node != NULL) {
304                                 /* Output is inside this group node. Create relink to make the output outside the group. */
305                                 output_node = ntree_shader_relink_output_from_group(ntree, node, output_node, target);
306                                 break;
307                         }
308                 }
309         }
310         return output_node;
311 }
312
313 /* Find an output node of the shader tree.
314  *
315  * NOTE: it will only return output which is NOT in the group, which isn't how
316  * render engines works but it's how the GPU shader compilation works. This we
317  * can change in the future and make it a generic function, but for now it stays
318  * private here.
319  */
320 bNode *ntreeShaderOutputNode(bNodeTree *ntree, int target)
321 {
322         /* Make sure we only have single node tagged as output. */
323         ntreeSetOutput(ntree);
324
325         /* Find output node that matches type and target. If there are
326          * multiple, we prefer exact target match and active nodes. */
327         bNode *output_node = NULL;
328
329         for (bNode *node = ntree->nodes.first; node; node = node->next) {
330                 if (!ELEM(node->type, SH_NODE_OUTPUT_MATERIAL,
331                                       SH_NODE_OUTPUT_WORLD,
332                                       SH_NODE_OUTPUT_LIGHT))
333                 {
334                         continue;
335                 }
336
337                 if (node->custom1 == SHD_OUTPUT_ALL) {
338                         if (output_node == NULL) {
339                                 output_node = node;
340                         }
341                         else if (output_node->custom1 == SHD_OUTPUT_ALL) {
342                                 if ((node->flag & NODE_DO_OUTPUT) &&
343                                     !(output_node->flag & NODE_DO_OUTPUT))
344                                 {
345                                         output_node = node;
346                                 }
347                         }
348                 }
349                 else if (node->custom1 == target) {
350                         if (output_node == NULL) {
351                                 output_node = node;
352                         }
353                         else if (output_node->custom1 == SHD_OUTPUT_ALL) {
354                                 output_node = node;
355                         }
356                         else if ((node->flag & NODE_DO_OUTPUT) &&
357                                  !(output_node->flag & NODE_DO_OUTPUT))
358                         {
359                                 output_node = node;
360                         }
361                 }
362         }
363
364         return output_node;
365 }
366
367 /* Find the active output node of a group nodetree.
368  *
369  * Does not return the shading output node but the group output node.
370  */
371 static bNode *ntree_group_output_node(bNodeTree *ntree)
372 {
373         /* Make sure we only have single node tagged as output. */
374         ntreeSetOutput(ntree);
375
376         /* Find output node that matches type and target. If there are
377          * multiple, we prefer exact target match and active nodes. */
378         bNode *output_node = NULL;
379
380         for (bNode *node = ntree->nodes.first; node; node = node->next) {
381                 if ((node->type == NODE_GROUP_OUTPUT) &&
382                     (node->flag & NODE_DO_OUTPUT))
383                 {
384                         output_node = node;
385                 }
386         }
387
388         return output_node;
389 }
390
391 /* Find socket with a specified identifier. */
392 static bNodeSocket *ntree_shader_node_find_socket(ListBase *sockets,
393                                                   const char *identifier)
394 {
395         for (bNodeSocket *sock = sockets->first; sock != NULL; sock = sock->next) {
396                 if (STREQ(sock->identifier, identifier)) {
397                         return sock;
398                 }
399         }
400         return NULL;
401 }
402
403 /* Find input socket with a specified identifier. */
404 static bNodeSocket *ntree_shader_node_find_input(bNode *node,
405                                                  const char *identifier)
406 {
407         return ntree_shader_node_find_socket(&node->inputs, identifier);
408 }
409
410 /* Find output socket with a specified identifier. */
411 static bNodeSocket *ntree_shader_node_find_output(bNode *node,
412                                                   const char *identifier)
413 {
414         return ntree_shader_node_find_socket(&node->outputs, identifier);
415 }
416
417 static void ntree_shader_unlink_hidden_value_sockets(bNode *group_node, bNodeSocket *isock)
418 {
419         bNodeTree *group_ntree = (bNodeTree *)group_node->id;
420         bNode *node;
421         bool removed_link = false;
422
423         for (node = group_ntree->nodes.first; node; node = node->next) {
424                 for (bNodeSocket *sock = node->inputs.first; sock; sock = sock->next) {
425                         if ((sock->flag & SOCK_HIDE_VALUE) == 0)
426                                 continue;
427                         /* If socket is linked to a group input node and sockets id match. */
428                         if (sock && sock->link && sock->link->fromnode->type == NODE_GROUP_INPUT) {
429                                 if (STREQ(isock->identifier, sock->link->fromsock->identifier)) {
430                                         nodeRemLink(group_ntree, sock->link);
431                                         removed_link = true;
432                                 }
433                         }
434                 }
435         }
436
437         if (removed_link) {
438                 ntreeUpdateTree(G.main, group_ntree);
439         }
440 }
441
442 /* Node groups once expanded looses their input sockets values.
443  * To fix this, link value/rgba nodes into the sockets and copy the group sockets values. */
444 static void ntree_shader_groups_expand_inputs(bNodeTree *localtree)
445 {
446         bNode *value_node, *group_node;
447         bNodeSocket *value_socket;
448         bNodeSocketValueVector *src_vector;
449         bNodeSocketValueRGBA *src_rgba, *dst_rgba;
450         bNodeSocketValueFloat *src_float, *dst_float;
451         bNodeSocketValueInt *src_int;
452         bool link_added = false;
453
454         for (group_node = localtree->nodes.first; group_node; group_node = group_node->next) {
455
456                 if (!(ELEM(group_node->type, NODE_GROUP, NODE_CUSTOM_GROUP)) || group_node->id == NULL)
457                         continue;
458
459                 /* Do it recursively. */
460                 ntree_shader_groups_expand_inputs((bNodeTree *)group_node->id);
461
462                 bNodeSocket *group_socket = group_node->inputs.first;
463                 for (; group_socket; group_socket = group_socket->next) {
464                         if (group_socket->link != NULL)
465                                 continue;
466
467                         /* Detect the case where an input is plugged into a hidden value socket.
468                          * In this case we should just remove the link to trigger the socket default override. */
469                         ntree_shader_unlink_hidden_value_sockets(group_node, group_socket);
470
471                         switch (group_socket->type) {
472                                 case SOCK_VECTOR:
473                                         value_node = nodeAddStaticNode(NULL, localtree, SH_NODE_RGB);
474                                         value_socket = ntree_shader_node_find_output(value_node, "Color");
475                                         BLI_assert(value_socket != NULL);
476                                         src_vector = group_socket->default_value;
477                                         dst_rgba = value_socket->default_value;
478                                         copy_v3_v3(dst_rgba->value, src_vector->value);
479                                         dst_rgba->value[3] = 1.0f; /* should never be read */
480                                         break;
481                                 case SOCK_RGBA:
482                                         value_node = nodeAddStaticNode(NULL, localtree, SH_NODE_RGB);
483                                         value_socket = ntree_shader_node_find_output(value_node, "Color");
484                                         BLI_assert(value_socket != NULL);
485                                         src_rgba = group_socket->default_value;
486                                         dst_rgba = value_socket->default_value;
487                                         copy_v4_v4(dst_rgba->value, src_rgba->value);
488                                         break;
489                                 case SOCK_INT:
490                                         /* HACK: Support as float. */
491                                         value_node = nodeAddStaticNode(NULL, localtree, SH_NODE_VALUE);
492                                         value_socket = ntree_shader_node_find_output(value_node, "Value");
493                                         BLI_assert(value_socket != NULL);
494                                         src_int = group_socket->default_value;
495                                         dst_float = value_socket->default_value;
496                                         dst_float->value = (float)(src_int->value);
497                                         break;
498                                 case SOCK_FLOAT:
499                                         value_node = nodeAddStaticNode(NULL, localtree, SH_NODE_VALUE);
500                                         value_socket = ntree_shader_node_find_output(value_node, "Value");
501                                         BLI_assert(value_socket != NULL);
502                                         src_float = group_socket->default_value;
503                                         dst_float = value_socket->default_value;
504                                         dst_float->value = src_float->value;
505                                         break;
506                                 default:
507                                         continue;
508                         }
509
510                         nodeAddLink(localtree,
511                                     value_node, value_socket,
512                                     group_node, group_socket);
513
514                         link_added = true;
515                 }
516         }
517
518         if (link_added) {
519                 ntreeUpdateTree(G.main, localtree);
520         }
521 }
522
523 /* Check whether shader has a displacement.
524  *
525  * Will also return a node and it's socket which is connected to a displacement
526  * output. Additionally, link which is attached to the displacement output is
527  * also returned.
528  */
529 static bool ntree_shader_has_displacement(bNodeTree *ntree,
530                                           bNode *output_node,
531                                           bNode **r_node,
532                                           bNodeSocket **r_socket,
533                                           bNodeLink **r_link)
534 {
535         if (output_node == NULL) {
536                 /* We can't have displacement without output node, apparently. */
537                 return false;
538         }
539         /* Make sure sockets links pointers are correct. */
540         ntreeUpdateTree(G.main, ntree);
541         bNodeSocket *displacement = ntree_shader_node_find_input(output_node,
542                                                                  "Displacement");
543
544         if (displacement == NULL) {
545                 /* Non-cycles node is used as an output. */
546                 return false;
547         }
548         if (displacement->link != NULL) {
549                 *r_node = displacement->link->fromnode;
550                 *r_socket = displacement->link->fromsock;
551                 *r_link = displacement->link;
552         }
553         return displacement->link != NULL;
554 }
555
556 static bool ntree_shader_relink_node_normal(bNodeTree *ntree,
557                                             bNode *node,
558                                             bNode *node_from,
559                                             bNodeSocket *socket_from)
560 {
561         bNodeSocket *sock = ntree_shader_node_find_input(node, "Normal");
562         /* TODO(sergey): Can we do something smarter here than just a name-based
563          * matching?
564          */
565         if (sock == NULL) {
566                 /* There's no Normal input, nothing to link. */
567                 return false;
568         }
569         if (sock->link != NULL) {
570                 /* Something is linked to the normal input already. can't
571                  * use other input for that.
572                  */
573                 return false;
574         }
575         /* Create connection between specified node and the normal input. */
576         nodeAddLink(ntree, node_from, socket_from, node, sock);
577         return true;
578 }
579
580 static void ntree_shader_link_builtin_group_normal(
581         bNodeTree *ntree,
582         bNode *group_node,
583         bNode *node_from,
584         bNodeSocket *socket_from,
585         bNode *displacement_node,
586         bNodeSocket *displacement_socket)
587 {
588         bNodeTree *group_ntree = (bNodeTree *)group_node->id;
589         /* Create input socket to plug displacement connection to. */
590         bNodeSocket *group_normal_socket =
591                 ntreeAddSocketInterface(group_ntree,
592                                         SOCK_IN,
593                                         "NodeSocketVector",
594                                         "Normal");
595         /* Need to update tree so all node instances nodes gets proper sockets. */
596         bNode *group_input_node = ntreeFindType(group_ntree, NODE_GROUP_INPUT);
597         node_group_verify(ntree, group_node, &group_ntree->id);
598         if (group_input_node)
599                 node_group_input_verify(group_ntree, group_input_node, &group_ntree->id);
600         ntreeUpdateTree(G.main, group_ntree);
601         /* Assumes sockets are always added at the end. */
602         bNodeSocket *group_node_normal_socket = group_node->inputs.last;
603         if (displacement_node == group_node) {
604                 /* If displacement is coming from this node group we need to perform
605                  * some internal re-linking in order to avoid cycles.
606                  */
607                 bNode *group_output_node = ntreeFindType(group_ntree, NODE_GROUP_OUTPUT);
608                 if (group_output_node == NULL) {
609                         return;
610                 }
611                 bNodeSocket *group_output_node_displacement_socket =
612                         nodeFindSocket(group_output_node,
613                                        SOCK_IN,
614                                        displacement_socket->identifier);
615                 bNodeLink *group_displacement_link = group_output_node_displacement_socket->link;
616                 if (group_displacement_link == NULL) {
617                         /* Displacement output is not connected to anything, can just stop
618                          * right away.
619                          */
620                         return;
621                 }
622                 /* This code is similar to ntree_shader_relink_displacement() */
623                 bNode *group_displacement_node = group_displacement_link->fromnode;
624                 bNodeSocket *group_displacement_socket = group_displacement_link->fromsock;
625                 /* Create and link bump node.
626                  * Can't re-use bump node from parent tree because it'll cause cycle.
627                  */
628                 bNode *bump_node = nodeAddStaticNode(NULL, group_ntree, SH_NODE_BUMP);
629                 bNodeSocket *bump_input_socket = ntree_shader_node_find_input(bump_node, "Height");
630                 bNodeSocket *bump_output_socket = ntree_shader_node_find_output(bump_node, "Normal");
631                 BLI_assert(bump_input_socket != NULL);
632                 BLI_assert(bump_output_socket != NULL);
633                 nodeAddLink(group_ntree,
634                             group_displacement_node, group_displacement_socket,
635                             bump_node, bump_input_socket);
636                 /* Relink normals inside of the instanced tree. */
637                 ntree_shader_link_builtin_normal(group_ntree,
638                                                  bump_node,
639                                                  bump_output_socket,
640                                                  group_displacement_node,
641                                                  group_displacement_socket);
642                 ntreeUpdateTree(G.main, group_ntree);
643         }
644         else if (group_input_node) {
645                 /* Connect group node normal input. */
646                 nodeAddLink(ntree,
647                             node_from, socket_from,
648                             group_node, group_node_normal_socket);
649                 BLI_assert(group_input_node != NULL);
650                 bNodeSocket *group_input_node_normal_socket =
651                         nodeFindSocket(group_input_node,
652                                        SOCK_OUT,
653                                        group_normal_socket->identifier);
654                 BLI_assert(group_input_node_normal_socket != NULL);
655                 /* Relink normals inside of the instanced tree. */
656                 ntree_shader_link_builtin_normal(group_ntree,
657                                                  group_input_node,
658                                                  group_input_node_normal_socket,
659                                                  displacement_node,
660                                                  displacement_socket);
661                 ntreeUpdateTree(G.main, group_ntree);
662         }
663 }
664
665 /* Use specified node and socket as an input for unconnected normal sockets. */
666 static void ntree_shader_link_builtin_normal(bNodeTree *ntree,
667                                              bNode *node_from,
668                                              bNodeSocket *socket_from,
669                                              bNode *displacement_node,
670                                              bNodeSocket *displacement_socket)
671 {
672         for (bNode *node = ntree->nodes.first; node != NULL; node = node->next) {
673                 if (node == node_from) {
674                         /* Don't connect node itself! */
675                         continue;
676                 }
677                 if ((ELEM(node->type, NODE_GROUP, NODE_CUSTOM_GROUP)) && node->id) {
678                         /* Special re-linking for group nodes. */
679                         ntree_shader_link_builtin_group_normal(ntree,
680                                                                node,
681                                                                node_from,
682                                                                socket_from,
683                                                                displacement_node,
684                                                                displacement_socket);
685                         continue;
686                 }
687                 if (ELEM(node->type, NODE_GROUP_INPUT, NODE_GROUP_OUTPUT)) {
688                         /* Group inputs and outputs needs nothing special. */
689                         continue;
690                 }
691                 ntree_shader_relink_node_normal(ntree, node, node_from, socket_from);
692         }
693 }
694
695 /* Re-link displacement output to unconnected normal sockets via bump node.
696  * This way material with have proper displacement in the viewport.
697  */
698 static void ntree_shader_relink_displacement(bNodeTree *ntree, bNode *output_node)
699 {
700         bNode *displacement_node;
701         bNodeSocket *displacement_socket;
702         bNodeLink *displacement_link;
703         if (!ntree_shader_has_displacement(ntree,
704                                            output_node,
705                                            &displacement_node,
706                                            &displacement_socket,
707                                            &displacement_link))
708         {
709                 /* There is no displacement output connected, nothing to re-link. */
710                 return;
711         }
712         /* We have to disconnect displacement output socket, otherwise we'll have
713          * cycles in the Cycles material :)
714          */
715         nodeRemLink(ntree, displacement_link);
716
717         /* Convert displacement vector to bump height. */
718         bNode *dot_node = nodeAddStaticNode(NULL, ntree, SH_NODE_VECT_MATH);
719         bNode *geo_node = nodeAddStaticNode(NULL, ntree, SH_NODE_NEW_GEOMETRY);
720         dot_node->custom1 = 3; /* dot product */
721
722         nodeAddLink(ntree,
723                     displacement_node, displacement_socket,
724                     dot_node, dot_node->inputs.first);
725         nodeAddLink(ntree,
726                     geo_node, ntree_shader_node_find_output(geo_node, "Normal"),
727                     dot_node, dot_node->inputs.last);
728         displacement_node = dot_node;
729         displacement_socket = ntree_shader_node_find_output(dot_node, "Value");
730
731         /* We can't connect displacement to normal directly, use bump node for that
732          * and hope that it gives good enough approximation.
733          */
734         bNode *bump_node = nodeAddStaticNode(NULL, ntree, SH_NODE_BUMP);
735         bNodeSocket *bump_input_socket = ntree_shader_node_find_input(bump_node, "Height");
736         bNodeSocket *bump_output_socket = ntree_shader_node_find_output(bump_node, "Normal");
737         BLI_assert(bump_input_socket != NULL);
738         BLI_assert(bump_output_socket != NULL);
739         /* Connect bump node to where displacement output was originally
740          * connected to.
741          */
742         nodeAddLink(ntree,
743                     displacement_node, displacement_socket,
744                     bump_node, bump_input_socket);
745         /* Connect all free-standing Normal inputs. */
746         ntree_shader_link_builtin_normal(ntree,
747                                          bump_node,
748                                          bump_output_socket,
749                                          displacement_node,
750                                          displacement_socket);
751         /* TODO(sergey): Reconnect Geometry Info->Normal sockets to the new
752          * bump node.
753          */
754         /* We modified the tree, it needs to be updated now. */
755         ntreeUpdateTree(G.main, ntree);
756 }
757
758 static bool ntree_tag_bsdf_cb(bNode *fromnode, bNode *UNUSED(tonode), void *userdata, const bool UNUSED(reversed))
759 {
760         /* Don't evaluate nodes more than once. */
761         if (fromnode->tmp_flag) {
762                 return true;
763         }
764         fromnode->tmp_flag = 1;
765
766         switch (fromnode->type) {
767                 case NODE_GROUP:
768                 case NODE_CUSTOM_GROUP:
769                         /* Recursive */
770                         if (fromnode->id != NULL) {
771                                 bNodeTree *ntree = (bNodeTree *)fromnode->id;
772                                 bNode *group_output = ntree_group_output_node(ntree);
773                                 ntree_shader_tag_nodes(ntree, group_output, (nTreeTags *)userdata);
774                         }
775                         break;
776                 case SH_NODE_BSDF_ANISOTROPIC:
777                 case SH_NODE_EEVEE_SPECULAR:
778                 case SH_NODE_BSDF_GLOSSY:
779                 case SH_NODE_BSDF_GLASS:
780                         fromnode->ssr_id = ((nTreeTags *)userdata)->ssr_id;
781                         ((nTreeTags *)userdata)->ssr_id += 1;
782                         break;
783                 case SH_NODE_SUBSURFACE_SCATTERING:
784                         fromnode->sss_id = ((nTreeTags *)userdata)->sss_id;
785                         ((nTreeTags *)userdata)->sss_id += 1;
786                         break;
787                 case SH_NODE_BSDF_PRINCIPLED:
788                         fromnode->ssr_id = ((nTreeTags *)userdata)->ssr_id;
789                         fromnode->sss_id = ((nTreeTags *)userdata)->sss_id;
790                         ((nTreeTags *)userdata)->sss_id += 1;
791                         ((nTreeTags *)userdata)->ssr_id += 1;
792                         break;
793                 default:
794                         /* We could return false here but since we
795                          * allow the use of Closure as RGBA, we can have
796                          * Bsdf nodes linked to other Bsdf nodes. */
797                         break;
798         }
799
800         return true;
801 }
802
803 /* EEVEE: Scan the ntree to set the Screen Space Reflection
804  * layer id of every specular node AND the Subsurface Scattering id of every SSS node.
805  */
806 void ntree_shader_tag_nodes(bNodeTree *ntree, bNode *output_node, nTreeTags *tags)
807 {
808         if (output_node == NULL) {
809                 return;
810         }
811         /* Make sure sockets links pointers are correct. */
812         ntreeUpdateTree(G.main, ntree);
813
814         /* Reset visit flag. */
815         for (bNode *node = ntree->nodes.first; node; node = node->next) {
816                 node->tmp_flag = 0;
817         }
818
819         nodeChainIter(ntree, output_node, ntree_tag_bsdf_cb, tags, true);
820 }
821
822 /* This one needs to work on a local tree. */
823 void ntreeGPUMaterialNodes(bNodeTree *localtree, GPUMaterial *mat, bool *has_surface_output, bool *has_volume_output)
824 {
825         bNodeTreeExec *exec;
826
827         /* Extract output nodes from inside nodegroups. */
828         ntree_shader_output_node_from_group(localtree, SHD_OUTPUT_EEVEE);
829
830         bNode *output = ntreeShaderOutputNode(localtree, SHD_OUTPUT_EEVEE);
831
832         ntree_shader_groups_expand_inputs(localtree);
833
834         /* Perform all needed modifications on the tree in order to support
835          * displacement/bump mapping.
836          */
837         ntree_shader_relink_displacement(localtree, output);
838
839         /* TODO(fclem): consider moving this to the gpu shader tree evaluation. */
840         nTreeTags tags = {
841                 .ssr_id = 1.0,
842                 .sss_id = 1.0,
843         };
844         ntree_shader_tag_nodes(localtree, output, &tags);
845
846         exec = ntreeShaderBeginExecTree(localtree);
847         ntreeExecGPUNodes(exec, mat, 1);
848         ntreeShaderEndExecTree(exec);
849
850         /* EEVEE: Find which material domain was used (volume, surface ...). */
851         *has_surface_output = false;
852         *has_volume_output = false;
853
854         if (output != NULL) {
855                 bNodeSocket *surface_sock = ntree_shader_node_find_input(output, "Surface");
856                 bNodeSocket *volume_sock = ntree_shader_node_find_input(output, "Volume");
857
858                 if (surface_sock != NULL) {
859                         *has_surface_output = (nodeCountSocketLinks(localtree, surface_sock) > 0);
860                 }
861
862                 if (volume_sock != NULL) {
863                         *has_volume_output = (nodeCountSocketLinks(localtree, volume_sock) > 0);
864                 }
865         }
866 }
867
868 bNodeTreeExec *ntreeShaderBeginExecTree_internal(bNodeExecContext *context, bNodeTree *ntree, bNodeInstanceKey parent_key)
869 {
870         bNodeTreeExec *exec;
871         bNode *node;
872
873         /* ensures only a single output node is enabled */
874         ntreeSetOutput(ntree);
875
876         /* common base initialization */
877         exec = ntree_exec_begin(context, ntree, parent_key);
878
879         /* allocate the thread stack listbase array */
880         exec->threadstack = MEM_callocN(BLENDER_MAX_THREADS * sizeof(ListBase), "thread stack array");
881
882         for (node = exec->nodetree->nodes.first; node; node = node->next)
883                 node->need_exec = 1;
884
885         return exec;
886 }
887
888 bNodeTreeExec *ntreeShaderBeginExecTree(bNodeTree *ntree)
889 {
890         bNodeExecContext context;
891         bNodeTreeExec *exec;
892
893         /* XXX hack: prevent exec data from being generated twice.
894          * this should be handled by the renderer!
895          */
896         if (ntree->execdata)
897                 return ntree->execdata;
898
899         context.previews = ntree->previews;
900
901         exec = ntreeShaderBeginExecTree_internal(&context, ntree, NODE_INSTANCE_KEY_BASE);
902
903         /* XXX this should not be necessary, but is still used for cmp/sha/tex nodes,
904          * which only store the ntree pointer. Should be fixed at some point!
905          */
906         ntree->execdata = exec;
907
908         return exec;
909 }
910
911 void ntreeShaderEndExecTree_internal(bNodeTreeExec *exec)
912 {
913         bNodeThreadStack *nts;
914         int a;
915
916         if (exec->threadstack) {
917                 for (a = 0; a < BLENDER_MAX_THREADS; a++) {
918                         for (nts = exec->threadstack[a].first; nts; nts = nts->next)
919                                 if (nts->stack) MEM_freeN(nts->stack);
920                         BLI_freelistN(&exec->threadstack[a]);
921                 }
922
923                 MEM_freeN(exec->threadstack);
924                 exec->threadstack = NULL;
925         }
926
927         ntree_exec_end(exec);
928 }
929
930 void ntreeShaderEndExecTree(bNodeTreeExec *exec)
931 {
932         if (exec) {
933                 /* exec may get freed, so assign ntree */
934                 bNodeTree *ntree = exec->nodetree;
935                 ntreeShaderEndExecTree_internal(exec);
936
937                 /* XXX clear nodetree backpointer to exec data, same problem as noted in ntreeBeginExecTree */
938                 ntree->execdata = NULL;
939         }
940 }
941
942 /* TODO: left over from Blender Internal, could reuse for new texture nodes. */
943 bool ntreeShaderExecTree(bNodeTree *ntree, int thread)
944 {
945         ShaderCallData scd;
946         bNodeThreadStack *nts = NULL;
947         bNodeTreeExec *exec = ntree->execdata;
948         int compat;
949
950         /* ensure execdata is only initialized once */
951         if (!exec) {
952                 BLI_thread_lock(LOCK_NODES);
953                 if (!ntree->execdata)
954                         ntree->execdata = ntreeShaderBeginExecTree(ntree);
955                 BLI_thread_unlock(LOCK_NODES);
956
957                 exec = ntree->execdata;
958         }
959
960         nts = ntreeGetThreadStack(exec, thread);
961         compat = ntreeExecThreadNodes(exec, nts, &scd, thread);
962         ntreeReleaseThreadStack(nts);
963
964         /* if compat is zero, it has been using non-compatible nodes */
965         return compat;
966 }