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