Scons build system. MSVC 7.1 in a moment.
[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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, 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): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <stdlib.h>
31 #include <string.h>
32
33 #include "DNA_ID.h"
34 #include "DNA_image_types.h"
35 #include "DNA_node_types.h"
36 #include "DNA_material_types.h"
37 #include "DNA_scene_types.h"
38
39 #include "BKE_blender.h"
40 #include "BKE_colortools.h"
41 #include "BKE_global.h"
42 #include "BKE_image.h"
43 #include "BKE_library.h"
44 #include "BKE_main.h"
45 #include "BKE_node.h"
46 #include "BKE_texture.h"
47 #include "BKE_utildefines.h"
48
49 #include "BLI_arithb.h"
50 #include "BLI_blenlib.h"
51 #include "BLI_rand.h"
52 #include "BLI_threads.h"
53
54 #include "PIL_time.h"
55
56 #include "MEM_guardedalloc.h"
57 #include "IMB_imbuf.h"
58
59 #include "RE_pipeline.h"
60 #include "RE_shader_ext.h"              /* <- TexResult */
61 #include "RE_render_ext.h"              /* <- ibuf_sample() */
62
63 #include "CMP_node.h"
64 #include "SHD_node.h"
65
66 /* not very important, but the stack solver likes to know a maximum */
67 #define MAX_SOCKET      64
68
69 /* ************** Type stuff **********  */
70
71 static bNodeType *node_get_type(bNodeTree *ntree, int type, bNodeTree *ngroup)
72 {
73         if(type==NODE_GROUP) {
74                 if(ngroup && GS(ngroup->id.name)==ID_NT) {
75                         return ngroup->owntype;
76                 }
77                 return NULL;
78         }
79         else {
80                 bNodeType **typedefs= ntree->alltypes;
81                 
82                 while( *typedefs && (*typedefs)->type!=type)
83                         typedefs++;
84                 
85                 return *typedefs;
86         }
87 }
88
89 void ntreeInitTypes(bNodeTree *ntree)
90 {
91         bNode *node, *next;
92         
93         if(ntree->type==NTREE_SHADER)
94                 ntree->alltypes= node_all_shaders;
95         else if(ntree->type==NTREE_COMPOSIT)
96                 ntree->alltypes= node_all_composit;
97         else {
98                 ntree->alltypes= NULL;
99                 printf("Error: no type definitions for nodes\n");
100         }
101         
102         for(node= ntree->nodes.first; node; node= next) {
103                 next= node->next;
104                 node->typeinfo= node_get_type(ntree, node->type, (bNodeTree *)node->id);
105                 if(node->typeinfo==NULL) {
106                         printf("Error: Node type %s doesn't exist anymore, removed\n", node->name);
107                         nodeFreeNode(ntree, node);
108                 }
109         }
110                         
111         ntree->init |= NTREE_TYPE_INIT;
112 }
113
114 /* only used internal... we depend on type definitions! */
115 static bNodeSocket *node_add_socket_type(ListBase *lb, bNodeSocketType *stype)
116 {
117         bNodeSocket *sock= MEM_callocN(sizeof(bNodeSocket), "sock");
118         
119         BLI_strncpy(sock->name, stype->name, NODE_MAXSTR);
120         if(stype->limit==0) sock->limit= 0xFFF;
121         else sock->limit= stype->limit;
122         sock->type= stype->type;
123         
124         sock->to_index= stype->own_index;
125         sock->tosock= stype->internsock;
126         
127         sock->ns.vec[0]= stype->val1;
128         sock->ns.vec[1]= stype->val2;
129         sock->ns.vec[2]= stype->val3;
130         sock->ns.vec[3]= stype->val4;
131         sock->ns.min= stype->min;
132         sock->ns.max= stype->max;
133         
134         if(lb)
135                 BLI_addtail(lb, sock);
136         
137         return sock;
138 }
139
140 static void node_rem_socket(bNodeTree *ntree, ListBase *lb, bNodeSocket *sock)
141 {
142         bNodeLink *link, *next;
143         
144         for(link= ntree->links.first; link; link= next) {
145                 next= link->next;
146                 if(link->fromsock==sock || link->tosock==sock) {
147                         nodeRemLink(ntree, link);
148                 }
149         }
150         
151         BLI_remlink(lb, sock);
152         MEM_freeN(sock);
153 }
154
155 static bNodeSocket *verify_socket(ListBase *lb, bNodeSocketType *stype)
156 {
157         bNodeSocket *sock;
158         
159         for(sock= lb->first; sock; sock= sock->next) {
160                 /* both indices are zero for non-groups, otherwise it's a unique index */
161                 if(sock->to_index==stype->own_index)
162                         if(strncmp(sock->name, stype->name, NODE_MAXSTR)==0)
163                                 break;
164         }
165         if(sock) {
166                 sock->type= stype->type;                /* in future, read this from tydefs! */
167                 if(stype->limit==0) sock->limit= 0xFFF;
168                 else sock->limit= stype->limit;
169                 sock->ns.min= stype->min;
170                 sock->ns.max= stype->max;
171                 sock->tosock= stype->internsock;
172                 
173                 BLI_remlink(lb, sock);
174                 
175                 return sock;
176         }
177         else {
178                 return node_add_socket_type(NULL, stype);
179         }
180 }
181
182 static void verify_socket_list(bNodeTree *ntree, ListBase *lb, bNodeSocketType *stype_first)
183 {
184         bNodeSocketType *stype;
185         
186         /* no inputs anymore? */
187         if(stype_first==NULL) {
188                 while(lb->first)
189                         node_rem_socket(ntree, lb, lb->first);
190         }
191         else {
192                 /* step by step compare */
193                 stype= stype_first;
194                 while(stype->type != -1) {
195                         stype->sock= verify_socket(lb, stype);
196                         stype++;
197                 }
198                 /* leftovers are removed */
199                 while(lb->first)
200                         node_rem_socket(ntree, lb, lb->first);
201                 /* and we put back the verified sockets */
202                 stype= stype_first;
203                 while(stype->type != -1) {
204                         BLI_addtail(lb, stype->sock);
205                         stype++;
206                 }
207         }
208 }
209
210 void nodeVerifyType(bNodeTree *ntree, bNode *node)
211 {
212         bNodeType *ntype= node->typeinfo;
213         
214         if(ntype) {
215                 /* might add some other verify stuff here */
216                 
217                 verify_socket_list(ntree, &node->inputs, ntype->inputs);
218                 verify_socket_list(ntree, &node->outputs, ntype->outputs);
219         }
220 }
221
222 void ntreeVerifyTypes(bNodeTree *ntree)
223 {
224         bNode *node;
225         
226         /* commented out, in linux a 2nd initialize on a Scene ntree from a lib crashes... */
227 /*      if((ntree->init & NTREE_TYPE_INIT)==0) */
228                 ntreeInitTypes(ntree);
229         
230         /* check inputs and outputs, and remove or insert them */
231         for(node= ntree->nodes.first; node; node= node->next)
232                 nodeVerifyType(ntree, node);
233         
234 }
235
236 /* ************** Group stuff ********** */
237
238 bNodeType node_group_typeinfo= {
239         /* type code   */       NODE_GROUP,
240         /* name        */       "Group",
241         /* width+range */       120, 60, 200,
242         /* class+opts  */       NODE_CLASS_GROUP, NODE_OPTIONS,
243         /* input sock  */       NULL,
244         /* output sock */       NULL,
245         /* storage     */       "",
246         /* execfunc    */       NULL,
247         
248 };
249
250 /* tag internal sockets */
251 static void group_tag_internal_sockets(bNodeTree *ngroup)
252 {
253         bNode *node;
254         bNodeSocket *sock;
255         bNodeLink *link;
256         
257         /* clear intern tag, but check already for hidden sockets */
258         for(node= ngroup->nodes.first; node; node= node->next) {
259                 for(sock= node->inputs.first; sock; sock= sock->next)
260                         sock->intern= sock->flag & SOCK_HIDDEN;
261                 for(sock= node->outputs.first; sock; sock= sock->next)
262                         sock->intern= sock->flag & SOCK_HIDDEN;
263         }
264         /* set tag */
265         for(link= ngroup->links.first; link; link= link->next) {
266                 link->fromsock->intern= 1;
267                 link->tosock->intern= 1;
268         }
269         
270         /* remove link pointer to external links (only happens on create group) */
271         for(node= ngroup->nodes.first; node; node= node->next) {
272                 for(sock= node->inputs.first; sock; sock= sock->next)
273                         if(sock->intern==0)
274                                 sock->link= NULL;
275         }
276
277         /* set all intern sockets to own_index zero, makes sure that later use won't mixup */
278         for(node= ngroup->nodes.first; node; node= node->next) {
279                 for(sock= node->inputs.first; sock; sock= sock->next)
280                         if(sock->intern)
281                                 sock->own_index= 0;
282                 for(sock= node->outputs.first; sock; sock= sock->next)
283                         if(sock->intern)
284                                 sock->own_index= 0;
285         }
286 }
287
288 /* after editing group, new sockets are zero */
289 /* this routine ensures unique identifiers for zero sockets that are exposed */
290 static void group_verify_own_indices(bNodeTree *ngroup)
291 {
292         bNode *node;
293         bNodeSocket *sock;
294         
295         for(node= ngroup->nodes.first; node; node= node->next) {
296                 for(sock= node->inputs.first; sock; sock= sock->next)
297                         if(sock->own_index==0 && sock->intern==0)
298                                 sock->own_index= ++(ngroup->cur_index);
299                 for(sock= node->outputs.first; sock; sock= sock->next)
300                         if(sock->own_index==0 && sock->intern==0)
301                                 sock->own_index= ++(ngroup->cur_index);
302         }
303         //printf("internal index %d\n", ngroup->cur_index);
304 }
305
306
307 /* nodetrees can be used as groups, so we need typeinfo structs generated */
308 void ntreeMakeOwnType(bNodeTree *ngroup)
309 {
310         bNode *node;
311         bNodeSocket *sock;
312         int totin= 0, totout=0, a;
313
314         /* tags socket when internal linked */
315         group_tag_internal_sockets(ngroup);
316         
317         /* ensure all sockets have own unique id */
318         group_verify_own_indices(ngroup);
319         
320         /* counting stats */
321         for(node= ngroup->nodes.first; node; node= node->next) {
322                 if(node->type==NODE_GROUP)
323                         break;
324                 for(sock= node->inputs.first; sock; sock= sock->next)
325                         if(sock->intern==0) 
326                                 totin++;
327                 for(sock= node->outputs.first; sock; sock= sock->next)
328                         if(sock->intern==0) 
329                                 totout++;
330         }
331         /* debug: nodetrees in nodetrees not handled yet */
332         if(node) {
333                 printf("group in group, not supported yet\n");
334                 return;
335         }
336         
337         /* free own type struct */
338         if(ngroup->owntype) {
339                 if(ngroup->owntype->inputs)
340                         MEM_freeN(ngroup->owntype->inputs);
341                 if(ngroup->owntype->outputs)
342                         MEM_freeN(ngroup->owntype->outputs);
343                 MEM_freeN(ngroup->owntype);
344         }
345         
346         /* make own type struct */
347         ngroup->owntype= MEM_mallocN(sizeof(bNodeType), "group type");
348         *ngroup->owntype= node_group_typeinfo;
349         
350         /* input type arrays */
351         if(totin) {
352                 bNodeSocketType *stype;
353                 bNodeSocketType *inputs= MEM_mallocN(sizeof(bNodeSocketType)*(totin+1), "bNodeSocketType");
354                 a= 0;
355                 
356                 for(node= ngroup->nodes.first; node; node= node->next) {
357                         /* nodes are presumed fully verified, stype and socket list are in sync */
358                         stype= node->typeinfo->inputs;
359                         for(sock= node->inputs.first; sock; sock= sock->next, stype++) {
360                                 if(sock->intern==0) {
361                                         /* debug only print */
362                                         if(stype==NULL || stype->type==-1) printf("group verification error %s\n", ngroup->id.name);
363                                         
364                                         inputs[a]= *stype;
365                                         inputs[a].own_index= sock->own_index;
366                                         inputs[a].internsock= sock;     
367                                         a++;
368                                 }
369                         }
370                 }
371                 inputs[a].type= -1;     /* terminator code */
372                 ngroup->owntype->inputs= inputs;
373         }       
374         
375         /* output type arrays */
376         if(totout) {
377                 bNodeSocketType *stype;
378                 bNodeSocketType *outputs= MEM_mallocN(sizeof(bNodeSocketType)*(totout+1), "bNodeSocketType");
379                 a= 0;
380                 
381                 for(node= ngroup->nodes.first; node; node= node->next) {
382                         /* nodes are presumed fully verified, stype and socket list are in sync */
383                         stype= node->typeinfo->outputs;
384                         for(sock= node->outputs.first; sock; sock= sock->next, stype++) {
385                                 if(sock->intern==0) {
386                                         /* debug only print */
387                                         if(stype==NULL || stype->type==-1) printf("group verification error %s\n", ngroup->id.name);
388                                         
389                                         outputs[a]= *stype;
390                                         outputs[a].own_index= sock->own_index;
391                                         outputs[a].internsock= sock;    
392                                         a++;
393                                 }
394                         }
395                 }
396                 outputs[a].type= -1;    /* terminator code */
397                 ngroup->owntype->outputs= outputs;
398         }
399         
400         /* voila, the nodetree has the full definition for generating group-node instances! */
401 }
402
403
404 static bNodeSocket *groupnode_find_tosock(bNode *gnode, int index)
405 {
406         bNodeSocket *sock;
407         
408         for(sock= gnode->inputs.first; sock; sock= sock->next)
409                 if(sock->to_index==index)
410                         return sock;
411         return NULL;
412 }
413
414 static bNodeSocket *groupnode_find_fromsock(bNode *gnode, int index)
415 {
416         bNodeSocket *sock;
417         
418         for(sock= gnode->outputs.first; sock; sock= sock->next)
419                 if(sock->to_index==index)
420                         return sock;
421         return NULL;
422 }
423
424 bNode *nodeMakeGroupFromSelected(bNodeTree *ntree)
425 {
426         bNodeLink *link, *linkn;
427         bNode *node, *gnode, *nextn;
428         bNodeSocket *sock;
429         bNodeTree *ngroup;
430         float min[2], max[2];
431         int totnode=0;
432         
433         INIT_MINMAX2(min, max);
434         
435         /* is there something to group? also do some clearing */
436         for(node= ntree->nodes.first; node; node= node->next) {
437                 if(node->flag & NODE_SELECT) {
438                         /* no groups in groups */
439                         if(node->type==NODE_GROUP)
440                                 return NULL;
441                         DO_MINMAX2( (&node->locx), min, max);
442                         totnode++;
443                 }
444                 node->done= 0;
445         }
446         if(totnode==0) return NULL;
447         
448         /* check if all connections are OK, no unselected node has both
449                 inputs and outputs to a selection */
450         for(link= ntree->links.first; link; link= link->next) {
451                 if(link->fromnode->flag & NODE_SELECT)
452                         link->tonode->done |= 1;
453                 if(link->tonode->flag & NODE_SELECT)
454                         link->fromnode->done |= 2;
455         }       
456         
457         for(node= ntree->nodes.first; node; node= node->next) {
458                 if((node->flag & NODE_SELECT)==0)
459                         if(node->done==3)
460                                 break;
461         }
462         if(node) 
463                 return NULL;
464         
465         /* OK! new nodetree */
466         ngroup= alloc_libblock(&G.main->nodetree, ID_NT, "NodeGroup");
467         ngroup->type= ntree->type;
468         ngroup->alltypes= ntree->alltypes;
469         
470         /* move nodes over */
471         for(node= ntree->nodes.first; node; node= nextn) {
472                 nextn= node->next;
473                 if(node->flag & NODE_SELECT) {
474                         BLI_remlink(&ntree->nodes, node);
475                         BLI_addtail(&ngroup->nodes, node);
476                         node->locx-= 0.5f*(min[0]+max[0]);
477                         node->locy-= 0.5f*(min[1]+max[1]);
478                 }
479         }
480
481         /* move links over */
482         for(link= ntree->links.first; link; link= linkn) {
483                 linkn= link->next;
484                 if(link->fromnode->flag & link->tonode->flag & NODE_SELECT) {
485                         BLI_remlink(&ntree->links, link);
486                         BLI_addtail(&ngroup->links, link);
487                 }
488         }
489         
490         /* now we can make own group typeinfo */
491         ntreeMakeOwnType(ngroup);
492         
493         /* make group node */
494         gnode= nodeAddNodeType(ntree, NODE_GROUP, ngroup);
495         gnode->locx= 0.5f*(min[0]+max[0]);
496         gnode->locy= 0.5f*(min[1]+max[1]);
497         
498         /* relink external sockets */
499         for(link= ntree->links.first; link; link= linkn) {
500                 linkn= link->next;
501                 
502                 if(link->tonode->flag & NODE_SELECT) {
503                         link->tonode= gnode;
504                         sock= groupnode_find_tosock(gnode, link->tosock->own_index);
505                         if(sock==NULL) {
506                                 nodeRemLink(ntree, link);       
507                                 printf("Removed link, cannot mix internal and external sockets in group\n");
508                         }
509                         else link->tosock= sock;
510                 }
511                 else if(link->fromnode->flag & NODE_SELECT) {
512                         link->fromnode= gnode;
513                         sock= groupnode_find_fromsock(gnode, link->fromsock->own_index);
514                         if(sock==NULL) {
515                                 nodeRemLink(ntree, link);       
516                                 printf("Removed link, cannot mix internal and external sockets in group\n");
517                         }
518                         else link->fromsock= sock;
519                 }
520         }
521         
522         /* initialize variables of unused input sockets */
523         for(node= ngroup->nodes.first; node; node= node->next) {
524                 for(sock= node->inputs.first; sock; sock= sock->next) {
525                         if(sock->intern==0) {
526                                 bNodeSocket *nsock= groupnode_find_tosock(gnode, sock->own_index);
527                                 if(nsock) {
528                                         QUATCOPY(nsock->ns.vec, sock->ns.vec);
529                                 }
530                         }
531                 }
532         }
533         return gnode;
534 }
535
536 /* note: ungroup: group_indices zero! */
537
538 /* here's a nasty little one, need to check users... */
539 /* should become callbackable... */
540 void nodeVerifyGroup(bNodeTree *ngroup)
541 {
542         
543         /* group changed, so we rebuild the type definition */
544         ntreeMakeOwnType(ngroup);
545         
546         if(ngroup->type==NTREE_SHADER) {
547                 Material *ma;
548                 for(ma= G.main->mat.first; ma; ma= ma->id.next) {
549                         if(ma->nodetree) {
550                                 bNode *node;
551                                 
552                                 /* find if group is in tree */
553                                 for(node= ma->nodetree->nodes.first; node; node= node->next)
554                                         if(node->id == (ID *)ngroup)
555                                                 break;
556                                 
557                                 if(node) {
558                                         /* set all type pointers OK */
559                                         ntreeInitTypes(ma->nodetree);
560                                         
561                                         for(node= ma->nodetree->nodes.first; node; node= node->next)
562                                                 if(node->id == (ID *)ngroup)
563                                                         nodeVerifyType(ma->nodetree, node);
564                                 }
565                         }
566                 }
567         }
568         else if(ngroup->type==NTREE_COMPOSIT) {
569                 Scene *sce;
570                 for(sce= G.main->scene.first; sce; sce= sce->id.next) {
571                         if(sce->nodetree) {
572                                 bNode *node;
573                                 
574                                 /* find if group is in tree */
575                                 for(node= sce->nodetree->nodes.first; node; node= node->next)
576                                         if(node->id == (ID *)ngroup)
577                                                 break;
578                                 
579                                 if(node) {
580                                         /* set all type pointers OK */
581                                         ntreeInitTypes(sce->nodetree);
582                                         
583                                         for(node= sce->nodetree->nodes.first; node; node= node->next)
584                                                 if(node->id == (ID *)ngroup)
585                                                         nodeVerifyType(sce->nodetree, node);
586                                 }
587                         }
588                 }
589         }
590 }
591
592 /* also to check all users of groups. Now only used in editor for hide/unhide */
593 /* should become callbackable? */
594 void nodeGroupSocketUseFlags(bNodeTree *ngroup)
595 {
596         bNode *node;
597         bNodeSocket *sock;
598
599         /* clear flags */
600         for(node= ngroup->nodes.first; node; node= node->next) {
601                 for(sock= node->inputs.first; sock; sock= sock->next)
602                         sock->flag &= ~SOCK_IN_USE;
603                 for(sock= node->outputs.first; sock; sock= sock->next)
604                         sock->flag &= ~SOCK_IN_USE;
605         }
606         
607         /* tag all thats in use */
608         if(ngroup->type==NTREE_SHADER) {
609                 Material *ma;
610                 for(ma= G.main->mat.first; ma; ma= ma->id.next) {
611                         if(ma->nodetree) {
612                                 for(node= ma->nodetree->nodes.first; node; node= node->next) {
613                                         if(node->id==(ID *)ngroup) {
614                                                 for(sock= node->inputs.first; sock; sock= sock->next)
615                                                         if(sock->link)
616                                                                 if(sock->tosock) 
617                                                                         sock->tosock->flag |= SOCK_IN_USE;
618                                                 for(sock= node->outputs.first; sock; sock= sock->next)
619                                                         if(nodeCountSocketLinks(ma->nodetree, sock))
620                                                                 if(sock->tosock) 
621                                                                         sock->tosock->flag |= SOCK_IN_USE;
622                                         }
623                                 }
624                         }
625                 }
626         }
627         else if(ngroup->type==NTREE_COMPOSIT) {
628                 Scene *sce;
629                 for(sce= G.main->scene.first; sce; sce= sce->id.next) {
630                         if(sce->nodetree) {
631                                 for(node= sce->nodetree->nodes.first; node; node= node->next) {
632                                         if(node->id==(ID *)ngroup) {
633                                                 for(sock= node->inputs.first; sock; sock= sock->next)
634                                                         if(sock->link)
635                                                                 if(sock->tosock) 
636                                                                         sock->tosock->flag |= SOCK_IN_USE;
637                                                 for(sock= node->outputs.first; sock; sock= sock->next)
638                                                         if(nodeCountSocketLinks(sce->nodetree, sock))
639                                                                 if(sock->tosock) 
640                                                                         sock->tosock->flag |= SOCK_IN_USE;
641                                         }
642                                 }
643                         }
644                 }
645         }
646 }
647
648 static void find_node_with_socket(bNodeTree *ntree, bNodeSocket *sock, bNode **nodep, int *sockindex)
649 {
650         bNode *node;
651         bNodeSocket *tsock;
652         int index= 0;
653         
654         for(node= ntree->nodes.first; node; node= node->next) {
655                 for(index=0, tsock= node->inputs.first; tsock; tsock= tsock->next, index++)
656                         if(tsock==sock)
657                                 break;
658                 if(tsock)
659                         break;
660                 for(index=0, tsock= node->outputs.first; tsock; tsock= tsock->next, index++)
661                         if(tsock==sock)
662                                 break;
663                 if(tsock)
664                         break;
665         }
666         if(node) {
667                 *nodep= node;
668                 *sockindex= index;
669         }
670         else {
671                 *nodep= NULL;
672         }
673 }
674
675 /* returns 1 if its OK */
676 int nodeGroupUnGroup(bNodeTree *ntree, bNode *gnode)
677 {
678         bNodeLink *link, *linkn;
679         bNode *node, *nextn;
680         bNodeTree *ngroup, *wgroup;
681         int index;
682         
683         ngroup= (bNodeTree *)gnode->id;
684         if(ngroup==NULL) return 0;
685         
686         /* clear new pointers, set in copytree */
687         for(node= ntree->nodes.first; node; node= node->next)
688                 node->new_node= NULL;
689
690         wgroup= ntreeCopyTree(ngroup, 0);
691         
692         /* add the nodes into the ntree */
693         for(node= wgroup->nodes.first; node; node= nextn) {
694                 nextn= node->next;
695                 BLI_remlink(&wgroup->nodes, node);
696                 BLI_addtail(&ntree->nodes, node);
697                 node->locx+= gnode->locx;
698                 node->locy+= gnode->locy;
699                 node->flag |= NODE_SELECT;
700         }
701         /* and the internal links */
702         for(link= wgroup->links.first; link; link= linkn) {
703                 linkn= link->next;
704                 BLI_remlink(&wgroup->links, link);
705                 BLI_addtail(&ntree->links, link);
706         }
707
708         /* restore links to and from the gnode */
709         for(link= ntree->links.first; link; link= link->next) {
710                 if(link->tonode==gnode) {
711                         /* link->tosock->tosock is on the node we look for */
712                         find_node_with_socket(ngroup, link->tosock->tosock, &nextn, &index);
713                         if(nextn==NULL) printf("wrong stuff!\n");
714                         else if(nextn->new_node==NULL) printf("wrong stuff too!\n");
715                         else {
716                                 link->tonode= nextn->new_node;
717                                 link->tosock= BLI_findlink(&link->tonode->inputs, index);
718                         }
719                 }
720                 else if(link->fromnode==gnode) {
721                         /* link->fromsock->tosock is on the node we look for */
722                         find_node_with_socket(ngroup, link->fromsock->tosock, &nextn, &index);
723                         if(nextn==NULL) printf("1 wrong stuff!\n");
724                         else if(nextn->new_node==NULL) printf("1 wrong stuff too!\n");
725                         else {
726                                 link->fromnode= nextn->new_node;
727                                 link->fromsock= BLI_findlink(&link->fromnode->outputs, index);
728                         }
729                 }
730         }
731         
732         /* remove the gnode & work tree */
733         free_libblock(&G.main->nodetree, wgroup);
734         
735         nodeFreeNode(ntree, gnode);
736         
737         /* solve order goes fine, but the level tags not... doing it twice works for now. solve this once */
738         ntreeSolveOrder(ntree);
739         ntreeSolveOrder(ntree);
740
741         return 1;
742 }
743
744 /* ************** Add stuff ********** */
745
746 bNode *nodeAddNodeType(bNodeTree *ntree, int type, bNodeTree *ngroup)
747 {
748         bNode *node;
749         bNodeType *ntype= node_get_type(ntree, type, ngroup);
750         bNodeSocketType *stype;
751         
752         node= MEM_callocN(sizeof(bNode), "new node");
753         BLI_addtail(&ntree->nodes, node);
754         node->typeinfo= ntype;
755         
756         if(ngroup)
757                 BLI_strncpy(node->name, ngroup->id.name+2, NODE_MAXSTR);
758         else
759                 BLI_strncpy(node->name, ntype->name, NODE_MAXSTR);
760         node->type= ntype->type;
761         node->flag= NODE_SELECT|ntype->flag;
762         node->width= ntype->width;
763         node->miniwidth= 42.0f;         /* small value only, allows print of first chars */
764         
765         if(type==NODE_GROUP)
766                 node->id= (ID *)ngroup;
767         
768         if(ntype->inputs) {
769                 stype= ntype->inputs;
770                 while(stype->type != -1) {
771                         node_add_socket_type(&node->inputs, stype);
772                         stype++;
773                 }
774         }
775         if(ntype->outputs) {
776                 stype= ntype->outputs;
777                 while(stype->type != -1) {
778                         node_add_socket_type(&node->outputs, stype);
779                         stype++;
780                 }
781         }
782         
783         /* need init handler later? */
784    /* got it-bob*/
785    if(ntype->initfunc!=NULL)
786       ntype->initfunc(node);
787         
788         return node;
789 }
790
791 /* keep socket listorder identical, for copying links */
792 /* ntree is the target tree */
793 bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node)
794 {
795         bNode *nnode= MEM_callocN(sizeof(bNode), "dupli node");
796         bNodeSocket *sock;
797
798         *nnode= *node;
799         BLI_addtail(&ntree->nodes, nnode);
800         
801         duplicatelist(&nnode->inputs, &node->inputs);
802         for(sock= nnode->inputs.first; sock; sock= sock->next)
803                 sock->own_index= 0;
804         
805         duplicatelist(&nnode->outputs, &node->outputs);
806         for(sock= nnode->outputs.first; sock; sock= sock->next) {
807                 sock->own_index= 0;
808                 sock->stack_index= 0;
809                 sock->ns.data= NULL;
810         }
811         
812         if(nnode->id)
813                 nnode->id->us++;
814         
815         if(nnode->storage) {
816                 /* another candidate for handlerizing! */
817                 if(ntree->type==NTREE_SHADER) {
818                         if(node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB)
819                                 nnode->storage= curvemapping_copy(node->storage);
820                         else 
821                                 nnode->storage= MEM_dupallocN(nnode->storage);
822                 }
823                 else if(ntree->type==NTREE_COMPOSIT) {
824                         if(ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB))
825                                 nnode->storage= curvemapping_copy(node->storage);
826                         else 
827                                 nnode->storage= MEM_dupallocN(nnode->storage);
828                 }
829                 else 
830                         nnode->storage= MEM_dupallocN(nnode->storage);
831         }
832         
833         node->new_node= nnode;
834         nnode->new_node= NULL;
835         nnode->preview= NULL;
836
837         return nnode;
838 }
839
840 bNodeLink *nodeAddLink(bNodeTree *ntree, bNode *fromnode, bNodeSocket *fromsock, bNode *tonode, bNodeSocket *tosock)
841 {
842         bNodeLink *link= MEM_callocN(sizeof(bNodeLink), "link");
843         
844         BLI_addtail(&ntree->links, link);
845         link->fromnode= fromnode;
846         link->fromsock= fromsock;
847         link->tonode= tonode;
848         link->tosock= tosock;
849         
850         return link;
851 }
852
853 void nodeRemLink(bNodeTree *ntree, bNodeLink *link)
854 {
855         BLI_remlink(&ntree->links, link);
856         if(link->tosock)
857                 link->tosock->link= NULL;
858         MEM_freeN(link);
859 }
860
861
862 bNodeTree *ntreeAddTree(int type)
863 {
864         bNodeTree *ntree= MEM_callocN(sizeof(bNodeTree), "new node tree");
865         ntree->type= type;
866         
867         ntreeInitTypes(ntree);
868         return ntree;
869 }
870
871 bNodeTree *ntreeCopyTree(bNodeTree *ntree, int internal_select)
872 {
873         bNodeTree *newtree;
874         bNode *node, *nnode, *last;
875         bNodeLink *link, *nlink;
876         bNodeSocket *sock;
877         int a;
878         
879         if(ntree==NULL) return NULL;
880         
881         if(internal_select==0) {
882                 /* is ntree part of library? */
883                 for(newtree=G.main->nodetree.first; newtree; newtree= newtree->id.next)
884                         if(newtree==ntree) break;
885                 if(newtree)
886                         newtree= copy_libblock(ntree);
887                 else
888                         newtree= MEM_dupallocN(ntree);
889                 newtree->nodes.first= newtree->nodes.last= NULL;
890                 newtree->links.first= newtree->links.last= NULL;
891         }
892         else
893                 newtree= ntree;
894         
895         last= ntree->nodes.last;
896         for(node= ntree->nodes.first; node; node= node->next) {
897                 
898                 node->new_node= NULL;
899                 if(internal_select==0 || (node->flag & NODE_SELECT)) {
900                         nnode= nodeCopyNode(newtree, node);     /* sets node->new */
901                         if(internal_select) {
902                                 node->flag &= ~NODE_SELECT;
903                                 nnode->flag |= NODE_SELECT;
904                         }
905                         node->flag &= ~NODE_ACTIVE;
906                 }
907                 if(node==last) break;
908         }
909         
910         /* check for copying links */
911         for(link= ntree->links.first; link; link= link->next) {
912                 if(link->fromnode->new_node && link->tonode->new_node) {
913                         nlink= nodeAddLink(newtree, link->fromnode->new_node, NULL, link->tonode->new_node, NULL);
914                         /* sockets were copied in order */
915                         for(a=0, sock= link->fromnode->outputs.first; sock; sock= sock->next, a++) {
916                                 if(sock==link->fromsock)
917                                         break;
918                         }
919                         nlink->fromsock= BLI_findlink(&link->fromnode->new_node->outputs, a);
920                         
921                         for(a=0, sock= link->tonode->inputs.first; sock; sock= sock->next, a++) {
922                                 if(sock==link->tosock)
923                                         break;
924                         }
925                         nlink->tosock= BLI_findlink(&link->tonode->new_node->inputs, a);
926                 }
927         }
928         
929         /* own type definition for group usage */
930         if(internal_select==0) {
931                 if(ntree->owntype) {
932                         newtree->owntype= MEM_dupallocN(ntree->owntype);
933                         if(ntree->owntype->inputs)
934                                 newtree->owntype->inputs= MEM_dupallocN(ntree->owntype->inputs);
935                         if(ntree->owntype->outputs)
936                                 newtree->owntype->outputs= MEM_dupallocN(ntree->owntype->outputs);
937                 }
938         }
939         /* weird this is required... there seem to be link pointers wrong still? */
940         /* anyhoo, doing this solves crashes on copying entire tree (copy scene) and delete nodes */
941         ntreeSolveOrder(newtree);
942
943         return newtree;
944 }
945
946 /* ************** Free stuff ********** */
947
948 /* goes over entire tree */
949 static void node_unlink_node(bNodeTree *ntree, bNode *node)
950 {
951         bNodeLink *link, *next;
952         bNodeSocket *sock;
953         ListBase *lb;
954         
955         for(link= ntree->links.first; link; link= next) {
956                 next= link->next;
957                 
958                 if(link->fromnode==node) {
959                         lb= &node->outputs;
960                         NodeTagChanged(ntree, link->tonode);
961                 }
962                 else if(link->tonode==node)
963                         lb= &node->inputs;
964                 else
965                         lb= NULL;
966
967                 if(lb) {
968                         for(sock= lb->first; sock; sock= sock->next) {
969                                 if(link->fromsock==sock || link->tosock==sock)
970                                         break;
971                         }
972                         if(sock) {
973                                 nodeRemLink(ntree, link);
974                         }
975                 }
976         }
977 }
978
979 static void composit_free_node_cache(bNode *node)
980 {
981         bNodeSocket *sock;
982         
983         for(sock= node->outputs.first; sock; sock= sock->next) {
984                 if(sock->ns.data) {
985                         free_compbuf(sock->ns.data);
986                         sock->ns.data= NULL;
987                 }
988         }
989 }
990
991 void nodeFreeNode(bNodeTree *ntree, bNode *node)
992 {
993         node_unlink_node(ntree, node);
994         BLI_remlink(&ntree->nodes, node);
995
996         /* since it is called while free database, node->id is undefined */
997         
998         if(ntree->type==NTREE_COMPOSIT)
999                 composit_free_node_cache(node);
1000         BLI_freelistN(&node->inputs);
1001         BLI_freelistN(&node->outputs);
1002         
1003         if(node->preview) {
1004                 if(node->preview->rect)
1005                         MEM_freeN(node->preview->rect);
1006                 MEM_freeN(node->preview);
1007         }
1008         if(node->storage) {
1009                 /* could be handlerized at some point, now only 1 exception still */
1010                 if(ntree->type==NTREE_SHADER) {
1011                         if(node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB)
1012                                 curvemapping_free(node->storage);
1013                         else 
1014                                 MEM_freeN(node->storage);
1015                 }
1016                 else if(ntree->type==NTREE_COMPOSIT) {
1017                         if(ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB))
1018                                 curvemapping_free(node->storage);
1019                         else 
1020                                 MEM_freeN(node->storage);
1021                 }
1022                 else 
1023                         MEM_freeN(node->storage);
1024         }
1025         MEM_freeN(node);
1026 }
1027
1028 /* do not free ntree itself here, free_libblock calls this function too */
1029 void ntreeFreeTree(bNodeTree *ntree)
1030 {
1031         bNode *node, *next;
1032         
1033         if(ntree==NULL) return;
1034         
1035         ntreeEndExecTree(ntree);        /* checks for if it is still initialized */
1036         
1037         BLI_freelistN(&ntree->links);   /* do first, then unlink_node goes fast */
1038         
1039         for(node= ntree->nodes.first; node; node= next) {
1040                 next= node->next;
1041                 nodeFreeNode(ntree, node);
1042         }
1043         
1044         if(ntree->owntype) {
1045                 if(ntree->owntype->inputs)
1046                         MEM_freeN(ntree->owntype->inputs);
1047                 if(ntree->owntype->outputs)
1048                         MEM_freeN(ntree->owntype->outputs);
1049                 MEM_freeN(ntree->owntype);
1050         }
1051 }
1052
1053 void ntreeFreeCache(bNodeTree *ntree)
1054 {
1055         bNode *node;
1056         
1057         if(ntree==NULL) return;
1058
1059         if(ntree->type==NTREE_COMPOSIT)
1060                 for(node= ntree->nodes.first; node; node= node->next)
1061                         composit_free_node_cache(node);
1062
1063 }
1064
1065 void ntreeMakeLocal(bNodeTree *ntree)
1066 {
1067         int local=0, lib=0;
1068         
1069         /* - only lib users: do nothing
1070             * - only local users: set flag
1071             * - mixed: make copy
1072             */
1073         
1074         if(ntree->id.lib==NULL) return;
1075         if(ntree->id.us==1) {
1076                 ntree->id.lib= 0;
1077                 ntree->id.flag= LIB_LOCAL;
1078                 new_id(0, (ID *)ntree, 0);
1079                 return;
1080         }
1081         
1082         /* now check users of groups... again typedepending, callback... */
1083         if(ntree->type==NTREE_SHADER) {
1084                 Material *ma;
1085                 for(ma= G.main->mat.first; ma; ma= ma->id.next) {
1086                         if(ma->nodetree) {
1087                                 bNode *node;
1088                                 
1089                                 /* find if group is in tree */
1090                                 for(node= ma->nodetree->nodes.first; node; node= node->next) {
1091                                         if(node->id == (ID *)ntree) {
1092                                                 if(ma->id.lib) lib= 1;
1093                                                 else local= 1;
1094                                         }
1095                                 }
1096                         }
1097                 }
1098         }
1099         else if(ntree->type==NTREE_COMPOSIT) {
1100                 Scene *sce;
1101                 for(sce= G.main->scene.first; sce; sce= sce->id.next) {
1102                         if(sce->nodetree) {
1103                                 bNode *node;
1104                                 
1105                                 /* find if group is in tree */
1106                                 for(node= sce->nodetree->nodes.first; node; node= node->next) {
1107                                         if(node->id == (ID *)ntree) {
1108                                                 if(sce->id.lib) lib= 1;
1109                                                 else local= 1;
1110                                         }
1111                                 }
1112                         }
1113                 }
1114         }
1115         
1116         /* if all users are local, we simply make tree local */
1117         if(local && lib==0) {
1118                 ntree->id.lib= NULL;
1119                 ntree->id.flag= LIB_LOCAL;
1120                 new_id(0, (ID *)ntree, 0);
1121         }
1122         else if(local && lib) {
1123                 /* this is the mixed case, we copy the tree and assign it to local users */
1124                 bNodeTree *newtree= ntreeCopyTree(ntree, 0);
1125                 
1126                 newtree->id.us= 0;
1127                 
1128                 if(ntree->type==NTREE_SHADER) {
1129                         Material *ma;
1130                         for(ma= G.main->mat.first; ma; ma= ma->id.next) {
1131                                 if(ma->nodetree) {
1132                                         bNode *node;
1133                                         
1134                                         /* find if group is in tree */
1135                                         for(node= ma->nodetree->nodes.first; node; node= node->next) {
1136                                                 if(node->id == (ID *)ntree) {
1137                                                         if(ma->id.lib==NULL) {
1138                                                                 node->id= &newtree->id;
1139                                                                 newtree->id.us++;
1140                                                                 ntree->id.us--;
1141                                                         }
1142                                                 }
1143                                         }
1144                                 }
1145                         }
1146                 }
1147                 else if(ntree->type==NTREE_COMPOSIT) {
1148                         Scene *sce;
1149                         for(sce= G.main->scene.first; sce; sce= sce->id.next) {
1150                                 if(sce->nodetree) {
1151                                         bNode *node;
1152                                         
1153                                         /* find if group is in tree */
1154                                         for(node= sce->nodetree->nodes.first; node; node= node->next) {
1155                                                 if(node->id == (ID *)ntree) {
1156                                                         if(sce->id.lib==NULL) {
1157                                                                 node->id= &newtree->id;
1158                                                                 newtree->id.us++;
1159                                                                 ntree->id.us--;
1160                                                         }
1161                                                 }
1162                                         }
1163                                 }
1164                         }
1165                 }
1166         }
1167 }
1168
1169
1170 /* ************ find stuff *************** */
1171
1172 static int ntreeHasType(bNodeTree *ntree, int type)
1173 {
1174         bNode *node;
1175         
1176         if(ntree)
1177                 for(node= ntree->nodes.first; node; node= node->next)
1178                         if(node->type == type)
1179                                 return 1;
1180         return 0;
1181 }
1182
1183 bNodeLink *nodeFindLink(bNodeTree *ntree, bNodeSocket *from, bNodeSocket *to)
1184 {
1185         bNodeLink *link;
1186         
1187         for(link= ntree->links.first; link; link= link->next) {
1188                 if(link->fromsock==from && link->tosock==to)
1189                         return link;
1190                 if(link->fromsock==to && link->tosock==from)    /* hrms? */
1191                         return link;
1192         }
1193         return NULL;
1194 }
1195
1196 int nodeCountSocketLinks(bNodeTree *ntree, bNodeSocket *sock)
1197 {
1198         bNodeLink *link;
1199         int tot= 0;
1200         
1201         for(link= ntree->links.first; link; link= link->next) {
1202                 if(link->fromsock==sock || link->tosock==sock)
1203                         tot++;
1204         }
1205         return tot;
1206 }
1207
1208 bNode *nodeGetActive(bNodeTree *ntree)
1209 {
1210         bNode *node;
1211         
1212         if(ntree==NULL) return NULL;
1213         
1214         for(node= ntree->nodes.first; node; node= node->next)
1215                 if(node->flag & NODE_ACTIVE)
1216                         break;
1217         return node;
1218 }
1219
1220 /* two active flags, ID nodes have special flag for buttons display */
1221 bNode *nodeGetActiveID(bNodeTree *ntree, short idtype)
1222 {
1223         bNode *node;
1224         
1225         if(ntree==NULL) return NULL;
1226         
1227         for(node= ntree->nodes.first; node; node= node->next)
1228                 if(node->id && GS(node->id->name)==idtype)
1229                         if(node->flag & NODE_ACTIVE_ID)
1230                                 break;
1231         return node;
1232 }
1233
1234 /* two active flags, ID nodes have special flag for buttons display */
1235 void nodeClearActiveID(bNodeTree *ntree, short idtype)
1236 {
1237         bNode *node;
1238         
1239         if(ntree==NULL) return;
1240         
1241         for(node= ntree->nodes.first; node; node= node->next)
1242                 if(node->id && GS(node->id->name)==idtype)
1243                         node->flag &= ~NODE_ACTIVE_ID;
1244 }
1245
1246 /* two active flags, ID nodes have special flag for buttons display */
1247 void nodeSetActive(bNodeTree *ntree, bNode *node)
1248 {
1249         bNode *tnode;
1250         
1251         /* make sure only one node is active, and only one per ID type */
1252         for(tnode= ntree->nodes.first; tnode; tnode= tnode->next) {
1253                 tnode->flag &= ~NODE_ACTIVE;
1254                 
1255                 if(node->id && tnode->id) {
1256                         if(GS(node->id->name) == GS(tnode->id->name))
1257                                 tnode->flag &= ~NODE_ACTIVE_ID;
1258                 }
1259         }
1260         
1261         node->flag |= NODE_ACTIVE;
1262         if(node->id)
1263                 node->flag |= NODE_ACTIVE_ID;
1264 }
1265
1266 /* use flags are not persistant yet, groups might need different tagging, so we do it each time
1267    when we need to get this info */
1268 void ntreeSocketUseFlags(bNodeTree *ntree)
1269 {
1270         bNode *node;
1271         bNodeSocket *sock;
1272         bNodeLink *link;
1273         
1274         /* clear flags */
1275         for(node= ntree->nodes.first; node; node= node->next) {
1276                 for(sock= node->inputs.first; sock; sock= sock->next)
1277                         sock->flag &= ~SOCK_IN_USE;
1278                 for(sock= node->outputs.first; sock; sock= sock->next)
1279                         sock->flag &= ~SOCK_IN_USE;
1280         }
1281         
1282         /* tag all thats in use */
1283         for(link= ntree->links.first; link; link= link->next) {
1284                 link->fromsock->flag |= SOCK_IN_USE;
1285                 link->tosock->flag |= SOCK_IN_USE;
1286         }
1287 }
1288
1289 /* ************** dependency stuff *********** */
1290
1291 /* node is guaranteed to be not checked before */
1292 static int node_recurs_check(bNode *node, bNode ***nsort, int level)
1293 {
1294         bNode *fromnode;
1295         bNodeSocket *sock;
1296         int has_inputlinks= 0;
1297         
1298         node->done= 1;
1299         level++;
1300         
1301         for(sock= node->inputs.first; sock; sock= sock->next) {
1302                 if(sock->link) {
1303                         has_inputlinks= 1;
1304                         fromnode= sock->link->fromnode;
1305                         if(fromnode->done==0) {
1306                                 fromnode->level= node_recurs_check(fromnode, nsort, level);
1307                         }
1308                 }
1309         }
1310 //      printf("node sort %s level %d\n", node->name, level);
1311         **nsort= node;
1312         (*nsort)++;
1313         
1314         if(has_inputlinks)
1315                 return level;
1316         else 
1317                 return 0xFFF;
1318 }
1319
1320 void ntreeSolveOrder(bNodeTree *ntree)
1321 {
1322         bNode *node, **nodesort, **nsort;
1323         bNodeSocket *sock;
1324         bNodeLink *link;
1325         int a, totnode=0;
1326         
1327         /* the solve-order is called on each tree change, so we should be sure no exec can be running */
1328         ntreeEndExecTree(ntree);
1329
1330         /* set links pointers the input sockets, to find dependencies */
1331         /* first clear data */
1332         for(node= ntree->nodes.first; node; node= node->next) {
1333                 node->done= 0;
1334                 totnode++;
1335                 for(sock= node->inputs.first; sock; sock= sock->next)
1336                         sock->link= NULL;
1337         }
1338         if(totnode==0)
1339                 return;
1340         
1341         for(link= ntree->links.first; link; link= link->next) {
1342                 link->tosock->link= link;
1343         }
1344         
1345         nsort= nodesort= MEM_callocN(totnode*sizeof(void *), "sorted node array");
1346         
1347         /* recursive check */
1348         for(node= ntree->nodes.first; node; node= node->next) {
1349                 if(node->done==0) {
1350                         node->level= node_recurs_check(node, &nsort, 0);
1351                 }
1352         }
1353         
1354         /* re-insert nodes in order, first a paranoia check */
1355         for(a=0; a<totnode; a++) {
1356                 if(nodesort[a]==NULL)
1357                         break;
1358         }
1359         if(a<totnode)
1360                 printf("sort error in node tree");
1361         else {
1362                 ntree->nodes.first= ntree->nodes.last= NULL;
1363                 for(a=0; a<totnode; a++)
1364                         BLI_addtail(&ntree->nodes, nodesort[a]);
1365         }
1366         
1367         MEM_freeN(nodesort);
1368         
1369         /* find the active outputs, might become tree type dependant handler */
1370         for(node= ntree->nodes.first; node; node= node->next) {
1371                 if(node->typeinfo->nclass==NODE_CLASS_OUTPUT) {
1372                         bNode *tnode;
1373                         int output= 0;
1374                         
1375                         /* we need a check for which output node should be tagged like this, below an exception */
1376                         if(node->type==CMP_NODE_OUTPUT_FILE)
1377                            continue;
1378                            
1379                         /* there is more types having output class, each one is checked */
1380                         for(tnode= ntree->nodes.first; tnode; tnode= tnode->next) {
1381                                 if(tnode->typeinfo->nclass==NODE_CLASS_OUTPUT) {
1382                                         if(tnode->type==node->type) {
1383                                                 if(tnode->flag & NODE_DO_OUTPUT) {
1384                                                         output++;
1385                                                         if(output>1)
1386                                                                 tnode->flag &= ~NODE_DO_OUTPUT;
1387                                                 }
1388                                         }
1389                                 }
1390                         }
1391                         if(output==0)
1392                                 node->flag |= NODE_DO_OUTPUT;
1393                 }
1394         }
1395         
1396         /* here we could recursively set which nodes have to be done,
1397                 might be different for editor or for "real" use... */
1398 }
1399
1400 /* should be callback! */
1401 void NodeTagChanged(bNodeTree *ntree, bNode *node)
1402 {
1403         if(ntree->type==NTREE_COMPOSIT) {
1404                 bNodeSocket *sock;
1405
1406                 for(sock= node->outputs.first; sock; sock= sock->next) {
1407                         if(sock->ns.data) {
1408                                 free_compbuf(sock->ns.data);
1409                                 sock->ns.data= NULL;
1410                                 
1411                                 //if(node->preview && node->preview->rect) {
1412                                 //      MEM_freeN(node->preview->rect);
1413                                 //      node->preview->rect= NULL;
1414                                 //}
1415                                         
1416                         }
1417                 }
1418                 node->need_exec= 1;
1419         }
1420 }
1421
1422 void NodeTagIDChanged(bNodeTree *ntree, ID *id)
1423 {
1424         if(id==NULL)
1425                 return;
1426         
1427         if(ntree->type==NTREE_COMPOSIT) {
1428                 bNode *node;
1429                 
1430                 for(node= ntree->nodes.first; node; node= node->next)
1431                         if(node->id==id)
1432                                 NodeTagChanged(ntree, node);
1433         }
1434 }
1435
1436
1437 /* *************** preview *********** */
1438
1439 /* if node->preview, then we assume the rect to exist */
1440
1441 static void nodeInitPreview(bNode *node, int xsize, int ysize)
1442 {
1443         
1444         if(node->preview==NULL) {
1445                 node->preview= MEM_callocN(sizeof(bNodePreview), "node preview");
1446 //              printf("added preview %s\n", node->name);
1447         }
1448         
1449         /* node previews can get added with variable size this way */
1450         if(xsize==0 || ysize==0)
1451                 return;
1452         
1453         /* sanity checks & initialize */
1454         if(node->preview->rect) {
1455                 if(node->preview->xsize!=xsize && node->preview->ysize!=ysize) {
1456                         MEM_freeN(node->preview->rect);
1457                         node->preview->rect= NULL;
1458                 }
1459         }
1460         
1461         if(node->preview->rect==NULL) {
1462                 node->preview->rect= MEM_callocN(4*xsize + xsize*ysize*sizeof(float)*4, "node preview rect");
1463                 node->preview->xsize= xsize;
1464                 node->preview->ysize= ysize;
1465         }
1466 }
1467
1468 void ntreeInitPreview(bNodeTree *ntree, int xsize, int ysize)
1469 {
1470         bNode *node;
1471         
1472         if(ntree==NULL)
1473                 return;
1474         
1475         for(node= ntree->nodes.first; node; node= node->next) {
1476                 if(node->typeinfo->flag & NODE_PREVIEW) /* hrms, check for closed nodes? */
1477                         nodeInitPreview(node, xsize, ysize);
1478                 if(node->type==NODE_GROUP && (node->flag & NODE_GROUP_EDIT))
1479                         ntreeInitPreview((bNodeTree *)node->id, xsize, ysize);
1480         }               
1481 }
1482
1483 static void nodeClearPreview(bNode *node)
1484 {
1485         if(node->preview && node->preview->rect)
1486                 memset(node->preview->rect, 0, MEM_allocN_len(node->preview->rect));
1487 }
1488
1489 /* use it to enforce clear */
1490 void ntreeClearPreview(bNodeTree *ntree)
1491 {
1492         bNode *node;
1493         
1494         if(ntree==NULL)
1495                 return;
1496         
1497         for(node= ntree->nodes.first; node; node= node->next) {
1498                 if(node->typeinfo->flag & NODE_PREVIEW)
1499                         nodeClearPreview(node);
1500                 if(node->type==NODE_GROUP && (node->flag & NODE_GROUP_EDIT))
1501                         ntreeClearPreview((bNodeTree *)node->id);
1502         }               
1503 }
1504
1505 /* hack warning! this function is only used for shader previews, and 
1506    since it gets called multiple times per pixel for Ztransp we only
1507    add the color once. Preview gets cleared before it starts render though */
1508 void nodeAddToPreview(bNode *node, float *col, int x, int y)
1509 {
1510         bNodePreview *preview= node->preview;
1511         if(preview) {
1512                 if(x>=0 && y>=0) {
1513                         if(x<preview->xsize && y<preview->ysize) {
1514                                 float *tar= preview->rect+ 4*((preview->xsize*y) + x);
1515                                 if(tar[0]==0.0f) {
1516                                         QUATCOPY(tar, col);
1517                                 }
1518                         }
1519                         //else printf("prv out bound x y %d %d\n", x, y);
1520                 }
1521                 //else printf("prv out bound x y %d %d\n", x, y);
1522         }
1523 }
1524
1525
1526
1527 /* ******************* executing ************* */
1528
1529 /* see notes at ntreeBeginExecTree */
1530 static void group_node_get_stack(bNode *node, bNodeStack *stack, bNodeStack **in, bNodeStack **out, bNodeStack **gin, bNodeStack **gout)
1531 {
1532         bNodeSocket *sock;
1533         
1534         /* build pointer stack */
1535         for(sock= node->inputs.first; sock; sock= sock->next) {
1536                 if(sock->intern) {
1537                         /* yep, intern can have link or is hidden socket */
1538                         if(sock->link)
1539                                 *(in++)= stack + sock->link->fromsock->stack_index;
1540                         else
1541                                 *(in++)= &sock->ns;
1542                 }
1543                 else
1544                         *(in++)= gin[sock->stack_index_ext];
1545         }
1546         
1547         for(sock= node->outputs.first; sock; sock= sock->next) {
1548                 if(sock->intern)
1549                         *(out++)= stack + sock->stack_index;
1550                 else
1551                         *(out++)= gout[sock->stack_index_ext];
1552         }
1553 }
1554
1555 static void node_group_execute(bNodeStack *stack, void *data, bNode *gnode, bNodeStack **in, bNodeStack **out)
1556 {
1557         bNode *node;
1558         bNodeTree *ntree= (bNodeTree *)gnode->id;
1559         bNodeStack *nsin[MAX_SOCKET];   /* arbitrary... watch this */
1560         bNodeStack *nsout[MAX_SOCKET];  /* arbitrary... watch this */
1561         
1562         if(ntree==NULL) return;
1563         
1564         stack+= gnode->stack_index;
1565                 
1566         for(node= ntree->nodes.first; node; node= node->next) {
1567                 if(node->typeinfo->execfunc) {
1568                         group_node_get_stack(node, stack, nsin, nsout, in, out);
1569                         
1570                         /* for groups, only execute outputs for edited group */
1571                         if(node->typeinfo->nclass==NODE_CLASS_OUTPUT) {
1572                                 if(gnode->flag & NODE_GROUP_EDIT)
1573                                         if(node->flag & NODE_DO_OUTPUT)
1574                                                 node->typeinfo->execfunc(data, node, nsin, nsout);
1575                         }
1576                         else
1577                                 node->typeinfo->execfunc(data, node, nsin, nsout);
1578                 }
1579         }
1580         
1581         /* free internal group output nodes */
1582         if(ntree->type==NTREE_COMPOSIT) {
1583                 for(node= ntree->nodes.first; node; node= node->next) {
1584                         if(node->typeinfo->execfunc) {
1585                                 bNodeSocket *sock;
1586                                 
1587                                 for(sock= node->outputs.first; sock; sock= sock->next) {
1588                                         if(sock->intern) {
1589                                                 bNodeStack *ns= stack + sock->stack_index;
1590                                                 if(ns->data) {
1591                                                         free_compbuf(ns->data);
1592                                                         ns->data= NULL;
1593                                                 }
1594                                         }
1595                                 }
1596                         }
1597                 }
1598         }
1599 }
1600
1601 /* recursively called for groups */
1602 /* we set all trees on own local indices, but put a total counter
1603    in the groups, so each instance of a group has own stack */
1604 static int ntree_begin_exec_tree(bNodeTree *ntree)
1605 {
1606         bNode *node;
1607         bNodeSocket *sock;
1608         int index= 0, index_in= 0, index_out= 0;
1609         
1610         if((ntree->init & NTREE_TYPE_INIT)==0)
1611                 ntreeInitTypes(ntree);
1612         
1613         /* create indices for stack, check preview */
1614         for(node= ntree->nodes.first; node; node= node->next) {
1615                 
1616                 for(sock= node->inputs.first; sock; sock= sock->next) {
1617                         if(sock->intern==0)
1618                                 sock->stack_index_ext= index_in++;
1619                 }
1620                 
1621                 for(sock= node->outputs.first; sock; sock= sock->next) {
1622                         sock->stack_index= index++;
1623                         if(sock->intern==0)
1624                                 sock->stack_index_ext= index_out++;
1625                 }
1626                 
1627                 if(node->type==NODE_GROUP) {
1628                         if(node->id) {
1629                                 node->stack_index= index;
1630                                 index+= ntree_begin_exec_tree((bNodeTree *)node->id);
1631                         }
1632                 }
1633         }
1634         
1635         return index;
1636 }
1637
1638 /* copy socket compbufs to stack, initialize usage of curve nodes */
1639 static void composit_begin_exec(bNodeTree *ntree, int is_group)
1640 {
1641         bNode *node;
1642         bNodeSocket *sock;
1643         
1644         for(node= ntree->nodes.first; node; node= node->next) {
1645                 if(is_group==0) {
1646                         for(sock= node->outputs.first; sock; sock= sock->next) {
1647                                 bNodeStack *ns= ntree->stack[0] + sock->stack_index;
1648                                 
1649                                 if(sock->ns.data) {
1650                                         ns->data= sock->ns.data;
1651                                         sock->ns.data= NULL;
1652                                 }
1653                         }
1654                 }               
1655                 /* cannot initialize them while using in threads */
1656                 if(ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB)) {
1657                         curvemapping_initialize(node->storage);
1658                         if(node->type==CMP_NODE_CURVE_RGB)
1659                                 curvemapping_premultiply(node->storage, 0);
1660                 }
1661                 if(node->type==NODE_GROUP)
1662                         composit_begin_exec((bNodeTree *)node->id, 1);
1663
1664         }
1665 }
1666
1667 /* copy stack compbufs to sockets */
1668 static void composit_end_exec(bNodeTree *ntree, int is_group)
1669 {
1670         extern void print_compbuf(char *str, struct CompBuf *cbuf);
1671         bNode *node;
1672         bNodeStack *ns;
1673         int a;
1674
1675         for(node= ntree->nodes.first; node; node= node->next) {
1676                 if(is_group==0) {
1677                         bNodeSocket *sock;
1678                 
1679                         for(sock= node->outputs.first; sock; sock= sock->next) {
1680                                 ns= ntree->stack[0] + sock->stack_index;
1681                                 if(ns->data) {
1682                                         sock->ns.data= ns->data;
1683                                         ns->data= NULL;
1684                                 }
1685                         }
1686                 }
1687                 if(node->type==CMP_NODE_CURVE_RGB)
1688                         curvemapping_premultiply(node->storage, 1);
1689                 
1690                 if(node->type==NODE_GROUP)
1691                         composit_end_exec((bNodeTree *)node->id, 1);
1692
1693                 node->need_exec= 0;
1694         }
1695         
1696         if(is_group==0) {
1697                 /* internally, group buffers are not stored */
1698                 for(ns= ntree->stack[0], a=0; a<ntree->stacksize; a++, ns++) {
1699                         if(ns->data) {
1700                                 printf("freed leftover buffer from stack\n");
1701                                 free_compbuf(ns->data);
1702                         }
1703                 }
1704         }
1705 }
1706
1707 static void group_tag_used_outputs(bNode *gnode, bNodeStack *stack)
1708 {
1709         bNodeTree *ntree= (bNodeTree *)gnode->id;
1710         bNode *node;
1711         
1712         stack+= gnode->stack_index;
1713         
1714         for(node= ntree->nodes.first; node; node= node->next) {
1715                 if(node->typeinfo->execfunc) {
1716                         bNodeSocket *sock;
1717                         
1718                         for(sock= node->inputs.first; sock; sock= sock->next) {
1719                                 if(sock->intern) {
1720                                         if(sock->link) {
1721                                                 bNodeStack *ns= stack + sock->link->fromsock->stack_index;
1722                                                 ns->hasoutput= 1;
1723                                                 ns->sockettype= sock->link->fromsock->type;
1724                                         }
1725                                         else
1726                                                 sock->ns.sockettype= sock->type;
1727                                 }
1728                         }
1729                 }
1730         }
1731 }
1732
1733 /* stack indices make sure all nodes only write in allocated data, for making it thread safe */
1734 /* only root tree gets the stack, to enable instances to have own stack entries */
1735 /* only two threads now! */
1736 /* per tree (and per group) unique indices are created */
1737 /* the index_ext we need to be able to map from groups to the group-node own stack */
1738
1739 void ntreeBeginExecTree(bNodeTree *ntree)
1740 {
1741         /* let's make it sure */
1742         if(ntree->init & NTREE_EXEC_INIT)
1743                 return;
1744         
1745         /* allocate the stack pointer array */
1746         ntree->stack= MEM_callocN(BLENDER_MAX_THREADS*sizeof(void *), "stack array");
1747         
1748         /* goes recursive over all groups */
1749         ntree->stacksize= ntree_begin_exec_tree(ntree);
1750
1751         if(ntree->stacksize) {
1752                 bNode *node;
1753                 bNodeStack *ns;
1754                 int a;
1755                 
1756                 /* allocate the base stack */
1757                 ns=ntree->stack[0]= MEM_callocN(ntree->stacksize*sizeof(bNodeStack), "node stack");
1758                 
1759                 /* tag inputs, the get_stack() gives own socket stackdata if not in use */
1760                 for(a=0; a<ntree->stacksize; a++, ns++) ns->hasinput= 1;
1761                 
1762                 /* tag used outputs, so we know when we can skip operations */
1763                 for(node= ntree->nodes.first; node; node= node->next) {
1764                         bNodeSocket *sock;
1765                         for(sock= node->inputs.first; sock; sock= sock->next) {
1766                                 if(sock->link) {
1767                                         ns= ntree->stack[0] + sock->link->fromsock->stack_index;
1768                                         ns->hasoutput= 1;
1769                                         ns->sockettype= sock->link->fromsock->type;
1770                                 }
1771                                 else
1772                                         sock->ns.sockettype= sock->type;
1773                         }
1774                         if(node->type==NODE_GROUP && node->id)
1775                                 group_tag_used_outputs(node, ntree->stack[0]);
1776                 }
1777                 
1778                 /* composite does 1 node per thread, so no multiple stacks needed */
1779                 if(ntree->type==NTREE_COMPOSIT)
1780                         composit_begin_exec(ntree, 0);
1781                 else {
1782                         for(a=1; a<BLENDER_MAX_THREADS; a++)
1783                                 ntree->stack[a]= MEM_dupallocN(ntree->stack[0]);
1784                 }
1785         }
1786         
1787         ntree->init |= NTREE_EXEC_INIT;
1788 }
1789
1790 void ntreeEndExecTree(bNodeTree *ntree)
1791 {
1792         
1793         if(ntree->init & NTREE_EXEC_INIT) {
1794                 int a;
1795                 
1796                 /* another callback candidate! */
1797                 if(ntree->type==NTREE_COMPOSIT)
1798                         composit_end_exec(ntree, 0);
1799                 
1800                 if(ntree->stack) {
1801                         for(a=0; a<BLENDER_MAX_THREADS; a++)
1802                                 if(ntree->stack[a])
1803                                         MEM_freeN(ntree->stack[a]);
1804                 
1805                         MEM_freeN(ntree->stack);
1806                         ntree->stack= NULL;
1807                 }
1808
1809                 ntree->init &= ~NTREE_EXEC_INIT;
1810         }
1811 }
1812
1813 static void node_get_stack(bNode *node, bNodeStack *stack, bNodeStack **in, bNodeStack **out)
1814 {
1815         bNodeSocket *sock;
1816         
1817         /* build pointer stack */
1818         for(sock= node->inputs.first; sock; sock= sock->next) {
1819                 if(sock->link)
1820                         *(in++)= stack + sock->link->fromsock->stack_index;
1821                 else
1822                         *(in++)= &sock->ns;
1823         }
1824         
1825         for(sock= node->outputs.first; sock; sock= sock->next) {
1826                 *(out++)= stack + sock->stack_index;
1827         }
1828 }
1829
1830 /* nodes are presorted, so exec is in order of list */
1831 void ntreeExecTree(bNodeTree *ntree, void *callerdata, int thread)
1832 {
1833         bNode *node;
1834         bNodeStack *nsin[MAX_SOCKET];   /* arbitrary... watch this */
1835         bNodeStack *nsout[MAX_SOCKET];  /* arbitrary... watch this */
1836         bNodeStack *stack;
1837         
1838         /* only when initialized */
1839         if((ntree->init & NTREE_EXEC_INIT)==0)
1840                 ntreeBeginExecTree(ntree);
1841                 
1842         stack= ntree->stack[thread];
1843         
1844         for(node= ntree->nodes.first; node; node= node->next) {
1845                 if(node->typeinfo->execfunc) {
1846                         node_get_stack(node, stack, nsin, nsout);
1847                         node->typeinfo->execfunc(callerdata, node, nsin, nsout);
1848                 }
1849                 else if(node->type==NODE_GROUP && node->id) {
1850                         node_get_stack(node, stack, nsin, nsout);
1851                         node_group_execute(stack, callerdata, node, nsin, nsout); 
1852                 }
1853         }
1854 }
1855
1856
1857 /* ***************************** threaded version for execute composite nodes ************* */
1858
1859 #define NODE_PROCESSING 1
1860 #define NODE_READY              2
1861 #define NODE_FINISHED   4
1862 #define NODE_FREEBUFS   8
1863
1864 /* not changing info, for thread callback */
1865 typedef struct ThreadData {
1866         bNodeStack *stack;
1867         RenderData *rd;
1868 } ThreadData;
1869
1870 static void *exec_composite_node(void *node_v)
1871 {
1872         bNodeStack *nsin[MAX_SOCKET];   /* arbitrary... watch this */
1873         bNodeStack *nsout[MAX_SOCKET];  /* arbitrary... watch this */
1874         bNode *node= node_v;
1875         ThreadData *thd= (ThreadData *)node->new_node; /* abuse */
1876         
1877         node_get_stack(node, thd->stack, nsin, nsout);
1878         
1879         if(node->typeinfo->execfunc) {
1880                 node->typeinfo->execfunc(thd->rd, node, nsin, nsout);
1881         }
1882         else if(node->type==NODE_GROUP && node->id) {
1883                 node_group_execute(thd->stack, thd->rd, node, nsin, nsout); 
1884         }
1885         
1886         node->exec |= NODE_READY;
1887         return 0;
1888 }
1889
1890 /* these are nodes without input, only giving values */
1891 /* or nodes with only value inputs */
1892 static int node_only_value(bNode *node)
1893 {
1894         bNodeSocket *sock;
1895         
1896         if(ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_VALUE, CMP_NODE_RGB))
1897                 return 1;
1898         
1899         /* doing this for all node types goes wrong. memory free errors */
1900         if(node->inputs.first && node->type==CMP_NODE_MAP_VALUE) {
1901                 int retval= 1;
1902                 for(sock= node->inputs.first; sock; sock= sock->next) {
1903                         if(sock->link)
1904                                 retval &= node_only_value(sock->link->fromnode);
1905                 }
1906                 return retval;
1907         }
1908         return 0;
1909 }
1910
1911 /* return total of executable nodes, for timecursor */
1912 /* only compositor uses it */
1913 static int setExecutableNodes(bNodeTree *ntree, ThreadData *thd)
1914 {
1915         bNodeStack *nsin[MAX_SOCKET];   /* arbitrary... watch this */
1916         bNodeStack *nsout[MAX_SOCKET];  /* arbitrary... watch this */
1917         bNode *node;
1918         bNodeSocket *sock;
1919         int totnode= 0, group_edit= 0;
1920         
1921         /* note; do not add a dependency sort here, the stack was created already */
1922         
1923         /* if we are in group edit, viewer nodes get skipped when group has viewer */
1924         for(node= ntree->nodes.first; node; node= node->next)
1925                 if(node->type==NODE_GROUP && (node->flag & NODE_GROUP_EDIT))
1926                         if(ntreeHasType((bNodeTree *)node->id, CMP_NODE_VIEWER))
1927                                 group_edit= 1;
1928         
1929         for(node= ntree->nodes.first; node; node= node->next) {
1930                 int a;
1931                 
1932                 node_get_stack(node, thd->stack, nsin, nsout);
1933                 
1934                 /* test the outputs */
1935                 /* skip value-only nodes (should be in type!) */
1936                 if(!node_only_value(node)) {
1937                         for(a=0, sock= node->outputs.first; sock; sock= sock->next, a++) {
1938                                 if(nsout[a]->data==NULL && nsout[a]->hasoutput) {
1939                                         node->need_exec= 1;
1940                                         break;
1941                                 }
1942                         }
1943                 }
1944                 
1945                 /* test the inputs */
1946                 for(a=0, sock= node->inputs.first; sock; sock= sock->next, a++) {
1947                         /* skip viewer nodes in bg render or group edit */
1948                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER) && (G.background || group_edit))
1949                                 node->need_exec= 0;
1950                         /* is sock in use? */
1951                         else if(sock->link) {
1952                                 bNodeLink *link= sock->link;
1953                                 /* this is the test for a cyclic case */
1954                                 if(link->fromnode->level >= link->tonode->level && link->tonode->level!=0xFFF) {
1955                                         if(link->fromnode->need_exec) {
1956                                                 node->need_exec= 1;
1957                                                 break;
1958                                         }
1959                                 }
1960                                 else {
1961                                         node->need_exec= 0;
1962                                         printf("Node %s skipped, cyclic dependency\n", node->name);
1963                                 }
1964                         }
1965                 }
1966                 
1967                 if(node->need_exec) {
1968                         
1969                         /* free output buffers */
1970                         for(a=0, sock= node->outputs.first; sock; sock= sock->next, a++) {
1971                                 if(nsout[a]->data) {
1972                                         free_compbuf(nsout[a]->data);
1973                                         nsout[a]->data= NULL;
1974                                 }
1975                         }
1976                         totnode++;
1977                         /* printf("node needs exec %s\n", node->name); */
1978                         
1979                         /* tag for getExecutableNode() */
1980                         node->exec= 0;
1981                 }
1982                 else {
1983                         /* tag for getExecutableNode() */
1984                         node->exec= NODE_READY|NODE_FINISHED;
1985                         
1986                 }
1987         }
1988         
1989         /* last step: set the stack values for only-value nodes */
1990         /* just does all now, compared to a full buffer exec this is nothing */
1991         if(totnode) {
1992                 for(node= ntree->nodes.first; node; node= node->next) {
1993                         if(node->need_exec==0 && node_only_value(node)) {
1994                                 if(node->typeinfo->execfunc) {
1995                                         node_get_stack(node, thd->stack, nsin, nsout);
1996                                         node->typeinfo->execfunc(thd->rd, node, nsin, nsout);
1997                                 }
1998                         }
1999                 }
2000         }
2001         
2002         return totnode;
2003 }
2004
2005 /* while executing tree, free buffers from nodes that are not needed anymore */
2006 static void freeExecutableNode(bNodeTree *ntree)
2007 {
2008         /* node outputs can be freed when:
2009         - not a render result or image node
2010         - when node outputs go to nodes all being set NODE_FINISHED
2011         */
2012         bNode *node;
2013         bNodeSocket *sock;
2014         
2015         /* set exec flag for finished nodes that might need freed */
2016         for(node= ntree->nodes.first; node; node= node->next) {
2017                 if(node->type!=CMP_NODE_R_LAYERS)
2018                         if(node->exec & NODE_FINISHED)
2019                                 node->exec |= NODE_FREEBUFS;
2020         }
2021         /* clear this flag for input links that are not done yet */
2022         for(node= ntree->nodes.first; node; node= node->next) {
2023                 if((node->exec & NODE_FINISHED)==0) {
2024                         for(sock= node->inputs.first; sock; sock= sock->next)
2025                                 if(sock->link)
2026                                         sock->link->fromnode->exec &= ~NODE_FREEBUFS;
2027                 }
2028         }
2029         /* now we can free buffers */
2030         for(node= ntree->nodes.first; node; node= node->next) {
2031                 if(node->exec & NODE_FREEBUFS) {
2032                         for(sock= node->outputs.first; sock; sock= sock->next) {
2033                                 bNodeStack *ns= ntree->stack[0] + sock->stack_index;
2034                                 if(ns->data) {
2035                                         free_compbuf(ns->data);
2036                                         ns->data= NULL;
2037                                         // printf("freed buf node %s \n", node->name);
2038                                 }
2039                         }
2040                 }
2041         }
2042 }
2043
2044 static bNode *getExecutableNode(bNodeTree *ntree)
2045 {
2046         bNode *node;
2047         bNodeSocket *sock;
2048         
2049         for(node= ntree->nodes.first; node; node= node->next) {
2050                 if(node->exec==0) {
2051                         
2052                         /* input sockets should be ready */
2053                         for(sock= node->inputs.first; sock; sock= sock->next) {
2054                                 if(sock->link)
2055                                         if((sock->link->fromnode->exec & NODE_READY)==0)
2056                                                 break;
2057                         }
2058                         if(sock==NULL)
2059                                 return node;
2060                 }
2061         }
2062         return NULL;
2063 }
2064
2065
2066 /* optimized tree execute test for compositing */
2067 void ntreeCompositExecTree(bNodeTree *ntree, RenderData *rd, int do_preview)
2068 {
2069         bNode *node;
2070         ListBase threads;
2071         ThreadData thdata;
2072         int totnode, rendering= 1;
2073         
2074         if(ntree==NULL) return;
2075         
2076         if(do_preview)
2077                 ntreeInitPreview(ntree, 0, 0);
2078         
2079         ntreeBeginExecTree(ntree);
2080         
2081         /* prevent unlucky accidents */
2082         if(G.background)
2083                 rd->scemode &= ~R_COMP_CROP;
2084         
2085         /* setup callerdata for thread callback */
2086         thdata.rd= rd;
2087         thdata.stack= ntree->stack[0];
2088         
2089         /* fixed seed, for example noise texture */
2090         BLI_srandom(rd->cfra);
2091
2092         /* sets need_exec tags in nodes */
2093         totnode= setExecutableNodes(ntree, &thdata);
2094         
2095         BLI_init_threads(&threads, exec_composite_node, rd->threads);
2096         
2097         while(rendering) {
2098                 
2099                 if(BLI_available_threads(&threads)) {
2100                         node= getExecutableNode(ntree);
2101                         if(node) {
2102
2103                                 if(ntree->timecursor)
2104                                         ntree->timecursor(totnode);
2105                                 if(ntree->stats_draw) {
2106                                         char str[64];
2107                                         sprintf(str, "Compositing %d %s", totnode, node->name);
2108                                         ntree->stats_draw(str);
2109                                 }
2110                                 totnode--;
2111                                 
2112                                 node->new_node = (bNode *)&thdata;
2113                                 node->exec= NODE_PROCESSING;
2114                                 BLI_insert_thread(&threads, node);
2115                         }
2116                         else
2117                                 PIL_sleep_ms(50);
2118                 }
2119                 else
2120                         PIL_sleep_ms(50);
2121                 
2122                 rendering= 0;
2123                 /* test for ESC */
2124                 if(ntree->test_break && ntree->test_break()) {
2125                         for(node= ntree->nodes.first; node; node= node->next)
2126                                 node->exec |= NODE_READY;
2127                 }
2128                 
2129                 /* check for ready ones, and if we need to continue */
2130                 for(node= ntree->nodes.first; node; node= node->next) {
2131                         if(node->exec & NODE_READY) {
2132                                 if((node->exec & NODE_FINISHED)==0) {
2133                                         BLI_remove_thread(&threads, node);
2134                                         node->exec |= NODE_FINISHED;
2135                                         
2136                                         /* freeing unused buffers */
2137                                         if(rd->scemode & R_COMP_FREE)
2138                                                 freeExecutableNode(ntree);
2139                                 }
2140                         }
2141                         else rendering= 1;
2142                 }
2143         }
2144         
2145         
2146         BLI_end_threads(&threads);
2147         
2148         ntreeEndExecTree(ntree);
2149         
2150 }
2151
2152
2153 /* **************** call to switch lamploop for material node ************ */
2154
2155 void set_node_shader_lamp_loop(void (*lamp_loop_func)(ShadeInput *, ShadeResult *))
2156 {
2157    node_shader_lamp_loop= lamp_loop_func;
2158 }
2159
2160 /* clumsy checking... should do dynamic outputs once */
2161 static void force_hidden_passes(bNode *node, int passflag)
2162 {
2163    bNodeSocket *sock;
2164
2165    for(sock= node->outputs.first; sock; sock= sock->next)
2166       sock->flag &= ~SOCK_UNAVAIL;
2167
2168    sock= BLI_findlink(&node->outputs, RRES_OUT_Z);
2169    if(!(passflag & SCE_PASS_Z)) sock->flag |= SOCK_UNAVAIL;
2170    sock= BLI_findlink(&node->outputs, RRES_OUT_NORMAL);
2171    if(!(passflag & SCE_PASS_NORMAL)) sock->flag |= SOCK_UNAVAIL;
2172    sock= BLI_findlink(&node->outputs, RRES_OUT_VEC);
2173    if(!(passflag & SCE_PASS_VECTOR)) sock->flag |= SOCK_UNAVAIL;
2174    sock= BLI_findlink(&node->outputs, RRES_OUT_UV);
2175    if(!(passflag & SCE_PASS_UV)) sock->flag |= SOCK_UNAVAIL;
2176    sock= BLI_findlink(&node->outputs, RRES_OUT_RGBA);
2177    if(!(passflag & SCE_PASS_RGBA)) sock->flag |= SOCK_UNAVAIL;
2178    sock= BLI_findlink(&node->outputs, RRES_OUT_DIFF);
2179    if(!(passflag & SCE_PASS_DIFFUSE)) sock->flag |= SOCK_UNAVAIL;
2180    sock= BLI_findlink(&node->outputs, RRES_OUT_SPEC);
2181    if(!(passflag & SCE_PASS_SPEC)) sock->flag |= SOCK_UNAVAIL;
2182    sock= BLI_findlink(&node->outputs, RRES_OUT_SHADOW);
2183    if(!(passflag & SCE_PASS_SHADOW)) sock->flag |= SOCK_UNAVAIL;
2184    sock= BLI_findlink(&node->outputs, RRES_OUT_AO);
2185    if(!(passflag & SCE_PASS_AO)) sock->flag |= SOCK_UNAVAIL;
2186    sock= BLI_findlink(&node->outputs, RRES_OUT_REFLECT);
2187    if(!(passflag & SCE_PASS_REFLECT)) sock->flag |= SOCK_UNAVAIL;
2188    sock= BLI_findlink(&node->outputs, RRES_OUT_REFRACT);
2189    if(!(passflag & SCE_PASS_REFRACT)) sock->flag |= SOCK_UNAVAIL;
2190    sock= BLI_findlink(&node->outputs, RRES_OUT_RADIO);
2191    if(!(passflag & SCE_PASS_RADIO)) sock->flag |= SOCK_UNAVAIL;
2192    sock= BLI_findlink(&node->outputs, RRES_OUT_INDEXOB);
2193    if(!(passflag & SCE_PASS_INDEXOB)) sock->flag |= SOCK_UNAVAIL;
2194
2195 }
2196
2197 /* based on rules, force sockets hidden always */
2198 void ntreeCompositForceHidden(bNodeTree *ntree)
2199 {
2200    bNode *node;
2201
2202    if(ntree==NULL) return;
2203
2204    for(node= ntree->nodes.first; node; node= node->next) {
2205       if( node->type==CMP_NODE_R_LAYERS) {
2206          Scene *sce= node->id?(Scene *)node->id:G.scene; /* G.scene is WEAK! */
2207          SceneRenderLayer *srl= BLI_findlink(&sce->r.layers, node->custom1);
2208          if(srl)
2209             force_hidden_passes(node, srl->passflag);
2210       }
2211       else if( node->type==CMP_NODE_IMAGE) {
2212          Image *ima= (Image *)node->id;
2213          if(ima) {
2214             if(ima->rr) {
2215                ImageUser *iuser= node->storage;
2216                RenderLayer *rl= BLI_findlink(&ima->rr->layers, iuser->layer);
2217                if(rl)
2218                   force_hidden_passes(node, rl->passflag);
2219                else
2220                   force_hidden_passes(node, 0);
2221             }
2222             else if(ima->type!=IMA_TYPE_MULTILAYER) {   /* if ->rr not yet read we keep inputs */
2223                force_hidden_passes(node, RRES_OUT_Z);
2224             }
2225          }
2226          else
2227             force_hidden_passes(node, 0);
2228       }
2229    }
2230
2231 }
2232
2233 /* called from render pipeline, to tag render input and output */
2234 /* need to do all scenes, to prevent errors when you re-render 1 scene */
2235 void ntreeCompositTagRender(Scene *curscene)
2236 {
2237    Scene *sce;
2238
2239    for(sce= G.main->scene.first; sce; sce= sce->id.next) {
2240       if(sce->nodetree) {
2241          bNode *node;
2242
2243          for(node= sce->nodetree->nodes.first; node; node= node->next) {
2244             if(node->id==(ID *)curscene || node->type==CMP_NODE_COMPOSITE)
2245                NodeTagChanged(sce->nodetree, node);
2246          }
2247       }
2248    }
2249 }
2250
2251 /* tags nodes that have animation capabilities */
2252 int ntreeCompositTagAnimated(bNodeTree *ntree)
2253 {
2254    bNode *node;
2255    int tagged= 0;
2256
2257    if(ntree==NULL) return 0;
2258
2259    for(node= ntree->nodes.first; node; node= node->next) {
2260       if(node->type==CMP_NODE_IMAGE) {
2261          Image *ima= (Image *)node->id;
2262          if(ima && ELEM(ima->source, IMA_SRC_MOVIE, IMA_SRC_SEQUENCE)) {
2263             NodeTagChanged(ntree, node);
2264             tagged= 1;
2265          }
2266       }
2267       else if(node->type==CMP_NODE_TIME) {
2268          NodeTagChanged(ntree, node);
2269          tagged= 1;
2270       }
2271       else if(node->type==CMP_NODE_R_LAYERS) {
2272          NodeTagChanged(ntree, node);
2273          tagged= 1;
2274       }
2275       else if(node->type==NODE_GROUP) {
2276          if( ntreeCompositTagAnimated((bNodeTree *)node->id) ) {
2277             NodeTagChanged(ntree, node);
2278          }
2279       }
2280    }
2281
2282    return tagged;
2283 }
2284
2285
2286 /* called from image window preview */
2287 void ntreeCompositTagGenerators(bNodeTree *ntree)
2288 {
2289    bNode *node;
2290
2291    if(ntree==NULL) return;
2292
2293    for(node= ntree->nodes.first; node; node= node->next) {
2294       if( ELEM(node->type, CMP_NODE_R_LAYERS, CMP_NODE_IMAGE))
2295          NodeTagChanged(ntree, node);
2296    }
2297 }
2298