svn merge ^/trunk/blender -r41226:41227 .
[blender.git] / source / blender / blenkernel / intern / node.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Bob Holcomb.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/node.c
29  *  \ingroup bke
30  */
31
32
33 #if 0 /* pynodes commented for now */
34 #  ifdef WITH_PYTHON
35 #    include <Python.h>
36 #  endif
37 #endif
38
39 #include "MEM_guardedalloc.h"
40
41 #include <stdlib.h>
42 #include <stddef.h>
43 #include <string.h>
44 #include <limits.h>
45
46 #include "DNA_anim_types.h"
47 #include "DNA_node_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_action_types.h"
50
51 #include "BLI_string.h"
52 #include "BLI_math.h"
53 #include "BLI_listbase.h"
54 #include "BLI_path_util.h"
55 #include "BLI_utildefines.h"
56
57 #include "BKE_animsys.h"
58 #include "BKE_action.h"
59 #include "BKE_fcurve.h"
60 #include "BKE_global.h"
61 #include "BKE_image.h"
62 #include "BKE_library.h"
63 #include "BKE_main.h"
64 #include "BKE_node.h"
65 #include "BKE_utildefines.h"
66 #include "BKE_utildefines.h"
67
68 #include "BLI_listbase.h"
69
70 #include "RNA_access.h"
71
72 #include "NOD_socket.h"
73 #include "NOD_composite.h"
74 #include "NOD_shader.h"
75 #include "NOD_texture.h"
76
77
78 bNodeTreeType *ntreeGetType(int type)
79 {
80         static bNodeTreeType *types[NUM_NTREE_TYPES];
81         static int types_init = 1;
82         if (types_init) {
83                 types[NTREE_SHADER] = &ntreeType_Shader;
84                 types[NTREE_COMPOSIT] = &ntreeType_Composite;
85                 types[NTREE_TEXTURE] = &ntreeType_Texture;
86                 types_init = 0;
87         }
88         
89         if(type >= 0 && type < NUM_NTREE_TYPES) {
90                 return types[type];
91         }
92         else {
93                 return NULL;
94         }
95 }
96
97 static bNodeType *node_get_type(bNodeTree *ntree, int type)
98 {
99         bNodeType *ntype = ntreeGetType(ntree->type)->node_types.first;
100         for(; ntype; ntype= ntype->next)
101                 if(ntype->type==type)
102                         return ntype;
103         
104         return NULL;
105 }
106
107 bNodeType *ntreeGetNodeType(bNodeTree *ntree)
108 {
109         return node_get_type(ntree, ntree->nodetype);
110 }
111
112 bNodeSocketType *ntreeGetSocketType(int type)
113 {
114         static bNodeSocketType *types[NUM_SOCKET_TYPES]= {NULL};
115         static int types_init = 1;
116
117         if (types_init) {
118                 node_socket_type_init(types);
119                 types_init= 0;
120         }
121
122         if(type < NUM_SOCKET_TYPES) {
123                 return types[type];
124         }
125         else {
126                 return NULL;
127         }
128 }
129
130 void ntreeInitTypes(bNodeTree *ntree)
131 {
132         bNode *node, *next;
133         
134         for(node= ntree->nodes.first; node; node= next) {
135                 next= node->next;
136                 
137                 node->typeinfo= node_get_type(ntree, node->type);
138                 
139                 if(node->type==NODE_DYNAMIC) {
140                         /* needed info if the pynode script fails now: */
141                         node->storage= ntree;
142                         if(node->id!=NULL) { /* not an empty script node */
143                                 node->custom1= 0;
144                                 node->custom1= BSET(node->custom1,NODE_DYNAMIC_ADDEXIST);
145                         }
146 //                      if(node->typeinfo)
147 //                              node->typeinfo->initfunc(node);
148                 }
149
150                 if(node->typeinfo==NULL) {
151                         printf("Error: Node type %s doesn't exist anymore, removed\n", node->name);
152                         nodeFreeNode(ntree, node);
153                 }
154         }
155                         
156         ntree->init |= NTREE_TYPE_INIT;
157 }
158
159 static bNodeSocket *make_socket(bNodeTree *UNUSED(ntree), int in_out, const char *name, int type)
160 {
161         bNodeSocketType *stype= ntreeGetSocketType(type);
162         bNodeSocket *sock;
163         
164         sock= MEM_callocN(sizeof(bNodeSocket), "sock");
165         
166         BLI_strncpy(sock->name, name, NODE_MAXSTR);
167         sock->limit = (in_out==SOCK_IN ? 1 : 0xFFF);
168         sock->type= type;
169         sock->storage = NULL;
170         
171         if (stype->value_structsize > 0)
172                 sock->default_value = MEM_callocN(stype->value_structsize, "default socket value");
173         
174         return sock;
175 }
176
177 bNodeSocket *nodeAddSocket(bNodeTree *ntree, bNode *node, int in_out, const char *name, int type)
178 {
179         bNodeSocket *sock = make_socket(ntree, in_out, name, type);
180         if (in_out==SOCK_IN)
181                 BLI_addtail(&node->inputs, sock);
182         else if (in_out==SOCK_OUT)
183                 BLI_addtail(&node->outputs, sock);
184         
185         node->update |= NODE_UPDATE;
186         
187         return sock;
188 }
189
190 bNodeSocket *nodeInsertSocket(bNodeTree *ntree, bNode *node, int in_out, bNodeSocket *next_sock, const char *name, int type)
191 {
192         bNodeSocket *sock = make_socket(ntree, in_out, name, type);
193         if (in_out==SOCK_IN)
194                 BLI_insertlinkbefore(&node->inputs, next_sock, sock);
195         else if (in_out==SOCK_OUT)
196                 BLI_insertlinkbefore(&node->outputs, next_sock, sock);
197         
198         node->update |= NODE_UPDATE;
199         
200         return sock;
201 }
202
203 void nodeRemoveSocket(bNodeTree *ntree, bNode *node, bNodeSocket *sock)
204 {
205         bNodeLink *link, *next;
206         
207         for(link= ntree->links.first; link; link= next) {
208                 next= link->next;
209                 if(link->fromsock==sock || link->tosock==sock) {
210                         nodeRemLink(ntree, link);
211                 }
212         }
213         
214         /* this is fast, this way we don't need an in_out argument */
215         BLI_remlink(&node->inputs, sock);
216         BLI_remlink(&node->outputs, sock);
217         
218         if (sock->default_value)
219                 MEM_freeN(sock->default_value);
220         MEM_freeN(sock);
221         
222         node->update |= NODE_UPDATE;
223 }
224
225 void nodeRemoveAllSockets(bNodeTree *ntree, bNode *node)
226 {
227         bNodeSocket *sock;
228         bNodeLink *link, *next;
229         
230         for(link= ntree->links.first; link; link= next) {
231                 next= link->next;
232                 if(link->fromnode==node || link->tonode==node) {
233                         nodeRemLink(ntree, link);
234                 }
235         }
236         
237         for (sock=node->inputs.first; sock; sock=sock->next)
238                 if (sock->default_value)
239                         MEM_freeN(sock->default_value);
240         BLI_freelistN(&node->inputs);
241         for (sock=node->outputs.first; sock; sock=sock->next)
242                 if (sock->default_value)
243                         MEM_freeN(sock->default_value);
244         
245         BLI_freelistN(&node->outputs);
246         
247         node->update |= NODE_UPDATE;
248 }
249
250 /* finds a node based on its name */
251 bNode *nodeFindNodebyName(bNodeTree *ntree, const char *name)
252 {
253         return BLI_findstring(&ntree->nodes, name, offsetof(bNode, name));
254 }
255
256 /* finds a node based on given socket */
257 int nodeFindNode(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockindex, int *in_out)
258 {
259         bNode *node;
260         bNodeSocket *tsock;
261         int index= 0;
262         
263         for(node= ntree->nodes.first; node; node= node->next) {
264                 for(index=0, tsock= node->inputs.first; tsock; tsock= tsock->next, index++) {
265                         if(tsock==sock) {
266                                 if (in_out) *in_out= SOCK_IN;
267                                 break;
268                         }
269                 }
270                 if(tsock)
271                         break;
272                 for(index=0, tsock= node->outputs.first; tsock; tsock= tsock->next, index++) {
273                         if(tsock==sock) {
274                                 if (in_out) *in_out= SOCK_OUT;
275                                 break;
276                         }
277                 }
278                 if(tsock)
279                         break;
280         }
281
282         if(node) {
283                 *nodep= node;
284                 if(sockindex) *sockindex= index;
285                 return 1;
286         }
287         
288         *nodep= NULL;
289         return 0;
290 }
291
292 /* ************** Add stuff ********** */
293 static void node_add_sockets_from_type(bNodeTree *ntree, bNode *node, bNodeType *ntype)
294 {
295         bNodeSocketTemplate *sockdef;
296         /* bNodeSocket *sock; */ /* UNUSED */
297
298         if(ntype->inputs) {
299                 sockdef= ntype->inputs;
300                 while(sockdef->type != -1) {
301                         /* sock = */ node_add_input_from_template(ntree, node, sockdef);
302                         
303                         sockdef++;
304                 }
305         }
306         if(ntype->outputs) {
307                 sockdef= ntype->outputs;
308                 while(sockdef->type != -1) {
309                         /* sock = */ node_add_output_from_template(ntree, node, sockdef);
310                         
311                         sockdef++;
312                 }
313         }
314 }
315
316 /* Find the first available, non-duplicate name for a given node */
317 void nodeUniqueName(bNodeTree *ntree, bNode *node)
318 {
319         BLI_uniquename(&ntree->nodes, node, "Node", '.', offsetof(bNode, name), sizeof(node->name));
320 }
321
322 bNode *nodeAddNode(bNodeTree *ntree, struct bNodeTemplate *ntemp)
323 {
324         bNode *node;
325         bNodeType *ntype;
326         
327         ntype= node_get_type(ntree, ntemp->type);
328         if(ntype == NULL) {
329                 printf("nodeAddNodeType() error: '%d' type invalid\n", ntemp->type);
330                 return NULL;
331         }
332         /* validity check */
333         if (!nodeValid(ntree, ntemp))
334                 return NULL;
335         
336         node= MEM_callocN(sizeof(bNode), "new node");
337         node->type= ntype->type;
338         node->typeinfo= ntype;
339         node->flag= NODE_SELECT|ntype->flag;
340         node->width= ntype->width;
341         node->miniwidth= 42.0f;
342         node->height= ntype->height;
343         
344         node_add_sockets_from_type(ntree, node, ntype);
345         
346         if(ntype->initfunc!=NULL)
347                 ntype->initfunc(ntree, node, ntemp);
348         
349         /* initialize the node name with the node label */
350         BLI_strncpy(node->name, nodeLabel(node), NODE_MAXSTR);
351         nodeUniqueName(ntree, node);
352         
353         BLI_addtail(&ntree->nodes, node);
354         
355         ntree->update |= NTREE_UPDATE_NODES;
356         
357         return node;
358 }
359
360 void nodeMakeDynamicType(bNode *node)
361 {
362         /* find SH_DYNAMIC_NODE ntype */
363         bNodeType *ntype= ntreeGetType(NTREE_SHADER)->node_types.first;
364         while(ntype) {
365                 if(ntype->type==NODE_DYNAMIC)
366                         break;
367                 ntype= ntype->next;
368         }
369
370         /* make own type struct to fill */
371         if(ntype) {
372                 /*node->typeinfo= MEM_dupallocN(ntype);*/
373                 bNodeType *newtype= MEM_callocN(sizeof(bNodeType), "dynamic bNodeType");
374                 *newtype= *ntype;
375                 BLI_strncpy(newtype->name, ntype->name, sizeof(newtype->name));
376                 node->typeinfo= newtype;
377         }
378 }
379
380 /* keep socket listorder identical, for copying links */
381 /* ntree is the target tree */
382 bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node)
383 {
384         bNode *nnode= MEM_callocN(sizeof(bNode), "dupli node");
385         bNodeSocket *sock, *oldsock;
386
387         *nnode= *node;
388         nodeUniqueName(ntree, nnode);
389         
390         BLI_addtail(&ntree->nodes, nnode);
391
392         BLI_duplicatelist(&nnode->inputs, &node->inputs);
393         oldsock= node->inputs.first;
394         for(sock= nnode->inputs.first; sock; sock= sock->next, oldsock= oldsock->next) {
395                 oldsock->new_sock= sock;
396                 sock->stack_index= 0;
397                 
398                 sock->default_value = (oldsock->default_value ? MEM_dupallocN(oldsock->default_value) : NULL);
399                 
400                 /* XXX some compositor node (e.g. image, render layers) still store
401                  * some persistent buffer data here, need to clear this to avoid dangling pointers.
402                  */
403                 sock->cache = NULL;
404         }
405         
406         BLI_duplicatelist(&nnode->outputs, &node->outputs);
407         oldsock= node->outputs.first;
408         for(sock= nnode->outputs.first; sock; sock= sock->next, oldsock= oldsock->next) {
409                 oldsock->new_sock= sock;
410                 sock->stack_index= 0;
411                 
412                 sock->default_value = (oldsock->default_value ? MEM_dupallocN(oldsock->default_value) : NULL);
413                 
414                 /* XXX some compositor node (e.g. image, render layers) still store
415                  * some persistent buffer data here, need to clear this to avoid dangling pointers.
416                  */
417                 sock->cache = NULL;
418         }
419         
420         /* don't increase node->id users, freenode doesn't decrement either */
421         
422         if(node->typeinfo->copystoragefunc)
423                 node->typeinfo->copystoragefunc(node, nnode);
424         
425         node->new_node= nnode;
426         nnode->new_node= NULL;
427         nnode->preview= NULL;
428         
429         ntree->update |= NTREE_UPDATE_NODES;
430         
431         return nnode;
432 }
433
434 /* also used via rna api, so we check for proper input output direction */
435 bNodeLink *nodeAddLink(bNodeTree *ntree, bNode *fromnode, bNodeSocket *fromsock, bNode *tonode, bNodeSocket *tosock)
436 {
437         bNodeSocket *sock;
438         bNodeLink *link= NULL; 
439         int from= 0, to= 0;
440         
441         if(fromnode) {
442                 /* test valid input */
443                 for(sock= fromnode->outputs.first; sock; sock= sock->next)
444                         if(sock==fromsock)
445                                 break;
446                 if(sock)
447                         from= 1; /* OK */
448                 else {
449                         for(sock= fromnode->inputs.first; sock; sock= sock->next)
450                                 if(sock==fromsock)
451                                         break;
452                         if(sock)
453                                 from= -1; /* OK but flip */
454                 }
455         }
456         else {
457                 /* check tree sockets */
458                 for(sock= ntree->inputs.first; sock; sock= sock->next)
459                         if(sock==fromsock)
460                                 break;
461                 if(sock)
462                         from= 1; /* OK */
463                 else {
464                         for(sock= ntree->outputs.first; sock; sock= sock->next)
465                                 if(sock==fromsock)
466                                         break;
467                         if(sock)
468                                 from= -1; /* OK but flip */
469                 }
470         }
471         if(tonode) {
472                 for(sock= tonode->inputs.first; sock; sock= sock->next)
473                         if(sock==tosock)
474                                 break;
475                 if(sock)
476                         to= 1; /* OK */
477                 else {
478                         for(sock= tonode->outputs.first; sock; sock= sock->next)
479                                 if(sock==tosock)
480                                         break;
481                         if(sock)
482                                 to= -1; /* OK but flip */
483                 }
484         }
485         else {
486                 /* check tree sockets */
487                 for(sock= ntree->outputs.first; sock; sock= sock->next)
488                         if(sock==tosock)
489                                 break;
490                 if(sock)
491                         to= 1; /* OK */
492                 else {
493                         for(sock= ntree->inputs.first; sock; sock= sock->next)
494                                 if(sock==tosock)
495                                         break;
496                         if(sock)
497                                 to= -1; /* OK but flip */
498                 }
499         }
500         
501         if(from >= 0 && to >= 0) {
502                 link= MEM_callocN(sizeof(bNodeLink), "link");
503                 BLI_addtail(&ntree->links, link);
504                 link->fromnode= fromnode;
505                 link->fromsock= fromsock;
506                 link->tonode= tonode;
507                 link->tosock= tosock;
508         }
509         else if(from <= 0 && to <= 0) {
510                 link= MEM_callocN(sizeof(bNodeLink), "link");
511                 BLI_addtail(&ntree->links, link);
512                 link->fromnode= tonode;
513                 link->fromsock= tosock;
514                 link->tonode= fromnode;
515                 link->tosock= fromsock;
516         }
517         
518         ntree->update |= NTREE_UPDATE_LINKS;
519         
520         return link;
521 }
522
523 void nodeRemLink(bNodeTree *ntree, bNodeLink *link)
524 {
525         BLI_remlink(&ntree->links, link);
526         if(link->tosock)
527                 link->tosock->link= NULL;
528         MEM_freeN(link);
529         
530         ntree->update |= NTREE_UPDATE_LINKS;
531 }
532
533 void nodeRemSocketLinks(bNodeTree *ntree, bNodeSocket *sock)
534 {
535         bNodeLink *link, *next;
536         
537         for(link= ntree->links.first; link; link= next) {
538                 next= link->next;
539                 if(link->fromsock==sock || link->tosock==sock) {
540                         nodeRemLink(ntree, link);
541                 }
542         }
543         
544         ntree->update |= NTREE_UPDATE_LINKS;
545 }
546
547 /* transforms node location to area coords */
548 void nodeSpaceCoords(bNode *node, float *locx, float *locy)
549 {
550         if (node->parent) {
551                 nodeSpaceCoords(node->parent, locx, locy);
552                 *locx += node->locx;
553                 *locy += node->locy;
554         }
555         else {
556                 *locx = node->locx;
557                 *locy = node->locy;
558         }
559 }
560
561 void nodeAttachNode(bNode *node, bNode *parent)
562 {
563         float parentx, parenty;
564         
565         node->parent = parent;
566         /* transform to parent space */
567         nodeSpaceCoords(parent, &parentx, &parenty);
568         node->locx -= parentx;
569         node->locy -= parenty;
570 }
571
572 void nodeDetachNode(struct bNode *node)
573 {
574         float parentx, parenty;
575         
576         if (node->parent) {
577                 /* transform to "global" (area) space */
578                 nodeSpaceCoords(node->parent, &parentx, &parenty);
579                 node->locx += parentx;
580                 node->locy += parenty;
581                 node->parent = NULL;
582         }
583 }
584
585 bNodeTree *ntreeAddTree(const char *name, int type, int nodetype)
586 {
587         bNodeTree *ntree;
588         bNodeType *ntype;
589         
590         /* trees are created as local trees if they of compositor, material or texture type,
591          * node groups and other tree types are created as library data.
592          */
593         if (ELEM3(type, NTREE_COMPOSIT, NTREE_SHADER, NTREE_TEXTURE) && nodetype==0) {
594                 ntree= MEM_callocN(sizeof(bNodeTree), "new node tree");
595                 *( (short *)ntree->id.name )= ID_NT; /* not "type", as that is ntree->type */
596                 BLI_strncpy(ntree->id.name+2, name, sizeof(ntree->id.name));
597         }
598         else
599                 ntree= alloc_libblock(&G.main->nodetree, ID_NT, name);
600         
601         ntree->type= type;
602         ntree->nodetype = nodetype;
603         
604         ntreeInitTypes(ntree);
605         
606         ntype = node_get_type(ntree, ntree->nodetype);
607         if (ntype && ntype->inittreefunc)
608                 ntype->inittreefunc(ntree);
609         
610         return ntree;
611 }
612
613 /* Warning: this function gets called during some rather unexpected times
614  *      - this gets called when executing compositing updates (for threaded previews)
615  *      - when the nodetree datablock needs to be copied (i.e. when users get copied)
616  *      - for scene duplication use ntreeSwapID() after so we dont have stale pointers.
617  */
618 bNodeTree *ntreeCopyTree(bNodeTree *ntree)
619 {
620         bNodeTree *newtree;
621         bNode *node /*, *nnode */ /* UNUSED */, *last;
622         bNodeLink *link;
623         bNodeSocket *gsock, *oldgsock;
624         
625         if(ntree==NULL) return NULL;
626         
627         /* is ntree part of library? */
628         for(newtree=G.main->nodetree.first; newtree; newtree= newtree->id.next)
629                 if(newtree==ntree) break;
630         if(newtree) {
631                 newtree= copy_libblock(ntree);
632         } else {
633                 newtree= MEM_dupallocN(ntree);
634                 copy_libblock_data(&newtree->id, &ntree->id, TRUE); /* copy animdata and ID props */
635         }
636
637         id_us_plus((ID *)newtree->gpd);
638
639         /* in case a running nodetree is copied */
640         newtree->execdata= NULL;
641         
642         newtree->nodes.first= newtree->nodes.last= NULL;
643         newtree->links.first= newtree->links.last= NULL;
644         
645         last = ntree->nodes.last;
646         for(node= ntree->nodes.first; node; node= node->next) {
647                 node->new_node= NULL;
648                 /* nnode= */ nodeCopyNode(newtree, node);       /* sets node->new */
649                 
650                 /* make sure we don't copy new nodes again! */
651                 if (node==last)
652                         break;
653         }
654         
655         /* socket definition for group usage */
656         BLI_duplicatelist(&newtree->inputs, &ntree->inputs);
657         for(gsock= newtree->inputs.first, oldgsock= ntree->inputs.first; gsock; gsock=gsock->next, oldgsock=oldgsock->next) {
658                 oldgsock->new_sock= gsock;
659                 gsock->groupsock = (oldgsock->groupsock ? oldgsock->groupsock->new_sock : NULL);
660                 gsock->default_value = (oldgsock->default_value ? MEM_dupallocN(oldgsock->default_value) : NULL);
661         }
662         BLI_duplicatelist(&newtree->outputs, &ntree->outputs);
663         for(gsock= newtree->outputs.first, oldgsock= ntree->outputs.first; gsock; gsock=gsock->next, oldgsock=oldgsock->next) {
664                 oldgsock->new_sock= gsock;
665                 gsock->groupsock = (oldgsock->groupsock ? oldgsock->groupsock->new_sock : NULL);
666                 gsock->default_value = (oldgsock->default_value ? MEM_dupallocN(oldgsock->default_value) : NULL);
667         }
668         
669         /* copy links */
670         BLI_duplicatelist(&newtree->links, &ntree->links);
671         for(link= newtree->links.first; link; link= link->next) {
672                 link->fromnode = (link->fromnode ? link->fromnode->new_node : NULL);
673                 link->fromsock = (link->fromsock ? link->fromsock->new_sock : NULL);
674                 link->tonode = (link->tonode ? link->tonode->new_node : NULL);
675                 link->tosock = (link->tosock ? link->tosock->new_sock : NULL);
676                 /* update the link socket's pointer */
677                 if (link->tosock)
678                         link->tosock->link = link;
679         }
680         
681         /* update node->parent pointers */
682         for (node=newtree->nodes.first; node; node=node->next) {
683                 if (node->parent)
684                         node->parent = node->parent->new_node;
685         }
686         
687         return newtree;
688 }
689
690 /* use when duplicating scenes */
691 void ntreeSwitchID(bNodeTree *ntree, ID *id_from, ID *id_to)
692 {
693         bNode *node;
694         /* for scene duplication only */
695         for(node= ntree->nodes.first; node; node= node->next) {
696                 if(node->id==id_from) {
697                         node->id= id_to;
698                 }
699         }
700 }
701
702 /* *************** preview *********** */
703 /* if node->preview, then we assume the rect to exist */
704
705 void nodeFreePreview(bNode *node)
706 {
707         if(node->preview) {
708                 if(node->preview->rect)
709                         MEM_freeN(node->preview->rect);
710                 MEM_freeN(node->preview);
711                 node->preview= NULL;
712         }       
713 }
714
715 static void node_init_preview(bNode *node, int xsize, int ysize)
716 {
717         
718         if(node->preview==NULL) {
719                 node->preview= MEM_callocN(sizeof(bNodePreview), "node preview");
720                 //              printf("added preview %s\n", node->name);
721         }
722         
723         /* node previews can get added with variable size this way */
724         if(xsize==0 || ysize==0)
725                 return;
726         
727         /* sanity checks & initialize */
728         if(node->preview->rect) {
729                 if(node->preview->xsize!=xsize && node->preview->ysize!=ysize) {
730                         MEM_freeN(node->preview->rect);
731                         node->preview->rect= NULL;
732                 }
733         }
734         
735         if(node->preview->rect==NULL) {
736                 node->preview->rect= MEM_callocN(4*xsize + xsize*ysize*sizeof(char)*4, "node preview rect");
737                 node->preview->xsize= xsize;
738                 node->preview->ysize= ysize;
739         }
740         /* no clear, makes nicer previews */
741 }
742
743 void ntreeInitPreview(bNodeTree *ntree, int xsize, int ysize)
744 {
745         bNode *node;
746         
747         if(ntree==NULL)
748                 return;
749         
750         for(node= ntree->nodes.first; node; node= node->next) {
751                 if(node->typeinfo->flag & NODE_PREVIEW) /* hrms, check for closed nodes? */
752                         node_init_preview(node, xsize, ysize);
753                 if(node->type==NODE_GROUP && (node->flag & NODE_GROUP_EDIT))
754                         ntreeInitPreview((bNodeTree *)node->id, xsize, ysize);
755         }               
756 }
757
758 static void nodeClearPreview(bNode *node)
759 {
760         if(node->preview && node->preview->rect)
761                 memset(node->preview->rect, 0, MEM_allocN_len(node->preview->rect));
762 }
763
764 /* use it to enforce clear */
765 void ntreeClearPreview(bNodeTree *ntree)
766 {
767         bNode *node;
768         
769         if(ntree==NULL)
770                 return;
771         
772         for(node= ntree->nodes.first; node; node= node->next) {
773                 if(node->typeinfo->flag & NODE_PREVIEW)
774                         nodeClearPreview(node);
775                 if(node->type==NODE_GROUP && (node->flag & NODE_GROUP_EDIT))
776                         ntreeClearPreview((bNodeTree *)node->id);
777         }               
778 }
779
780 /* hack warning! this function is only used for shader previews, and 
781 since it gets called multiple times per pixel for Ztransp we only
782 add the color once. Preview gets cleared before it starts render though */
783 void nodeAddToPreview(bNode *node, float *col, int x, int y, int do_manage)
784 {
785         bNodePreview *preview= node->preview;
786         if(preview) {
787                 if(x>=0 && y>=0) {
788                         if(x<preview->xsize && y<preview->ysize) {
789                                 unsigned char *tar= preview->rect+ 4*((preview->xsize*y) + x);
790                                 
791                                 if(do_manage) {
792                                         tar[0]= FTOCHAR(linearrgb_to_srgb(col[0]));
793                                         tar[1]= FTOCHAR(linearrgb_to_srgb(col[1]));
794                                         tar[2]= FTOCHAR(linearrgb_to_srgb(col[2]));
795                                 }
796                                 else {
797                                         tar[0]= FTOCHAR(col[0]);
798                                         tar[1]= FTOCHAR(col[1]);
799                                         tar[2]= FTOCHAR(col[2]);
800                                 }
801                                 tar[3]= FTOCHAR(col[3]);
802                         }
803                         //else printf("prv out bound x y %d %d\n", x, y);
804                 }
805                 //else printf("prv out bound x y %d %d\n", x, y);
806         }
807 }
808
809 /* ************** Free stuff ********** */
810
811 /* goes over entire tree */
812 void nodeUnlinkNode(bNodeTree *ntree, bNode *node)
813 {
814         bNodeLink *link, *next;
815         bNodeSocket *sock;
816         ListBase *lb;
817         
818         for(link= ntree->links.first; link; link= next) {
819                 next= link->next;
820                 
821                 if(link->fromnode==node) {
822                         lb= &node->outputs;
823                         if (link->tonode)
824                                 link->tonode->update |= NODE_UPDATE;
825                 }
826                 else if(link->tonode==node)
827                         lb= &node->inputs;
828                 else
829                         lb= NULL;
830
831                 if(lb) {
832                         for(sock= lb->first; sock; sock= sock->next) {
833                                 if(link->fromsock==sock || link->tosock==sock)
834                                         break;
835                         }
836                         if(sock) {
837                                 nodeRemLink(ntree, link);
838                         }
839                 }
840         }
841 }
842
843 static void node_unlink_attached(bNodeTree *ntree, bNode *parent)
844 {
845         bNode *node;
846         for (node=ntree->nodes.first; node; node=node->next) {
847                 if (node->parent == parent)
848                         nodeDetachNode(node);
849         }
850 }
851
852 void nodeFreeNode(bNodeTree *ntree, bNode *node)
853 {
854         bNodeTreeType *treetype= ntreeGetType(ntree->type);
855         bNodeSocket *sock, *nextsock;
856         
857         /* remove all references to this node */
858         nodeUnlinkNode(ntree, node);
859         node_unlink_attached(ntree, node);
860         
861         BLI_remlink(&ntree->nodes, node);
862
863         /* since it is called while free database, node->id is undefined */
864         
865         if (treetype->free_node_cache)
866                 treetype->free_node_cache(ntree, node);
867         
868         for (sock=node->inputs.first; sock; sock = nextsock) {
869                 nextsock = sock->next;
870                 if (sock->default_value)
871                         MEM_freeN(sock->default_value);
872                 MEM_freeN(sock);
873         }
874         for (sock=node->outputs.first; sock; sock = nextsock) {
875                 nextsock = sock->next;
876                 if (sock->default_value)
877                         MEM_freeN(sock->default_value);
878                 MEM_freeN(sock);
879         }
880
881         nodeFreePreview(node);
882
883         if(node->typeinfo && node->typeinfo->freestoragefunc) {
884                 node->typeinfo->freestoragefunc(node);
885         }
886
887         MEM_freeN(node);
888         
889         ntree->update |= NTREE_UPDATE_NODES;
890 }
891
892 /* do not free ntree itself here, free_libblock calls this function too */
893 void ntreeFreeTree(bNodeTree *ntree)
894 {
895         bNode *node, *next;
896         bNodeSocket *sock;
897         
898         if(ntree==NULL) return;
899         
900         /* XXX hack! node trees should not store execution graphs at all.
901          * This should be removed when old tree types no longer require it.
902          * Currently the execution data for texture nodes remains in the tree
903          * after execution, until the node tree is updated or freed.
904          */
905         if (ntree->execdata) {
906                 switch (ntree->type) {
907                 case NTREE_COMPOSIT:
908                         ntreeCompositEndExecTree(ntree->execdata, 1);
909                         break;
910                 case NTREE_SHADER:
911                         ntreeShaderEndExecTree(ntree->execdata, 1);
912                         break;
913                 case NTREE_TEXTURE:
914                         ntreeTexEndExecTree(ntree->execdata, 1);
915                         break;
916                 }
917         }
918         
919         BKE_free_animdata((ID *)ntree);
920         
921         id_us_min((ID *)ntree->gpd);
922
923         BLI_freelistN(&ntree->links);   /* do first, then unlink_node goes fast */
924         
925         for(node= ntree->nodes.first; node; node= next) {
926                 next= node->next;
927                 nodeFreeNode(ntree, node);
928         }
929         
930         for (sock=ntree->inputs.first; sock; sock=sock->next)
931                 if (sock->default_value)
932                         MEM_freeN(sock->default_value);
933         BLI_freelistN(&ntree->inputs);
934         for (sock=ntree->outputs.first; sock; sock=sock->next)
935                 if (sock->default_value)
936                         MEM_freeN(sock->default_value);
937         BLI_freelistN(&ntree->outputs);
938 }
939
940 void ntreeFreeCache(bNodeTree *ntree)
941 {
942         bNodeTreeType *treetype;
943         
944         if(ntree==NULL) return;
945         
946         treetype= ntreeGetType(ntree->type);
947         if (treetype->free_cache)
948                 treetype->free_cache(ntree);
949 }
950
951 void ntreeSetOutput(bNodeTree *ntree)
952 {
953         bNode *node;
954
955         /* find the active outputs, might become tree type dependant handler */
956         for(node= ntree->nodes.first; node; node= node->next) {
957                 if(node->typeinfo->nclass==NODE_CLASS_OUTPUT) {
958                         bNode *tnode;
959                         int output= 0;
960                         
961                         /* we need a check for which output node should be tagged like this, below an exception */
962                         if(node->type==CMP_NODE_OUTPUT_FILE)
963                            continue;
964                            
965                         /* there is more types having output class, each one is checked */
966                         for(tnode= ntree->nodes.first; tnode; tnode= tnode->next) {
967                                 if(tnode->typeinfo->nclass==NODE_CLASS_OUTPUT) {
968                                         
969                                         if(ntree->type==NTREE_COMPOSIT) {
970                                                         
971                                                 /* same type, exception for viewer */
972                                                 if(tnode->type==node->type ||
973                                                    (ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER) &&
974                                                         ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))) {
975                                                         if(tnode->flag & NODE_DO_OUTPUT) {
976                                                                 output++;
977                                                                 if(output>1)
978                                                                         tnode->flag &= ~NODE_DO_OUTPUT;
979                                                         }
980                                                 }
981                                         }
982                                         else {
983                                                 /* same type */
984                                                 if(tnode->type==node->type) {
985                                                         if(tnode->flag & NODE_DO_OUTPUT) {
986                                                                 output++;
987                                                                 if(output>1)
988                                                                         tnode->flag &= ~NODE_DO_OUTPUT;
989                                                         }
990                                                 }
991                                         }
992                                 }
993                         }
994                         if(output==0)
995                                 node->flag |= NODE_DO_OUTPUT;
996                 }
997         }
998         
999         /* here we could recursively set which nodes have to be done,
1000                 might be different for editor or for "real" use... */
1001 }
1002
1003 typedef struct MakeLocalCallData {
1004         ID *group_id;
1005         ID *new_id;
1006         int lib, local;
1007 } MakeLocalCallData;
1008
1009 static void ntreeMakeLocal_CheckLocal(void *calldata, ID *owner_id, bNodeTree *ntree)
1010 {
1011         MakeLocalCallData *cd= (MakeLocalCallData*)calldata;
1012         bNode *node;
1013         
1014         /* find if group is in tree */
1015         for(node= ntree->nodes.first; node; node= node->next) {
1016                 if(node->id == cd->group_id) {
1017                         if(owner_id->lib) cd->lib= 1;
1018                         else cd->local= 1;
1019                 }
1020         }
1021 }
1022
1023 static void ntreeMakeLocal_LinkNew(void *calldata, ID *owner_id, bNodeTree *ntree)
1024 {
1025         MakeLocalCallData *cd= (MakeLocalCallData*)calldata;
1026         bNode *node;
1027         
1028         /* find if group is in tree */
1029         for(node= ntree->nodes.first; node; node= node->next) {
1030                 if(node->id == cd->group_id) {
1031                         if(owner_id->lib==NULL) {
1032                                 node->id= cd->new_id;
1033                                 cd->new_id->us++;
1034                                 cd->group_id->us--;
1035                         }
1036                 }
1037         }
1038 }
1039
1040 void ntreeMakeLocal(bNodeTree *ntree)
1041 {
1042         bNodeTreeType *treetype= ntreeGetType(ntree->type);
1043         MakeLocalCallData cd;
1044         
1045         /* - only lib users: do nothing
1046                 * - only local users: set flag
1047                 * - mixed: make copy
1048                 */
1049         
1050         if(ntree->id.lib==NULL) return;
1051         if(ntree->id.us==1) {
1052                 ntree->id.lib= NULL;
1053                 ntree->id.flag= LIB_LOCAL;
1054                 new_id(NULL, (ID *)ntree, NULL);
1055                 return;
1056         }
1057         
1058         /* now check users of groups... again typedepending, callback... */
1059         cd.group_id = &ntree->id;
1060         cd.new_id = NULL;
1061         cd.local = 0;
1062         cd.lib = 0;
1063         
1064         treetype->foreach_nodetree(G.main, &cd, &ntreeMakeLocal_CheckLocal);
1065         
1066         /* if all users are local, we simply make tree local */
1067         if(cd.local && cd.lib==0) {
1068                 ntree->id.lib= NULL;
1069                 ntree->id.flag= LIB_LOCAL;
1070                 new_id(NULL, (ID *)ntree, NULL);
1071         }
1072         else if(cd.local && cd.lib) {
1073                 /* this is the mixed case, we copy the tree and assign it to local users */
1074                 bNodeTree *newtree= ntreeCopyTree(ntree);
1075                 
1076                 newtree->id.us= 0;
1077                 
1078
1079                 cd.new_id = &newtree->id;
1080                 treetype->foreach_nodetree(G.main, &cd, &ntreeMakeLocal_LinkNew);
1081         }
1082 }
1083
1084 int ntreeNodeExists(bNodeTree *ntree, bNode *testnode)
1085 {
1086         bNode *node= ntree->nodes.first;
1087         for(; node; node= node->next)
1088                 if(node==testnode)
1089                         return 1;
1090         return 0;
1091 }
1092
1093 int ntreeOutputExists(bNode *node, bNodeSocket *testsock)
1094 {
1095         bNodeSocket *sock= node->outputs.first;
1096         for(; sock; sock= sock->next)
1097                 if(sock==testsock)
1098                         return 1;
1099         return 0;
1100 }
1101
1102 /* returns localized tree for execution in threads */
1103 bNodeTree *ntreeLocalize(bNodeTree *ntree)
1104 {
1105         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1106
1107         bNodeTree *ltree;
1108         bNode *node;
1109         
1110         bAction *action_backup= NULL, *tmpact_backup= NULL;
1111         
1112         /* Workaround for copying an action on each render!
1113          * set action to NULL so animdata actions dont get copied */
1114         AnimData *adt= BKE_animdata_from_id(&ntree->id);
1115
1116         if(adt) {
1117                 action_backup= adt->action;
1118                 tmpact_backup= adt->tmpact;
1119
1120                 adt->action= NULL;
1121                 adt->tmpact= NULL;
1122         }
1123
1124         /* node copy func */
1125         ltree= ntreeCopyTree(ntree);
1126
1127         if(adt) {
1128                 AnimData *ladt= BKE_animdata_from_id(&ltree->id);
1129
1130                 adt->action= ladt->action= action_backup;
1131                 adt->tmpact= ladt->tmpact= tmpact_backup;
1132
1133                 if(action_backup) action_backup->id.us++;
1134                 if(tmpact_backup) tmpact_backup->id.us++;
1135                 
1136         }
1137         /* end animdata uglyness */
1138
1139         /* ensures only a single output node is enabled */
1140         ntreeSetOutput(ntree);
1141
1142         for(node= ntree->nodes.first; node; node= node->next) {
1143                 /* store new_node pointer to original */
1144                 node->new_node->new_node= node;
1145         }
1146
1147         if (ntreetype->localize)
1148                 ntreetype->localize(ltree, ntree);
1149
1150         return ltree;
1151 }
1152
1153 /* sync local composite with real tree */
1154 /* local tree is supposed to be running, be careful moving previews! */
1155 /* is called by jobs manager, outside threads, so it doesnt happen during draw */
1156 void ntreeLocalSync(bNodeTree *localtree, bNodeTree *ntree)
1157 {
1158         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1159
1160         if (ntreetype->local_sync)
1161                 ntreetype->local_sync(localtree, ntree);
1162 }
1163
1164 /* merge local tree results back, and free local tree */
1165 /* we have to assume the editor already changed completely */
1166 void ntreeLocalMerge(bNodeTree *localtree, bNodeTree *ntree)
1167 {
1168         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1169         bNode *lnode;
1170         
1171         /* move over the compbufs and previews */
1172         for(lnode= localtree->nodes.first; lnode; lnode= lnode->next) {
1173                 if(ntreeNodeExists(ntree, lnode->new_node)) {
1174                         if(lnode->preview && lnode->preview->rect) {
1175                                 nodeFreePreview(lnode->new_node);
1176                                 lnode->new_node->preview= lnode->preview;
1177                                 lnode->preview= NULL;
1178                         }
1179                 }
1180         }
1181
1182         if (ntreetype->local_merge)
1183                 ntreetype->local_merge(localtree, ntree);
1184
1185         ntreeFreeTree(localtree);
1186         MEM_freeN(localtree);
1187 }
1188
1189 /* ************ find stuff *************** */
1190
1191 int ntreeHasType(bNodeTree *ntree, int type)
1192 {
1193         bNode *node;
1194         
1195         if(ntree)
1196                 for(node= ntree->nodes.first; node; node= node->next)
1197                         if(node->type == type)
1198                                 return 1;
1199         return 0;
1200 }
1201
1202 bNodeLink *nodeFindLink(bNodeTree *ntree, bNodeSocket *from, bNodeSocket *to)
1203 {
1204         bNodeLink *link;
1205         
1206         for(link= ntree->links.first; link; link= link->next) {
1207                 if(link->fromsock==from && link->tosock==to)
1208                         return link;
1209                 if(link->fromsock==to && link->tosock==from)    /* hrms? */
1210                         return link;
1211         }
1212         return NULL;
1213 }
1214
1215 int nodeCountSocketLinks(bNodeTree *ntree, bNodeSocket *sock)
1216 {
1217         bNodeLink *link;
1218         int tot= 0;
1219         
1220         for(link= ntree->links.first; link; link= link->next) {
1221                 if(link->fromsock==sock || link->tosock==sock)
1222                         tot++;
1223         }
1224         return tot;
1225 }
1226
1227 bNode *nodeGetActive(bNodeTree *ntree)
1228 {
1229         bNode *node;
1230         
1231         if(ntree==NULL) return NULL;
1232         
1233         for(node= ntree->nodes.first; node; node= node->next)
1234                 if(node->flag & NODE_ACTIVE)
1235                         break;
1236         return node;
1237 }
1238
1239 /* two active flags, ID nodes have special flag for buttons display */
1240 bNode *nodeGetActiveID(bNodeTree *ntree, short idtype)
1241 {
1242         bNode *node;
1243         
1244         if(ntree==NULL) return NULL;
1245
1246         /* check for group edit */
1247         for(node= ntree->nodes.first; node; node= node->next)
1248                 if(node->flag & NODE_GROUP_EDIT)
1249                         break;
1250
1251         if(node)
1252                 ntree= (bNodeTree*)node->id;
1253         
1254         /* now find active node with this id */
1255         for(node= ntree->nodes.first; node; node= node->next)
1256                 if(node->id && GS(node->id->name)==idtype)
1257                         if(node->flag & NODE_ACTIVE_ID)
1258                                 break;
1259
1260         return node;
1261 }
1262
1263 int nodeSetActiveID(bNodeTree *ntree, short idtype, ID *id)
1264 {
1265         bNode *node;
1266         int ok= FALSE;
1267
1268         if(ntree==NULL) return ok;
1269
1270         /* check for group edit */
1271         for(node= ntree->nodes.first; node; node= node->next)
1272                 if(node->flag & NODE_GROUP_EDIT)
1273                         break;
1274
1275         if(node)
1276                 ntree= (bNodeTree*)node->id;
1277
1278         /* now find active node with this id */
1279         for(node= ntree->nodes.first; node; node= node->next) {
1280                 if(node->id && GS(node->id->name)==idtype) {
1281                         if(id && ok==FALSE && node->id==id) {
1282                                 node->flag |= NODE_ACTIVE_ID;
1283                                 ok= TRUE;
1284                         } else {
1285                                 node->flag &= ~NODE_ACTIVE_ID;
1286                         }
1287                 }
1288         }
1289
1290         return ok;
1291 }
1292
1293
1294 /* two active flags, ID nodes have special flag for buttons display */
1295 void nodeClearActiveID(bNodeTree *ntree, short idtype)
1296 {
1297         bNode *node;
1298         
1299         if(ntree==NULL) return;
1300         
1301         for(node= ntree->nodes.first; node; node= node->next)
1302                 if(node->id && GS(node->id->name)==idtype)
1303                         node->flag &= ~NODE_ACTIVE_ID;
1304 }
1305
1306 /* two active flags, ID nodes have special flag for buttons display */
1307 void nodeSetActive(bNodeTree *ntree, bNode *node)
1308 {
1309         bNode *tnode;
1310         
1311         /* make sure only one node is active, and only one per ID type */
1312         for(tnode= ntree->nodes.first; tnode; tnode= tnode->next) {
1313                 tnode->flag &= ~NODE_ACTIVE;
1314                 
1315                 if(node->id && tnode->id) {
1316                         if(GS(node->id->name) == GS(tnode->id->name))
1317                                 tnode->flag &= ~NODE_ACTIVE_ID;
1318                 }
1319         }
1320         
1321         node->flag |= NODE_ACTIVE;
1322         if(node->id)
1323                 node->flag |= NODE_ACTIVE_ID;
1324 }
1325
1326 /* use flags are not persistant yet, groups might need different tagging, so we do it each time
1327    when we need to get this info */
1328 void ntreeSocketUseFlags(bNodeTree *ntree)
1329 {
1330         bNode *node;
1331         bNodeSocket *sock;
1332         bNodeLink *link;
1333         
1334         /* clear flags */
1335         for(node= ntree->nodes.first; node; node= node->next) {
1336                 for(sock= node->inputs.first; sock; sock= sock->next)
1337                         sock->flag &= ~SOCK_IN_USE;
1338                 for(sock= node->outputs.first; sock; sock= sock->next)
1339                         sock->flag &= ~SOCK_IN_USE;
1340         }
1341         
1342         /* tag all thats in use */
1343         for(link= ntree->links.first; link; link= link->next) {
1344         
1345                 if(link->fromsock) // FIXME, see below
1346                         link->fromsock->flag |= SOCK_IN_USE;
1347                 if(link->tosock) // FIXME This can be NULL, when dragging a new link in the UI, should probably copy the node tree for preview render - campbell
1348                         link->tosock->flag |= SOCK_IN_USE;
1349         }
1350 }
1351
1352 /* ************** dependency stuff *********** */
1353
1354 /* node is guaranteed to be not checked before */
1355 static int node_get_deplist_recurs(bNode *node, bNode ***nsort)
1356 {
1357         bNode *fromnode;
1358         bNodeSocket *sock;
1359         int level = 0xFFF;
1360         
1361         node->done= 1;
1362         
1363         /* check linked nodes */
1364         for(sock= node->inputs.first; sock; sock= sock->next) {
1365                 if(sock->link) {
1366                         fromnode= sock->link->fromnode;
1367                         if(fromnode) {
1368                                 if (fromnode->done==0)
1369                                         fromnode->level= node_get_deplist_recurs(fromnode, nsort);
1370                                 if (fromnode->level <= level)
1371                                         level = fromnode->level - 1;
1372                         }
1373                 }
1374         }
1375         
1376         /* check parent node */
1377         if (node->parent) {
1378                 if (node->parent->done==0)
1379                         node->parent->level= node_get_deplist_recurs(node->parent, nsort);
1380                 if (node->parent->level <= level)
1381                         level = node->parent->level - 1;
1382         }
1383         
1384         if (nsort) {
1385                 **nsort= node;
1386                 (*nsort)++;
1387         }
1388         
1389         return level;
1390 }
1391
1392 void ntreeGetDependencyList(struct bNodeTree *ntree, struct bNode ***deplist, int *totnodes)
1393 {
1394         bNode *node, **nsort;
1395         
1396         *totnodes=0;
1397         
1398         /* first clear data */
1399         for(node= ntree->nodes.first; node; node= node->next) {
1400                 node->done= 0;
1401                 (*totnodes)++;
1402         }
1403         if(*totnodes==0) {
1404                 *deplist = NULL;
1405                 return;
1406         }
1407         
1408         nsort= *deplist= MEM_callocN((*totnodes)*sizeof(bNode*), "sorted node array");
1409         
1410         /* recursive check */
1411         for(node= ntree->nodes.first; node; node= node->next) {
1412                 if(node->done==0) {
1413                         node->level= node_get_deplist_recurs(node, &nsort);
1414                 }
1415         }
1416 }
1417
1418 static void ntree_update_link_pointers(bNodeTree *ntree)
1419 {
1420         bNode *node;
1421         bNodeSocket *sock;
1422         bNodeLink *link;
1423         
1424         /* first clear data */
1425         for(node= ntree->nodes.first; node; node= node->next) {
1426                 for(sock= node->inputs.first; sock; sock= sock->next)
1427                         sock->link= NULL;
1428         }
1429         /* clear socket links */
1430         for(sock= ntree->outputs.first; sock; sock= sock->next)
1431                 sock->link= NULL;
1432
1433         for(link= ntree->links.first; link; link= link->next) {
1434                 if (link->tosock)
1435                         link->tosock->link= link;
1436         }
1437 }
1438
1439 static void ntree_validate_links(bNodeTree *ntree)
1440 {
1441         bNodeTreeType *ntreetype = ntreeGetType(ntree->type);
1442         bNodeLink *link;
1443         
1444         for (link = ntree->links.first; link; link = link->next) {
1445                 link->flag |= NODE_LINK_VALID;
1446                 if (link->fromnode && link->tonode && link->fromnode->level <= link->tonode->level)
1447                         link->flag &= ~NODE_LINK_VALID;
1448                 else if (ntreetype->validate_link) {
1449                         if (!ntreetype->validate_link(ntree, link))
1450                                 link->flag &= ~NODE_LINK_VALID;
1451                 }
1452         }
1453 }
1454
1455 static void ntree_verify_nodes_cb(void *calldata, struct ID *UNUSED(owner_id), struct bNodeTree *ntree)
1456 {
1457         ID *id= (ID*)calldata;
1458         bNode *node;
1459         
1460         for (node=ntree->nodes.first; node; node=node->next)
1461                 if (node->typeinfo->verifyfunc)
1462                         node->typeinfo->verifyfunc(ntree, node, id);
1463 }
1464
1465 void ntreeVerifyNodes(struct Main *main, struct ID *id)
1466 {
1467         bNodeTreeType *ntreetype;
1468         bNodeTree *ntree;
1469         int n;
1470         
1471         for (n=0; n < NUM_NTREE_TYPES; ++n) {
1472                 ntreetype= ntreeGetType(n);
1473                 if (ntreetype && ntreetype->foreach_nodetree)
1474                         ntreetype->foreach_nodetree(main, id, ntree_verify_nodes_cb);
1475         }
1476         for (ntree=main->nodetree.first; ntree; ntree=ntree->id.next)
1477                 ntree_verify_nodes_cb(id, NULL, ntree);
1478 }
1479
1480 void ntreeUpdateTree(bNodeTree *ntree)
1481 {
1482         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1483         bNode *node;
1484         bNode **deplist;
1485         int totnodes, n;
1486         
1487         ntree_update_link_pointers(ntree);
1488         
1489         /* also updates the node level! */
1490         ntreeGetDependencyList(ntree, &deplist, &totnodes);
1491         
1492         if (deplist) {
1493                 /* update individual nodes */
1494                 for (n=0; n < totnodes; ++n) {
1495                         node = deplist[n];
1496                         
1497                         /* node tree update tags override individual node update flags */
1498                         if ((node->update & NODE_UPDATE) || (ntree->update & NTREE_UPDATE)) {
1499                                 if (ntreetype->update_node)
1500                                         ntreetype->update_node(ntree, node);
1501                                 else if (node->typeinfo->updatefunc)
1502                                         node->typeinfo->updatefunc(ntree, node);
1503                         }
1504                         /* clear update flag */
1505                         node->update = 0;
1506                 }
1507                 
1508                 MEM_freeN(deplist);
1509         }
1510         
1511         /* general tree updates */
1512         if (ntree->update & (NTREE_UPDATE_LINKS|NTREE_UPDATE_NODES)) {
1513                 ntree_validate_links(ntree);
1514         }
1515         
1516         /* update tree */
1517         if (ntreetype->update)
1518                 ntreetype->update(ntree);
1519         else {
1520                 /* Trees can be associated with a specific node type (i.e. group nodes),
1521                  * in that case a tree update function may be defined by that node type.
1522                  */
1523                 bNodeType *ntype= node_get_type(ntree, ntree->nodetype);
1524                 if (ntype && ntype->updatetreefunc)
1525                         ntype->updatetreefunc(ntree);
1526         }
1527         
1528         /* XXX hack, should be done by depsgraph!! */
1529         ntreeVerifyNodes(G.main, &ntree->id);
1530         
1531         /* clear the update flag */
1532         ntree->update = 0;
1533 }
1534
1535 void nodeUpdate(bNodeTree *ntree, bNode *node)
1536 {
1537         bNodeTreeType *ntreetype= ntreeGetType(ntree->type);
1538         
1539         if (ntreetype->update_node)
1540                 ntreetype->update_node(ntree, node);
1541         else if (node->typeinfo->updatefunc)
1542                 node->typeinfo->updatefunc(ntree, node);
1543         /* clear update flag */
1544         node->update = 0;
1545 }
1546
1547 int nodeUpdateID(bNodeTree *ntree, ID *id)
1548 {
1549         bNodeTreeType *ntreetype;
1550         bNode *node;
1551         int change = FALSE;
1552         
1553         if(ELEM(NULL, id, ntree))
1554                 return change;
1555         
1556         ntreetype = ntreeGetType(ntree->type);
1557         
1558         if (ntreetype->update_node) {
1559                 for(node= ntree->nodes.first; node; node= node->next) {
1560                         if(node->id==id) {
1561                                 change = TRUE;
1562                                 ntreetype->update_node(ntree, node);
1563                                 /* clear update flag */
1564                                 node->update = 0;
1565                         }
1566                 }
1567         }
1568         else {
1569                 for(node= ntree->nodes.first; node; node= node->next) {
1570                         if(node->id==id) {
1571                                 change = TRUE;
1572                                 if (node->typeinfo->updatefunc)
1573                                         node->typeinfo->updatefunc(ntree, node);
1574                                 /* clear update flag */
1575                                 node->update = 0;
1576                         }
1577                 }
1578         }
1579         
1580         return change;
1581 }
1582
1583
1584 /* ************* node type access ********** */
1585
1586 int nodeValid(bNodeTree *ntree, bNodeTemplate *ntemp)
1587 {
1588         bNodeType *ntype= node_get_type(ntree, ntemp->type);
1589         if (ntype) {
1590                 if (ntype->validfunc)
1591                         return ntype->validfunc(ntree, ntemp);
1592                 else
1593                         return 1;
1594         }
1595         else
1596                 return 0;
1597 }
1598
1599 const char* nodeLabel(bNode *node)
1600 {
1601         if (node->label[0]!='\0')
1602                 return node->label;
1603         else if (node->typeinfo->labelfunc)
1604                 return node->typeinfo->labelfunc(node);
1605         else
1606                 return node->typeinfo->name;
1607 }
1608
1609 struct bNodeTree *nodeGroupEditGet(struct bNode *node)
1610 {
1611         if (node->typeinfo->group_edit_get)
1612                 return node->typeinfo->group_edit_get(node);
1613         else
1614                 return NULL;
1615 }
1616
1617 struct bNodeTree *nodeGroupEditSet(struct bNode *node, int edit)
1618 {
1619         if (node->typeinfo->group_edit_set)
1620                 return node->typeinfo->group_edit_set(node, edit);
1621         else if (node->typeinfo->group_edit_get)
1622                 return node->typeinfo->group_edit_get(node);
1623         else
1624                 return NULL;
1625 }
1626
1627 void nodeGroupEditClear(struct bNode *node)
1628 {
1629         if (node->typeinfo->group_edit_clear)
1630                 node->typeinfo->group_edit_clear(node);
1631 }
1632
1633 struct bNodeTemplate nodeMakeTemplate(struct bNode *node)
1634 {
1635         bNodeTemplate ntemp;
1636         if (node->typeinfo->templatefunc)
1637                 return node->typeinfo->templatefunc(node);
1638         else {
1639                 ntemp.type = node->type;
1640                 return ntemp;
1641         }
1642 }
1643
1644 void node_type_base(bNodeType *ntype, int type, const char *name, short nclass, short flag)
1645 {
1646         memset(ntype, 0, sizeof(bNodeType));
1647         
1648         ntype->type = type;
1649         BLI_strncpy(ntype->name, name, sizeof(ntype->name));
1650         ntype->nclass = nclass;
1651         ntype->flag = flag;
1652         
1653         /* default size values */
1654         ntype->width = 140;
1655         ntype->minwidth = 100;
1656         ntype->maxwidth = 320;
1657         ntype->height = 100;
1658         ntype->minheight = 30;
1659         ntype->maxheight = FLT_MAX;
1660 }
1661
1662 void node_type_socket_templates(struct bNodeType *ntype, struct bNodeSocketTemplate *inputs, struct bNodeSocketTemplate *outputs)
1663 {
1664         ntype->inputs = inputs;
1665         ntype->outputs = outputs;
1666 }
1667
1668 void node_type_init(struct bNodeType *ntype, void (*initfunc)(struct bNodeTree *ntree, struct bNode *node, struct bNodeTemplate *ntemp))
1669 {
1670         ntype->initfunc = initfunc;
1671 }
1672
1673 void node_type_valid(struct bNodeType *ntype, int (*validfunc)(struct bNodeTree *ntree, struct bNodeTemplate *ntemp))
1674 {
1675         ntype->validfunc = validfunc;
1676 }
1677
1678 void node_type_size(struct bNodeType *ntype, int width, int minwidth, int maxwidth)
1679 {
1680         ntype->width = width;
1681         ntype->minwidth = minwidth;
1682         if (maxwidth <= minwidth)
1683                 ntype->maxwidth = FLT_MAX;
1684         else
1685                 ntype->maxwidth = maxwidth;
1686 }
1687
1688 void node_type_storage(bNodeType *ntype, const char *storagename, void (*freestoragefunc)(struct bNode *), void (*copystoragefunc)(struct bNode *, struct bNode *))
1689 {
1690         if (storagename)
1691                 BLI_strncpy(ntype->storagename, storagename, sizeof(ntype->storagename));
1692         else
1693                 ntype->storagename[0] = '\0';
1694         ntype->copystoragefunc = copystoragefunc;
1695         ntype->freestoragefunc = freestoragefunc;
1696 }
1697
1698 void node_type_label(struct bNodeType *ntype, const char *(*labelfunc)(struct bNode *))
1699 {
1700         ntype->labelfunc = labelfunc;
1701 }
1702
1703 void node_type_template(struct bNodeType *ntype, struct bNodeTemplate (*templatefunc)(struct bNode *))
1704 {
1705         ntype->templatefunc = templatefunc;
1706 }
1707
1708 void node_type_update(struct bNodeType *ntype,
1709                                           void (*updatefunc)(struct bNodeTree *ntree, struct bNode *node),
1710                                           void (*verifyfunc)(struct bNodeTree *ntree, struct bNode *node, struct ID *id))
1711 {
1712         ntype->updatefunc = updatefunc;
1713         ntype->verifyfunc = verifyfunc;
1714 }
1715
1716 void node_type_tree(struct bNodeType *ntype, void (*inittreefunc)(struct bNodeTree *), void (*updatetreefunc)(struct bNodeTree *))
1717 {
1718         ntype->inittreefunc = inittreefunc;
1719         ntype->updatetreefunc = updatetreefunc;
1720 }
1721
1722 void node_type_group_edit(struct bNodeType *ntype,
1723                                                   struct bNodeTree *(*group_edit_get)(struct bNode *node),
1724                                                   struct bNodeTree *(*group_edit_set)(struct bNode *node, int edit),
1725                                                   void (*group_edit_clear)(struct bNode *node))
1726 {
1727         ntype->group_edit_get = group_edit_get;
1728         ntype->group_edit_set = group_edit_set;
1729         ntype->group_edit_clear = group_edit_clear;
1730 }
1731
1732 void node_type_exec(struct bNodeType *ntype, void (*execfunc)(void *data, struct bNode *, struct bNodeStack **, struct bNodeStack **))
1733 {
1734         ntype->execfunc = execfunc;
1735 }
1736
1737 void node_type_exec_new(struct bNodeType *ntype,
1738                                                 void *(*initexecfunc)(struct bNode *node),
1739                                                 void (*freeexecfunc)(struct bNode *node, void *nodedata),
1740                                                 void (*newexecfunc)(void *data, int thread, struct bNode *, void *nodedata, struct bNodeStack **, struct bNodeStack **))
1741 {
1742         ntype->initexecfunc = initexecfunc;
1743         ntype->freeexecfunc = freeexecfunc;
1744         ntype->newexecfunc = newexecfunc;
1745 }
1746
1747 void node_type_gpu(struct bNodeType *ntype, int (*gpufunc)(struct GPUMaterial *mat, struct bNode *node, struct GPUNodeStack *in, struct GPUNodeStack *out))
1748 {
1749         ntype->gpufunc = gpufunc;
1750 }
1751
1752 void node_type_gpu_ext(struct bNodeType *ntype, int (*gpuextfunc)(struct GPUMaterial *mat, struct bNode *node, void *nodedata, struct GPUNodeStack *in, struct GPUNodeStack *out))
1753 {
1754         ntype->gpuextfunc = gpuextfunc;
1755 }
1756
1757
1758 static bNodeType *is_nodetype_registered(ListBase *typelist, int type) 
1759 {
1760         bNodeType *ntype= typelist->first;
1761         
1762         for(;ntype; ntype= ntype->next )
1763                 if(ntype->type==type)
1764                         return ntype;
1765         
1766         return NULL;
1767 }
1768
1769 void nodeRegisterType(ListBase *typelist, bNodeType *ntype) 
1770 {
1771         bNodeType *found= is_nodetype_registered(typelist, ntype->type);
1772         
1773         if(found==NULL)
1774                 BLI_addtail(typelist, ntype);
1775 }
1776
1777 static void registerCompositNodes(ListBase *ntypelist)
1778 {
1779         register_node_type_frame(ntypelist);
1780         
1781         register_node_type_cmp_group(ntypelist);
1782 //      register_node_type_cmp_forloop(ntypelist);
1783 //      register_node_type_cmp_whileloop(ntypelist);
1784         
1785         register_node_type_cmp_rlayers(ntypelist);
1786         register_node_type_cmp_image(ntypelist);
1787         register_node_type_cmp_texture(ntypelist);
1788         register_node_type_cmp_value(ntypelist);
1789         register_node_type_cmp_rgb(ntypelist);
1790         register_node_type_cmp_curve_time(ntypelist);
1791         
1792         register_node_type_cmp_composite(ntypelist);
1793         register_node_type_cmp_viewer(ntypelist);
1794         register_node_type_cmp_splitviewer(ntypelist);
1795         register_node_type_cmp_output_file(ntypelist);
1796         register_node_type_cmp_view_levels(ntypelist);
1797         
1798         register_node_type_cmp_curve_rgb(ntypelist);
1799         register_node_type_cmp_mix_rgb(ntypelist);
1800         register_node_type_cmp_hue_sat(ntypelist);
1801         register_node_type_cmp_brightcontrast(ntypelist);
1802         register_node_type_cmp_gamma(ntypelist);
1803         register_node_type_cmp_invert(ntypelist);
1804         register_node_type_cmp_alphaover(ntypelist);
1805         register_node_type_cmp_zcombine(ntypelist);
1806         register_node_type_cmp_colorbalance(ntypelist);
1807         register_node_type_cmp_huecorrect(ntypelist);
1808         
1809         register_node_type_cmp_normal(ntypelist);
1810         register_node_type_cmp_curve_vec(ntypelist);
1811         register_node_type_cmp_map_value(ntypelist);
1812         register_node_type_cmp_normalize(ntypelist);
1813         
1814         register_node_type_cmp_filter(ntypelist);
1815         register_node_type_cmp_blur(ntypelist);
1816         register_node_type_cmp_dblur(ntypelist);
1817         register_node_type_cmp_bilateralblur(ntypelist);
1818         register_node_type_cmp_vecblur(ntypelist);
1819         register_node_type_cmp_dilateerode(ntypelist);
1820         register_node_type_cmp_defocus(ntypelist);
1821         
1822         register_node_type_cmp_valtorgb(ntypelist);
1823         register_node_type_cmp_rgbtobw(ntypelist);
1824         register_node_type_cmp_setalpha(ntypelist);
1825         register_node_type_cmp_idmask(ntypelist);
1826         register_node_type_cmp_math(ntypelist);
1827         register_node_type_cmp_seprgba(ntypelist);
1828         register_node_type_cmp_combrgba(ntypelist);
1829         register_node_type_cmp_sephsva(ntypelist);
1830         register_node_type_cmp_combhsva(ntypelist);
1831         register_node_type_cmp_sepyuva(ntypelist);
1832         register_node_type_cmp_combyuva(ntypelist);
1833         register_node_type_cmp_sepycca(ntypelist);
1834         register_node_type_cmp_combycca(ntypelist);
1835         register_node_type_cmp_premulkey(ntypelist);
1836         
1837         register_node_type_cmp_diff_matte(ntypelist);
1838         register_node_type_cmp_distance_matte(ntypelist);
1839         register_node_type_cmp_chroma_matte(ntypelist);
1840         register_node_type_cmp_color_matte(ntypelist);
1841         register_node_type_cmp_channel_matte(ntypelist);
1842         register_node_type_cmp_color_spill(ntypelist);
1843         register_node_type_cmp_luma_matte(ntypelist);
1844         
1845         register_node_type_cmp_translate(ntypelist);
1846         register_node_type_cmp_rotate(ntypelist);
1847         register_node_type_cmp_scale(ntypelist);
1848         register_node_type_cmp_flip(ntypelist);
1849         register_node_type_cmp_crop(ntypelist);
1850         register_node_type_cmp_displace(ntypelist);
1851         register_node_type_cmp_mapuv(ntypelist);
1852         register_node_type_cmp_glare(ntypelist);
1853         register_node_type_cmp_tonemap(ntypelist);
1854         register_node_type_cmp_lensdist(ntypelist);
1855 }
1856
1857 static void registerShaderNodes(ListBase *ntypelist) 
1858 {
1859         register_node_type_frame(ntypelist);
1860         
1861         register_node_type_sh_group(ntypelist);
1862 //      register_node_type_sh_forloop(ntypelist);
1863 //      register_node_type_sh_whileloop(ntypelist);
1864         
1865         register_node_type_sh_output(ntypelist);
1866         register_node_type_sh_mix_rgb(ntypelist);
1867         register_node_type_sh_valtorgb(ntypelist);
1868         register_node_type_sh_rgbtobw(ntypelist);
1869         register_node_type_sh_normal(ntypelist);
1870         register_node_type_sh_geom(ntypelist);
1871         register_node_type_sh_mapping(ntypelist);
1872         register_node_type_sh_curve_vec(ntypelist);
1873         register_node_type_sh_curve_rgb(ntypelist);
1874         register_node_type_sh_math(ntypelist);
1875         register_node_type_sh_vect_math(ntypelist);
1876         register_node_type_sh_squeeze(ntypelist);
1877         register_node_type_sh_camera(ntypelist);
1878         register_node_type_sh_material(ntypelist);
1879         register_node_type_sh_material_ext(ntypelist);
1880         register_node_type_sh_value(ntypelist);
1881         register_node_type_sh_rgb(ntypelist);
1882         register_node_type_sh_texture(ntypelist);
1883 //      register_node_type_sh_dynamic(ntypelist);
1884         register_node_type_sh_invert(ntypelist);
1885         register_node_type_sh_seprgb(ntypelist);
1886         register_node_type_sh_combrgb(ntypelist);
1887         register_node_type_sh_hue_sat(ntypelist);
1888 }
1889
1890 static void registerTextureNodes(ListBase *ntypelist)
1891 {
1892         register_node_type_frame(ntypelist);
1893         
1894         register_node_type_tex_group(ntypelist);
1895 //      register_node_type_tex_forloop(ntypelist);
1896 //      register_node_type_tex_whileloop(ntypelist);
1897         
1898         register_node_type_tex_math(ntypelist);
1899         register_node_type_tex_mix_rgb(ntypelist);
1900         register_node_type_tex_valtorgb(ntypelist);
1901         register_node_type_tex_rgbtobw(ntypelist);
1902         register_node_type_tex_valtonor(ntypelist);
1903         register_node_type_tex_curve_rgb(ntypelist);
1904         register_node_type_tex_curve_time(ntypelist);
1905         register_node_type_tex_invert(ntypelist);
1906         register_node_type_tex_hue_sat(ntypelist);
1907         register_node_type_tex_coord(ntypelist);
1908         register_node_type_tex_distance(ntypelist);
1909         register_node_type_tex_compose(ntypelist);
1910         register_node_type_tex_decompose(ntypelist);
1911         
1912         register_node_type_tex_output(ntypelist);
1913         register_node_type_tex_viewer(ntypelist);
1914         
1915         register_node_type_tex_checker(ntypelist);
1916         register_node_type_tex_texture(ntypelist);
1917         register_node_type_tex_bricks(ntypelist);
1918         register_node_type_tex_image(ntypelist);
1919         
1920         register_node_type_tex_rotate(ntypelist);
1921         register_node_type_tex_translate(ntypelist);
1922         register_node_type_tex_scale(ntypelist);
1923         register_node_type_tex_at(ntypelist);
1924         
1925         register_node_type_tex_proc_voronoi(ntypelist);
1926         register_node_type_tex_proc_blend(ntypelist);
1927         register_node_type_tex_proc_magic(ntypelist);
1928         register_node_type_tex_proc_marble(ntypelist);
1929         register_node_type_tex_proc_clouds(ntypelist);
1930         register_node_type_tex_proc_wood(ntypelist);
1931         register_node_type_tex_proc_musgrave(ntypelist);
1932         register_node_type_tex_proc_noise(ntypelist);
1933         register_node_type_tex_proc_stucci(ntypelist);
1934         register_node_type_tex_proc_distnoise(ntypelist);
1935 }
1936
1937 static void free_dynamic_typeinfo(bNodeType *ntype)
1938 {
1939         if(ntype->type==NODE_DYNAMIC) {
1940                 if(ntype->inputs) {
1941                         MEM_freeN(ntype->inputs);
1942                 }
1943                 if(ntype->outputs) {
1944                         MEM_freeN(ntype->outputs);
1945                 }
1946                 if(ntype->name) {
1947                         MEM_freeN((void *)ntype->name);
1948                 }
1949         }
1950 }
1951
1952 static void free_typeinfos(ListBase *list)
1953 {
1954         bNodeType *ntype, *next;
1955         for(ntype=list->first; ntype; ntype=next) {
1956                 next = ntype->next;
1957                 
1958                 if(ntype->type==NODE_DYNAMIC)
1959                         free_dynamic_typeinfo(ntype);
1960                 
1961                 if(ntype->needs_free)
1962                         MEM_freeN(ntype);
1963         }
1964 }
1965
1966 void init_nodesystem(void) 
1967 {
1968         registerCompositNodes(&ntreeGetType(NTREE_COMPOSIT)->node_types);
1969         registerShaderNodes(&ntreeGetType(NTREE_SHADER)->node_types);
1970         registerTextureNodes(&ntreeGetType(NTREE_TEXTURE)->node_types);
1971 }
1972
1973 void free_nodesystem(void) 
1974 {
1975         free_typeinfos(&ntreeGetType(NTREE_COMPOSIT)->node_types);
1976         free_typeinfos(&ntreeGetType(NTREE_SHADER)->node_types);
1977         free_typeinfos(&ntreeGetType(NTREE_TEXTURE)->node_types);
1978 }
1979
1980 /* called from unlink_scene, when deleting a scene goes over all scenes
1981  * other than the input, checks if they have render layer nodes referencing
1982  * the to-be-deleted scene, and resets them to NULL. */
1983
1984 /* XXX needs to get current scene then! */
1985 void clear_scene_in_nodes(Main *bmain, Scene *sce)
1986 {
1987         Scene *sce1;
1988         bNode *node;
1989
1990         for(sce1= bmain->scene.first; sce1; sce1=sce1->id.next) {
1991                 if(sce1!=sce) {
1992                         if(sce1->nodetree) {
1993                                 for(node= sce1->nodetree->nodes.first; node; node= node->next) {
1994                                         if(node->type==CMP_NODE_R_LAYERS) {
1995                                                 Scene *nodesce= (Scene *)node->id;
1996                                                 
1997                                                 if (nodesce==sce) node->id = NULL;
1998                                         }
1999                                 }
2000                         }
2001                 }
2002         }
2003 }
2004