c1e50c112fae58dbaa5e2eceec160b664d8235f5
[blender.git] / source / blender / editors / space_node / node_edit.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): David Millan Escriva, Juho Vepsäläinen, Nathan Letwory
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/space_node/node_edit.c
29  *  \ingroup spnode
30  */
31
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <math.h>
36 #include <string.h>
37 #include <errno.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_ID.h"
42 #include "DNA_lamp_types.h"
43 #include "DNA_material_types.h"
44 #include "DNA_node_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_particle_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_world_types.h"
49
50 #include "BLI_math.h"
51 #include "BLI_blenlib.h"
52 #include "BLI_utildefines.h"
53
54 #include "BKE_context.h"
55 #include "BKE_depsgraph.h"
56 #include "BKE_global.h"
57 #include "BKE_image.h"
58 #include "BKE_library.h"
59 #include "BKE_main.h"
60 #include "BKE_node.h"
61 #include "BKE_material.h"
62 #include "BKE_modifier.h"
63 #include "BKE_paint.h"
64 #include "BKE_screen.h"
65 #include "BKE_texture.h"
66 #include "BKE_report.h"
67
68 #include "RE_pipeline.h"
69
70 #include "IMB_imbuf_types.h"
71
72 #include "ED_node.h"
73 #include "ED_screen.h"
74 #include "ED_space_api.h"
75 #include "ED_render.h"
76
77 #include "RNA_access.h"
78 #include "RNA_define.h"
79 #include "RNA_enum_types.h"
80
81 #include "WM_api.h"
82 #include "WM_types.h"
83
84 #include "UI_interface.h"
85 #include "UI_resources.h"
86 #include "UI_view2d.h"
87
88 #include "IMB_imbuf.h"
89
90 #include "RNA_enum_types.h"
91
92 #include "node_intern.h"
93
94 static EnumPropertyItem socket_in_out_items[] = {
95         { SOCK_IN, "SOCK_IN", 0, "Input", "" },
96         { SOCK_OUT, "SOCK_OUT", 0, "Output", "" },
97         { 0, NULL, 0, NULL, NULL },
98 };
99
100 /* ***************** composite job manager ********************** */
101
102 typedef struct CompoJob {
103         Scene *scene;
104         bNodeTree *ntree;
105         bNodeTree *localtree;
106         short *stop;
107         short *do_update;
108         float *progress;
109 } CompoJob;
110
111 /* called by compo, only to check job 'stop' value */
112 static int compo_breakjob(void *cjv)
113 {
114         CompoJob *cj= cjv;
115         
116         return *(cj->stop);
117 }
118
119 /* called by compo, wmJob sends notifier */
120 static void compo_redrawjob(void *cjv, char *UNUSED(str))
121 {
122         CompoJob *cj= cjv;
123         
124         *(cj->do_update)= 1;
125 }
126
127 static void compo_freejob(void *cjv)
128 {
129         CompoJob *cj= cjv;
130
131         if(cj->localtree) {
132                 ntreeLocalMerge(cj->localtree, cj->ntree);
133         }
134         MEM_freeN(cj);
135 }
136
137 /* only now we copy the nodetree, so adding many jobs while
138    sliding buttons doesn't frustrate */
139 static void compo_initjob(void *cjv)
140 {
141         CompoJob *cj= cjv;
142
143         cj->localtree= ntreeLocalize(cj->ntree);
144 }
145
146 /* called before redraw notifiers, it moves finished previews over */
147 static void compo_updatejob(void *cjv)
148 {
149         CompoJob *cj= cjv;
150         
151         ntreeLocalSync(cj->localtree, cj->ntree);
152 }
153
154 static void compo_progressjob(void *cjv, float progress)
155 {
156         CompoJob *cj= cjv;
157         
158         *(cj->progress) = progress;
159 }
160
161
162 /* only this runs inside thread */
163 static void compo_startjob(void *cjv, short *stop, short *do_update, float *progress)
164 {
165         CompoJob *cj= cjv;
166         bNodeTree *ntree= cj->localtree;
167
168         if(cj->scene->use_nodes==0)
169                 return;
170         
171         cj->stop= stop;
172         cj->do_update= do_update;
173         cj->progress= progress;
174         
175         ntree->test_break= compo_breakjob;
176         ntree->tbh= cj;
177         ntree->stats_draw= compo_redrawjob;
178         ntree->sdh= cj;
179         ntree->progress= compo_progressjob;
180         ntree->prh= cj;
181         
182         // XXX BIF_store_spare();
183         
184         ntreeCompositExecTree(ntree, &cj->scene->r, 1); /* 1 is do_previews */
185         
186         ntree->test_break= NULL;
187         ntree->stats_draw= NULL;
188         ntree->progress= NULL;
189
190 }
191
192 void snode_composite_job(const bContext *C, ScrArea *sa)
193 {
194         SpaceNode *snode= sa->spacedata.first;
195         wmJob *steve;
196         CompoJob *cj;
197
198         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa, "Compositing", WM_JOB_EXCL_RENDER|WM_JOB_PROGRESS);
199         cj= MEM_callocN(sizeof(CompoJob), "compo job");
200         
201         /* customdata for preview thread */
202         cj->scene= CTX_data_scene(C);
203         cj->ntree= snode->nodetree;
204         
205         /* setup job */
206         WM_jobs_customdata(steve, cj, compo_freejob);
207         WM_jobs_timer(steve, 0.1, NC_SCENE, NC_SCENE|ND_COMPO_RESULT);
208         WM_jobs_callbacks(steve, compo_startjob, compo_initjob, compo_updatejob, NULL);
209         
210         WM_jobs_start(CTX_wm_manager(C), steve);
211         
212 }
213
214 /* ***************************************** */
215
216 /* operator poll callback */
217 static int composite_node_active(bContext *C)
218 {
219         if( ED_operator_node_active(C)) {
220                 SpaceNode *snode= CTX_wm_space_node(C);
221                 if(snode->treetype==NTREE_COMPOSIT)
222                         return 1;
223         }
224         return 0;
225 }
226
227 /* also checks for edited groups */
228 static bNode *editnode_get_active(bNodeTree *ntree)
229 {
230         bNode *node;
231         
232         /* check for edited group */
233         for(node= ntree->nodes.first; node; node= node->next)
234                 if(nodeGroupEditGet(node))
235                         break;
236         if(node)
237                 return nodeGetActive((bNodeTree *)node->id);
238         else
239                 return nodeGetActive(ntree);
240 }
241
242 void snode_dag_update(bContext *UNUSED(C), SpaceNode *snode)
243 {
244         DAG_id_tag_update(snode->id, 0);
245 }
246
247 void snode_notify(bContext *C, SpaceNode *snode)
248 {
249         WM_event_add_notifier(C, NC_NODE|NA_EDITED, NULL);
250
251         if(snode->treetype==NTREE_SHADER)
252                 WM_event_add_notifier(C, NC_MATERIAL|ND_NODES, snode->id);
253         else if(snode->treetype==NTREE_COMPOSIT)
254                 WM_event_add_notifier(C, NC_SCENE|ND_NODES, snode->id);
255         else if(snode->treetype==NTREE_TEXTURE)
256                 WM_event_add_notifier(C, NC_TEXTURE|ND_NODES, snode->id);
257 }
258
259 bNode *node_tree_get_editgroup(bNodeTree *nodetree)
260 {
261         bNode *gnode;
262         
263         /* get the groupnode */
264         for(gnode= nodetree->nodes.first; gnode; gnode= gnode->next)
265                 if(nodeGroupEditGet(gnode))
266                         break;
267         return gnode;
268 }
269
270 /* assumes nothing being done in ntree yet, sets the default in/out node */
271 /* called from shading buttons or header */
272 void ED_node_shader_default(Scene *UNUSED(scene), ID *id)
273 {
274         bNode *in, *out;
275         bNodeSocket *fromsock, *tosock;
276         bNodeTree *ntree;
277         bNodeTemplate ntemp;
278         int output_type, shader_type;
279         
280         ntree= ntreeAddTree("Shader Nodetree", NTREE_SHADER, 0);
281
282         switch(GS(id->name)) {
283                 case ID_MA: {
284                         Material *ma= (Material*)id;
285                         ma->nodetree = ntree;
286
287                         output_type = SH_NODE_OUTPUT;
288                         shader_type = SH_NODE_MATERIAL;
289                         break;
290                 }
291                 case ID_WO: {
292                         World *wo= (World*)id;
293                         wo->nodetree = ntree;
294
295                         output_type = SH_NODE_OUTPUT;
296                         shader_type = SH_NODE_MATERIAL;
297                         break;
298                 }
299                 case ID_LA: {
300                         Lamp *la= (Lamp*)id;
301                         la->nodetree = ntree;
302
303                         output_type = SH_NODE_OUTPUT;
304                         shader_type = SH_NODE_MATERIAL;
305                         break;
306                 }
307                 default:
308                         printf("ED_node_shader_default called on wrong ID type.\n");
309                         return;
310         }
311         
312         ntemp.type = output_type;
313         out= nodeAddNode(ntree, &ntemp);
314         out->locx= 300.0f; out->locy= 300.0f;
315         
316         ntemp.type = shader_type;
317         in= nodeAddNode(ntree, &ntemp);
318         in->locx= 10.0f; in->locy= 300.0f;
319         nodeSetActive(ntree, in);
320         
321         /* only a link from color to color */
322         fromsock= in->outputs.first;
323         tosock= out->inputs.first;
324         nodeAddLink(ntree, in, fromsock, out, tosock);
325         
326         ntreeUpdateTree(ntree);
327 }
328
329 /* assumes nothing being done in ntree yet, sets the default in/out node */
330 /* called from shading buttons or header */
331 void ED_node_composit_default(Scene *sce)
332 {
333         bNode *in, *out;
334         bNodeSocket *fromsock, *tosock;
335         bNodeTemplate ntemp;
336         
337         /* but lets check it anyway */
338         if(sce->nodetree) {
339                 if (G.f & G_DEBUG)
340                         printf("error in composite initialize\n");
341                 return;
342         }
343         
344         sce->nodetree= ntreeAddTree("Compositing Nodetree", NTREE_COMPOSIT, 0);
345         
346         ntemp.type = CMP_NODE_COMPOSITE;
347         out= nodeAddNode(sce->nodetree, &ntemp);
348         out->locx= 300.0f; out->locy= 400.0f;
349         out->id= &sce->id;
350         id_us_plus(out->id);
351         
352         ntemp.type = CMP_NODE_R_LAYERS;
353         in= nodeAddNode(sce->nodetree, &ntemp);
354         in->locx= 10.0f; in->locy= 400.0f;
355         in->id= &sce->id;
356         id_us_plus(in->id);
357         nodeSetActive(sce->nodetree, in);
358         
359         /* links from color to color */
360         fromsock= in->outputs.first;
361         tosock= out->inputs.first;
362         nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
363         
364         ntreeUpdateTree(sce->nodetree);
365         
366         // XXX ntreeCompositForceHidden(sce->nodetree);
367 }
368
369 /* assumes nothing being done in ntree yet, sets the default in/out node */
370 /* called from shading buttons or header */
371 void ED_node_texture_default(Tex *tx)
372 {
373         bNode *in, *out;
374         bNodeSocket *fromsock, *tosock;
375         bNodeTemplate ntemp;
376         
377         /* but lets check it anyway */
378         if(tx->nodetree) {
379                 if (G.f & G_DEBUG)
380                         printf("error in texture initialize\n");
381                 return;
382         }
383         
384         tx->nodetree= ntreeAddTree("Texture Nodetree", NTREE_TEXTURE, 0);
385         
386         ntemp.type = TEX_NODE_OUTPUT;
387         out= nodeAddNode(tx->nodetree, &ntemp);
388         out->locx= 300.0f; out->locy= 300.0f;
389         
390         ntemp.type = TEX_NODE_CHECKER;
391         in= nodeAddNode(tx->nodetree, &ntemp);
392         in->locx= 10.0f; in->locy= 300.0f;
393         nodeSetActive(tx->nodetree, in);
394         
395         fromsock= in->outputs.first;
396         tosock= out->inputs.first;
397         nodeAddLink(tx->nodetree, in, fromsock, out, tosock);
398         
399         ntreeUpdateTree(tx->nodetree);
400 }
401
402 /* id is supposed to contain a node tree */
403 void node_tree_from_ID(ID *id, bNodeTree **ntree, bNodeTree **edittree, int *treetype)
404 {
405         if (id) {
406                 bNode *node= NULL;
407                 short idtype= GS(id->name);
408         
409                 if(idtype == ID_NT) {
410                         *ntree= (bNodeTree*)id;
411                         if(treetype) *treetype= (*ntree)->type;
412                 }
413                 else if(idtype == ID_MA) {
414                         *ntree= ((Material*)id)->nodetree;
415                         if(treetype) *treetype= NTREE_SHADER;
416                 }
417                 else if(idtype == ID_LA) {
418                         *ntree= ((Lamp*)id)->nodetree;
419                         if(treetype) *treetype= NTREE_SHADER;
420                 }
421                 else if(idtype == ID_WO) {
422                         *ntree= ((World*)id)->nodetree;
423                         if(treetype) *treetype= NTREE_SHADER;
424                 }
425                 else if(idtype == ID_SCE) {
426                         *ntree= ((Scene*)id)->nodetree;
427                         if(treetype) *treetype= NTREE_COMPOSIT;
428                 }
429                 else if(idtype == ID_TE) {
430                         *ntree= ((Tex*)id)->nodetree;
431                         if(treetype) *treetype= NTREE_TEXTURE;
432                 }
433                 else {
434                         if(treetype) *treetype= 0;
435                         return;
436                 }
437         
438                 /* find editable group */
439                 if(edittree) {
440                         if(*ntree)
441                                 for(node= (*ntree)->nodes.first; node; node= node->next)
442                                         if(nodeGroupEditGet(node))
443                                                 break;
444                         
445                         if(node && node->id)
446                                 *edittree= (bNodeTree *)node->id;
447                         else
448                                 *edittree= *ntree;
449                 }
450         }
451         else {
452                 *ntree= NULL;
453                 if(treetype) *treetype= 0;
454         }
455 }
456
457 /* Here we set the active tree(s), even called for each redraw now, so keep it fast :) */
458 void snode_set_context(SpaceNode *snode, Scene *scene)
459 {
460         Object *ob= OBACT;
461         
462         snode->id= snode->from= NULL;
463         
464         if(snode->treetype==NTREE_SHADER) {
465                 /* need active object, or we allow pinning... */
466                 if(snode->shaderfrom == SNODE_SHADER_OBJECT) {
467                         if(ob) {
468                                 if(ob->type == OB_LAMP) {
469                                         snode->from= &ob->id;
470                                         snode->id= ob->data;
471                                 }
472                                 else {
473                                         Material *ma= give_current_material(ob, ob->actcol);
474                                         if(ma) {
475                                                 snode->from= &ob->id;
476                                                 snode->id= &ma->id;
477                                         }
478                                 }
479                         }
480                 }
481                 else { /* SNODE_SHADER_WORLD */
482                         if(scene->world) {
483                                 snode->from= NULL;
484                                 snode->id= &scene->world->id;
485                         }
486                 }
487         }
488         else if(snode->treetype==NTREE_COMPOSIT) {
489                 snode->id= &scene->id;
490                 
491                 /* update output sockets based on available layers */
492                 ntreeCompositForceHidden(scene->nodetree, scene);
493         }
494         else if(snode->treetype==NTREE_TEXTURE) {
495                 Tex *tx= NULL;
496
497                 if(snode->texfrom==SNODE_TEX_OBJECT) {
498                         if(ob) {
499                                 tx= give_current_object_texture(ob);
500
501                                 if(ob->type == OB_LAMP)
502                                         snode->from= (ID*)ob->data;
503                                 else
504                                         snode->from= (ID*)give_current_material(ob, ob->actcol);
505
506                                 /* from is not set fully for material nodes, should be ID + Node then */
507                                 snode->id= &tx->id;
508                         }
509                 }
510                 else if(snode->texfrom==SNODE_TEX_WORLD) {
511                         tx= give_current_world_texture(scene->world);
512                         snode->from= (ID *)scene->world;
513                         snode->id= &tx->id;
514                 }
515                 else {
516                         struct Brush *brush= NULL;
517                         
518                         if(ob && (ob->mode & OB_MODE_SCULPT))
519                                 brush= paint_brush(&scene->toolsettings->sculpt->paint);
520                         else
521                                 brush= paint_brush(&scene->toolsettings->imapaint.paint);
522
523                         if (brush) {
524                                 snode->from= (ID *)brush;
525                                 tx= give_current_brush_texture(brush);
526                                 snode->id= &tx->id;
527                         }
528                 }
529         }
530         else {
531                 if (snode->nodetree && snode->nodetree->type == snode->treetype)
532                         snode->id = &snode->nodetree->id;
533                 else
534                         snode->id = NULL;
535         }
536
537         node_tree_from_ID(snode->id, &snode->nodetree, &snode->edittree, NULL);
538 }
539
540 static void snode_update(SpaceNode *snode, bNode *node)
541 {
542         bNode *gnode;
543         
544         if (node)
545                 nodeUpdate(snode->edittree, node);
546         
547         /* if inside group, tag entire group */
548         gnode= node_tree_get_editgroup(snode->nodetree);
549         if(gnode)
550                 nodeUpdateID(snode->nodetree, gnode->id);
551 }
552
553 static int has_nodetree(bNodeTree *ntree, bNodeTree *lookup)
554 {
555         bNode *node;
556         
557         if(ntree == lookup)
558                 return 1;
559         
560         for(node=ntree->nodes.first; node; node=node->next)
561                 if(node->type == NODE_GROUP && node->id)
562                         if(has_nodetree((bNodeTree*)node->id, lookup))
563                                 return 1;
564         
565         return 0;
566 }
567
568 void ED_node_set_active(Main *bmain, bNodeTree *ntree, bNode *node)
569 {
570         nodeSetActive(ntree, node);
571         
572         if(node->type!=NODE_GROUP) {
573                 int was_output= (node->flag & NODE_DO_OUTPUT);
574                 
575                 /* tree specific activate calls */
576                 if(ntree->type==NTREE_SHADER) {
577                         /* when we select a material, active texture is cleared, for buttons */
578                         if(node->id && ELEM3(GS(node->id->name), ID_MA, ID_LA, ID_WO))
579                                 nodeClearActiveID(ntree, ID_TE);
580                         
581                         if(node->type==SH_NODE_OUTPUT) {
582                                 bNode *tnode;
583                                 
584                                 for(tnode= ntree->nodes.first; tnode; tnode= tnode->next)
585                                         if( tnode->type==SH_NODE_OUTPUT)
586                                                 tnode->flag &= ~NODE_DO_OUTPUT;
587                                 
588                                 node->flag |= NODE_DO_OUTPUT;
589                                 if(was_output==0)
590                                         ED_node_generic_update(bmain, ntree, node);
591                         }
592
593                         WM_main_add_notifier(NC_MATERIAL|ND_NODES, node->id);
594                 }
595                 else if(ntree->type==NTREE_COMPOSIT) {
596                         /* make active viewer, currently only 1 supported... */
597                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
598                                 bNode *tnode;
599                                 
600
601                                 for(tnode= ntree->nodes.first; tnode; tnode= tnode->next)
602                                         if( ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
603                                                 tnode->flag &= ~NODE_DO_OUTPUT;
604                                 
605                                 node->flag |= NODE_DO_OUTPUT;
606                                 if(was_output==0)
607                                         ED_node_generic_update(bmain, ntree, node);
608                                 
609                                 /* addnode() doesnt link this yet... */
610                                 node->id= (ID *)BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
611                         }
612                         else if(node->type==CMP_NODE_R_LAYERS) {
613                                 Scene *scene;
614
615                                 for(scene=bmain->scene.first; scene; scene=scene->id.next) {
616                                         if(scene->nodetree && scene->use_nodes && has_nodetree(scene->nodetree, ntree)) {
617                                                 if(node->id==NULL || node->id==(ID *)scene) {
618                                                         scene->r.actlay= node->custom1;
619                                                 }
620                                         }
621                                 }
622                         }
623                         else if(node->type==CMP_NODE_COMPOSITE) {
624                                 if (was_output==0) {
625                                         bNode *tnode;
626                                         
627                                         for(tnode= ntree->nodes.first; tnode; tnode= tnode->next)
628                                                 if( tnode->type==CMP_NODE_COMPOSITE)
629                                                         tnode->flag &= ~NODE_DO_OUTPUT;
630                                         
631                                         node->flag |= NODE_DO_OUTPUT;
632                                         ED_node_generic_update(bmain, ntree, node);
633                                 }
634                         }
635                 }
636                 else if(ntree->type==NTREE_TEXTURE) {
637                         // XXX
638 #if 0
639                         if(node->id)
640                                 ; // XXX BIF_preview_changed(-1);
641                         // allqueue(REDRAWBUTSSHADING, 1);
642                         // allqueue(REDRAWIPO, 0);
643 #endif
644                 }
645         }
646 }
647
648 static int compare_nodes(bNode *a, bNode *b)
649 {
650         bNode *parent;
651         /* These tell if either the node or any of the parent nodes is selected.
652          * A selected parent means an unselected node is also in foreground!
653          */
654         int a_select=(a->flag & NODE_SELECT), b_select=(b->flag & NODE_SELECT);
655         int a_active=(a->flag & NODE_ACTIVE), b_active=(b->flag & NODE_ACTIVE);
656         
657         /* if one is an ancestor of the other */
658         /* XXX there might be a better sorting algorithm for stable topological sort, this is O(n^2) worst case */
659         for (parent = a->parent; parent; parent=parent->parent) {
660                 /* if b is an ancestor, it is always behind a */
661                 if (parent==b)
662                         return 1;
663                 /* any selected ancestor moves the node forward */
664                 if (parent->flag & NODE_ACTIVE)
665                         a_active = 1;
666                 if (parent->flag & NODE_SELECT)
667                         a_select = 1;
668         }
669         for (parent = b->parent; parent; parent=parent->parent) {
670                 /* if a is an ancestor, it is always behind b */
671                 if (parent==a)
672                         return 0;
673                 /* any selected ancestor moves the node forward */
674                 if (parent->flag & NODE_ACTIVE)
675                         b_active = 1;
676                 if (parent->flag & NODE_SELECT)
677                         b_select = 1;
678         }
679
680         /* if one of the nodes is in the background and the other not */
681         if ((a->flag & NODE_BACKGROUND) && !(b->flag & NODE_BACKGROUND))
682                 return 0;
683         else if (!(a->flag & NODE_BACKGROUND) && (b->flag & NODE_BACKGROUND))
684                 return 1;
685         
686         /* if one has a higher selection state (active > selected > nothing) */
687         if (!b_active && a_active)
688                 return 1;
689         else if (!b_select && (a_active || a_select))
690                 return 1;
691         
692         return 0;
693 }
694 /* Sorts nodes by selection: unselected nodes first, then selected,
695  * then the active node at the very end. Relative order is kept intact!
696  */
697 void node_sort(bNodeTree *ntree)
698 {
699         /* merge sort is the algorithm of choice here */
700         bNode *first_a, *first_b, *node_a, *node_b, *tmp;
701         int totnodes= BLI_countlist(&ntree->nodes);
702         int k, a, b;
703         
704         k = 1;
705         while (k < totnodes) {
706                 first_a = first_b = ntree->nodes.first;
707                 
708                 do {
709                         /* setup first_b pointer */
710                         for (b=0; b < k && first_b; ++b) {
711                                 first_b = first_b->next;
712                         }
713                         /* all batches merged? */
714                         if (first_b==NULL)
715                                 break;
716                         
717                         /* merge batches */
718                         node_a = first_a;
719                         node_b = first_b;
720                         a = b = 0;
721                         while (a < k && b < k && node_b) {
722                                 if (compare_nodes(node_a, node_b)==0) {
723                                         node_a = node_a->next;
724                                         ++a;
725                                 }
726                                 else {
727                                         tmp = node_b;
728                                         node_b = node_b->next;
729                                         ++b;
730                                         BLI_remlink(&ntree->nodes, tmp);
731                                         BLI_insertlinkbefore(&ntree->nodes, node_a, tmp);
732                                 }
733                         }
734
735                         /* setup first pointers for next batch */
736                         first_b = node_b;
737                         for (; b < k; ++b) {
738                                 /* all nodes sorted? */
739                                 if (first_b==NULL)
740                                         break;
741                                 first_b = first_b->next;
742                         }
743                         first_a = first_b;
744                 } while (first_b);
745                 
746                 k = k << 1;
747         }
748 }
749
750 static int inside_rctf(rctf *bounds, rctf *rect)
751 {
752         return (bounds->xmin <= rect->xmin && bounds->xmax >= rect->xmax
753                         && bounds->ymin <= rect->ymin && bounds->ymax >= rect->ymax);
754 }
755
756 static void node_frame_attach_nodes(bNodeTree *UNUSED(ntree), bNode *frame)
757 {
758         bNode *node;
759         
760         /* only check nodes on top of the frame for attaching */
761         for (node=frame->next; node; node=node->next) {
762                 if (node->parent==frame) {
763                         /* detach nodes that went outside the frame */
764                         if (!inside_rctf(&frame->totr, &node->totr))
765                                 nodeDetachNode(node);
766                 }
767                 else if (node->flag & NODE_SELECT && node->parent==NULL) {
768                         /* attach selected, still unparented nodes */
769                         if (inside_rctf(&frame->totr, &node->totr))
770                                 nodeAttachNode(node, frame);
771                 }
772         }
773 }
774
775 void ED_node_update_hierarchy(bContext *UNUSED(C), bNodeTree *ntree)
776 {
777         bNode *node;
778         
779         /* XXX This does not work due to layout functions relying on node->block,
780          * which only exists during actual drawing. Can we rely on valid totr rects?
781          */
782         /* make sure nodes have correct bounding boxes after transform */
783 //      node_update_nodetree(C, ntree, 0.0f, 0.0f);
784         
785         /* all selected nodes are re-parented */
786         for (node=ntree->nodes.last; node; node=node->prev) {
787                 if (node->flag & NODE_SELECT && node->parent)
788                         nodeDetachNode(node);
789         }
790         
791         /* update higher Z-level nodes first */
792         for (node=ntree->nodes.last; node; node=node->prev) {
793                 /* XXX callback? */
794                 if (node->type==NODE_FRAME)
795                         node_frame_attach_nodes(ntree, node);
796         }
797 }
798
799 /* ***************** generic operator functions for nodes ***************** */
800
801 #if 0 /* UNUSED */
802
803 static int edit_node_poll(bContext *C)
804 {
805         return ED_operator_node_active(C);
806 }
807
808 static void edit_node_properties(wmOperatorType *ot)
809 {
810         /* XXX could node be a context pointer? */
811         RNA_def_string(ot->srna, "node", "", 32, "Node", "");
812         RNA_def_int(ot->srna, "socket", 0, 0, MAX_SOCKET, "Socket", "", 0, MAX_SOCKET);
813         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Side", "");
814 }
815
816 static int edit_node_invoke_properties(bContext *C, wmOperator *op)
817 {
818         if (!RNA_property_is_set(op->ptr, "node")) {
819                 bNode *node= CTX_data_pointer_get_type(C, "node", &RNA_Node).data;
820                 if (!node)
821                         return 0;
822                 else
823                         RNA_string_set(op->ptr, "node", node->name);
824         }
825         
826         if (!RNA_property_is_set(op->ptr, "in_out"))
827                 RNA_enum_set(op->ptr, "in_out", SOCK_IN);
828         
829         if (!RNA_property_is_set(op->ptr, "socket"))
830                 RNA_int_set(op->ptr, "socket", 0);
831         
832         return 1;
833 }
834
835 static void edit_node_properties_get(wmOperator *op, bNodeTree *ntree, bNode **rnode, bNodeSocket **rsock, int *rin_out)
836 {
837         bNode *node;
838         bNodeSocket *sock=NULL;
839         char nodename[32];
840         int sockindex;
841         int in_out;
842         
843         RNA_string_get(op->ptr, "node", nodename);
844         node = nodeFindNodebyName(ntree, nodename);
845         
846         in_out = RNA_enum_get(op->ptr, "in_out");
847         
848         sockindex = RNA_int_get(op->ptr, "socket");
849         switch (in_out) {
850         case SOCK_IN:   sock = BLI_findlink(&node->inputs, sockindex);  break;
851         case SOCK_OUT:  sock = BLI_findlink(&node->outputs, sockindex); break;
852         }
853         
854         if (rnode)
855                 *rnode = node;
856         if (rsock)
857                 *rsock = sock;
858         if (rin_out)
859                 *rin_out = in_out;
860 }
861 #endif
862
863 /* ***************** Edit Group operator ************* */
864
865 void snode_make_group_editable(SpaceNode *snode, bNode *gnode)
866 {
867         bNode *node;
868         
869         /* make sure nothing has group editing on */
870         for(node=snode->nodetree->nodes.first; node; node=node->next)
871                 nodeGroupEditClear(node);
872         
873         if(gnode==NULL) {
874                 /* with NULL argument we do a toggle */
875                 if(snode->edittree==snode->nodetree)
876                         gnode= nodeGetActive(snode->nodetree);
877         }
878         
879         if (gnode) {
880                 snode->edittree = nodeGroupEditSet(gnode, 1);
881                 
882                 /* deselect all other nodes, so we can also do grabbing of entire subtree */
883                 for(node= snode->nodetree->nodes.first; node; node= node->next)
884                         node->flag &= ~SELECT;
885                 gnode->flag |= SELECT;
886         }
887         else 
888                 snode->edittree= snode->nodetree;
889 }
890
891 static int node_group_edit_exec(bContext *C, wmOperator *UNUSED(op))
892 {
893         SpaceNode *snode = CTX_wm_space_node(C);
894
895         ED_preview_kill_jobs(C);
896
897         if (snode->nodetree==snode->edittree) {
898                 bNode *gnode= nodeGetActive(snode->nodetree);
899                 snode_make_group_editable(snode, gnode);
900         }
901         else
902                 snode_make_group_editable(snode, NULL);
903
904         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL);
905
906         return OPERATOR_FINISHED;
907 }
908
909 static int node_group_edit_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
910 {
911         SpaceNode *snode = CTX_wm_space_node(C);
912         bNode *gnode;
913
914         gnode= nodeGetActive(snode->edittree);
915         /* XXX callback? */
916         if(gnode && gnode->id && GS(gnode->id->name)==ID_NT && gnode->id->lib) {
917                 uiPupMenuOkee(C, op->type->idname, "Make group local?");
918                 return OPERATOR_CANCELLED;
919         }
920
921         return node_group_edit_exec(C, op);
922 }
923
924 void NODE_OT_group_edit(wmOperatorType *ot)
925 {
926         /* identifiers */
927         ot->name = "Edit Group";
928         ot->description = "Edit node group";
929         ot->idname = "NODE_OT_group_edit";
930         
931         /* api callbacks */
932         ot->invoke = node_group_edit_invoke;
933         ot->exec = node_group_edit_exec;
934         ot->poll = ED_operator_node_active;
935         
936         /* flags */
937         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
938 }
939
940 /* ***************** Add Group Socket operator ************* */
941
942 static int node_group_socket_add_exec(bContext *C, wmOperator *op)
943 {
944         SpaceNode *snode = CTX_wm_space_node(C);
945         int in_out= -1;
946         char name[32]= "";
947         int type= SOCK_FLOAT;
948         bNodeTree *ngroup= snode->edittree;
949         /* bNodeSocket *sock; */ /* UNUSED */
950         
951         ED_preview_kill_jobs(C);
952         
953         if (RNA_property_is_set(op->ptr, "name"))
954                 RNA_string_get(op->ptr, "name", name);
955         
956         if (RNA_property_is_set(op->ptr, "type"))
957                 type = RNA_enum_get(op->ptr, "type");
958         
959         if (RNA_property_is_set(op->ptr, "in_out"))
960                 in_out = RNA_enum_get(op->ptr, "in_out");
961         else
962                 return OPERATOR_CANCELLED;
963         
964         /* using placeholder subtype first */
965         /* sock = */ /* UNUSED */ node_group_add_socket(ngroup, name, type, in_out);
966         
967         ntreeUpdateTree(ngroup);
968         
969         snode_notify(C, snode);
970         
971         return OPERATOR_FINISHED;
972 }
973
974 void NODE_OT_group_socket_add(wmOperatorType *ot)
975 {
976         /* identifiers */
977         ot->name = "Add Group Socket";
978         ot->description = "Add node group socket";
979         ot->idname = "NODE_OT_group_socket_add";
980         
981         /* api callbacks */
982         ot->exec = node_group_socket_add_exec;
983         ot->poll = ED_operator_node_active;
984         
985         /* flags */
986         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
987         
988         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
989         RNA_def_string(ot->srna, "name", "", 32, "Name", "Group socket name");
990         RNA_def_enum(ot->srna, "type", node_socket_type_items, SOCK_FLOAT, "Type", "Type of the group socket");
991 }
992
993 /* ***************** Remove Group Socket operator ************* */
994
995 static int node_group_socket_remove_exec(bContext *C, wmOperator *op)
996 {
997         SpaceNode *snode = CTX_wm_space_node(C);
998         int index= -1;
999         int in_out= -1;
1000         bNodeTree *ngroup= snode->edittree;
1001         bNodeSocket *sock;
1002         
1003         ED_preview_kill_jobs(C);
1004         
1005         if (RNA_property_is_set(op->ptr, "index"))
1006                 index = RNA_int_get(op->ptr, "index");
1007         else
1008                 return OPERATOR_CANCELLED;
1009         
1010         if (RNA_property_is_set(op->ptr, "in_out"))
1011                 in_out = RNA_enum_get(op->ptr, "in_out");
1012         else
1013                 return OPERATOR_CANCELLED;
1014         
1015         sock = (bNodeSocket*)BLI_findlink(in_out==SOCK_IN ? &ngroup->inputs : &ngroup->outputs, index);
1016         if (sock) {
1017                 node_group_remove_socket(ngroup, sock, in_out);
1018                 ntreeUpdateTree(ngroup);
1019                 
1020                 snode_notify(C, snode);
1021         }
1022         
1023         return OPERATOR_FINISHED;
1024 }
1025
1026 void NODE_OT_group_socket_remove(wmOperatorType *ot)
1027 {
1028         /* identifiers */
1029         ot->name = "Remove Group Socket";
1030         ot->description = "Remove a node group socket";
1031         ot->idname = "NODE_OT_group_socket_remove";
1032         
1033         /* api callbacks */
1034         ot->exec = node_group_socket_remove_exec;
1035         ot->poll = ED_operator_node_active;
1036         
1037         /* flags */
1038         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1039         
1040         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
1041         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
1042 }
1043
1044 /* ***************** Move Group Socket Up operator ************* */
1045
1046 static int node_group_socket_move_up_exec(bContext *C, wmOperator *op)
1047 {
1048         SpaceNode *snode = CTX_wm_space_node(C);
1049         int index= -1;
1050         int in_out= -1;
1051         bNodeTree *ngroup= snode->edittree;
1052         bNodeSocket *sock, *prev;
1053         
1054         ED_preview_kill_jobs(C);
1055         
1056         if (RNA_property_is_set(op->ptr, "index"))
1057                 index = RNA_int_get(op->ptr, "index");
1058         else
1059                 return OPERATOR_CANCELLED;
1060         
1061         if (RNA_property_is_set(op->ptr, "in_out"))
1062                 in_out = RNA_enum_get(op->ptr, "in_out");
1063         else
1064                 return OPERATOR_CANCELLED;
1065         
1066         /* swap */
1067         if (in_out==SOCK_IN) {
1068                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
1069                 prev = sock->prev;
1070                 /* can't move up the first socket */
1071                 if (!prev)
1072                         return OPERATOR_CANCELLED;
1073                 BLI_remlink(&ngroup->inputs, sock);
1074                 BLI_insertlinkbefore(&ngroup->inputs, prev, sock);
1075                 
1076                 ngroup->update |= NTREE_UPDATE_GROUP_IN;
1077         }
1078         else if (in_out==SOCK_OUT) {
1079                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
1080                 prev = sock->prev;
1081                 /* can't move up the first socket */
1082                 if (!prev)
1083                         return OPERATOR_CANCELLED;
1084                 BLI_remlink(&ngroup->outputs, sock);
1085                 BLI_insertlinkbefore(&ngroup->outputs, prev, sock);
1086                 
1087                 ngroup->update |= NTREE_UPDATE_GROUP_OUT;
1088         }
1089         ntreeUpdateTree(ngroup);
1090         
1091         snode_notify(C, snode);
1092         
1093         return OPERATOR_FINISHED;
1094 }
1095
1096 void NODE_OT_group_socket_move_up(wmOperatorType *ot)
1097 {
1098         /* identifiers */
1099         ot->name = "Move Group Socket Up";
1100         ot->description = "Move up node group socket";
1101         ot->idname = "NODE_OT_group_socket_move_up";
1102         
1103         /* api callbacks */
1104         ot->exec = node_group_socket_move_up_exec;
1105         ot->poll = ED_operator_node_active;
1106         
1107         /* flags */
1108         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1109         
1110         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
1111         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
1112 }
1113
1114 /* ***************** Move Group Socket Up operator ************* */
1115
1116 static int node_group_socket_move_down_exec(bContext *C, wmOperator *op)
1117 {
1118         SpaceNode *snode = CTX_wm_space_node(C);
1119         int index= -1;
1120         int in_out= -1;
1121         bNodeTree *ngroup= snode->edittree;
1122         bNodeSocket *sock, *next;
1123         
1124         ED_preview_kill_jobs(C);
1125         
1126         if (RNA_property_is_set(op->ptr, "index"))
1127                 index = RNA_int_get(op->ptr, "index");
1128         else
1129                 return OPERATOR_CANCELLED;
1130         
1131         if (RNA_property_is_set(op->ptr, "in_out"))
1132                 in_out = RNA_enum_get(op->ptr, "in_out");
1133         else
1134                 return OPERATOR_CANCELLED;
1135         
1136         /* swap */
1137         if (in_out==SOCK_IN) {
1138                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
1139                 next = sock->next;
1140                 /* can't move down the last socket */
1141                 if (!next)
1142                         return OPERATOR_CANCELLED;
1143                 BLI_remlink(&ngroup->inputs, sock);
1144                 BLI_insertlinkafter(&ngroup->inputs, next, sock);
1145                 
1146                 ngroup->update |= NTREE_UPDATE_GROUP_IN;
1147         }
1148         else if (in_out==SOCK_OUT) {
1149                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
1150                 next = sock->next;
1151                 /* can't move down the last socket */
1152                 if (!next)
1153                         return OPERATOR_CANCELLED;
1154                 BLI_remlink(&ngroup->outputs, sock);
1155                 BLI_insertlinkafter(&ngroup->outputs, next, sock);
1156                 
1157                 ngroup->update |= NTREE_UPDATE_GROUP_OUT;
1158         }
1159         ntreeUpdateTree(ngroup);
1160         
1161         snode_notify(C, snode);
1162         
1163         return OPERATOR_FINISHED;
1164 }
1165
1166 void NODE_OT_group_socket_move_down(wmOperatorType *ot)
1167 {
1168         /* identifiers */
1169         ot->name = "Move Group Socket Down";
1170         ot->description = "Move down node group socket";
1171         ot->idname = "NODE_OT_group_socket_move_down";
1172         
1173         /* api callbacks */
1174         ot->exec = node_group_socket_move_down_exec;
1175         ot->poll = ED_operator_node_active;
1176         
1177         /* flags */
1178         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1179         
1180         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
1181         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
1182 }
1183
1184 /* ******************** Ungroup operator ********************** */
1185
1186 static int node_group_ungroup_exec(bContext *C, wmOperator *op)
1187 {
1188         SpaceNode *snode = CTX_wm_space_node(C);
1189         bNode *gnode;
1190
1191         ED_preview_kill_jobs(C);
1192
1193         /* are we inside of a group? */
1194         gnode= node_tree_get_editgroup(snode->nodetree);
1195         if(gnode)
1196                 snode_make_group_editable(snode, NULL);
1197         
1198         gnode= nodeGetActive(snode->edittree);
1199         if(gnode==NULL)
1200                 return OPERATOR_CANCELLED;
1201         
1202         if(gnode->type!=NODE_GROUP) {
1203                 BKE_report(op->reports, RPT_WARNING, "Not a group");
1204                 return OPERATOR_CANCELLED;
1205         }
1206         else if(!node_group_ungroup(snode->edittree, gnode)) {
1207                 BKE_report(op->reports, RPT_WARNING, "Can't ungroup");
1208                 return OPERATOR_CANCELLED;
1209         }
1210
1211         snode_notify(C, snode);
1212         snode_dag_update(C, snode);
1213
1214         return OPERATOR_FINISHED;
1215 }
1216
1217 void NODE_OT_group_ungroup(wmOperatorType *ot)
1218 {
1219         /* identifiers */
1220         ot->name = "Ungroup";
1221         ot->description = "Ungroup selected nodes";
1222         ot->idname = "NODE_OT_group_ungroup";
1223         
1224         /* api callbacks */
1225         ot->exec = node_group_ungroup_exec;
1226         ot->poll = ED_operator_node_active;
1227         
1228         /* flags */
1229         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1230 }
1231
1232 /* ************************** Node generic ************** */
1233
1234 /* is rct in visible part of node? */
1235 static bNode *visible_node(SpaceNode *snode, rctf *rct)
1236 {
1237         bNode *node;
1238         
1239         for(node=snode->edittree->nodes.last; node; node=node->prev) {
1240                 if(BLI_isect_rctf(&node->totr, rct, NULL))
1241                         break;
1242         }
1243         return node;
1244 }
1245
1246 /* **************************** */
1247
1248 typedef struct NodeViewMove {
1249         int mvalo[2];
1250         int xmin, ymin, xmax, ymax;
1251 } NodeViewMove;
1252
1253 static int snode_bg_viewmove_modal(bContext *C, wmOperator *op, wmEvent *event)
1254 {
1255         SpaceNode *snode= CTX_wm_space_node(C);
1256         ARegion *ar= CTX_wm_region(C);
1257         NodeViewMove *nvm= op->customdata;
1258
1259         switch (event->type) {
1260                 case MOUSEMOVE:
1261                         
1262                         snode->xof -= (nvm->mvalo[0]-event->mval[0]);
1263                         snode->yof -= (nvm->mvalo[1]-event->mval[1]);
1264                         nvm->mvalo[0]= event->mval[0];
1265                         nvm->mvalo[1]= event->mval[1];
1266                         
1267                         /* prevent dragging image outside of the window and losing it! */
1268                         CLAMP(snode->xof, nvm->xmin, nvm->xmax);
1269                         CLAMP(snode->yof, nvm->ymin, nvm->ymax);
1270                         
1271                         ED_region_tag_redraw(ar);
1272                         
1273                         break;
1274                         
1275                 case LEFTMOUSE:
1276                 case MIDDLEMOUSE:
1277                 case RIGHTMOUSE:
1278                         
1279                         MEM_freeN(nvm);
1280                         op->customdata= NULL;
1281
1282                         WM_event_add_notifier(C, NC_SPACE|ND_SPACE_NODE, NULL);
1283                         
1284                         return OPERATOR_FINISHED;
1285         }
1286         
1287         return OPERATOR_RUNNING_MODAL;
1288 }
1289
1290 static int snode_bg_viewmove_invoke(bContext *C, wmOperator *op, wmEvent *event)
1291 {
1292         ARegion *ar= CTX_wm_region(C);
1293         NodeViewMove *nvm;
1294         Image *ima;
1295         ImBuf *ibuf;
1296         int pad= 10;
1297         void *lock;
1298         
1299         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1300         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1301         
1302         if(ibuf == NULL) {
1303                 BKE_image_release_ibuf(ima, lock);
1304                 return OPERATOR_CANCELLED;
1305         }
1306
1307         nvm= MEM_callocN(sizeof(NodeViewMove), "NodeViewMove struct");
1308         op->customdata= nvm;
1309         nvm->mvalo[0]= event->mval[0];
1310         nvm->mvalo[1]= event->mval[1];
1311
1312         nvm->xmin = -(ar->winx/2) - ibuf->x/2 + pad;
1313         nvm->xmax = ar->winx/2 + ibuf->x/2 - pad;
1314         nvm->ymin = -(ar->winy/2) - ibuf->y/2 + pad;
1315         nvm->ymax = ar->winy/2 + ibuf->y/2 - pad;
1316
1317         BKE_image_release_ibuf(ima, lock);
1318         
1319         /* add modal handler */
1320         WM_event_add_modal_handler(C, op);
1321         
1322         return OPERATOR_RUNNING_MODAL;
1323 }
1324
1325 static int snode_bg_viewmove_cancel(bContext *UNUSED(C), wmOperator *op)
1326 {
1327         MEM_freeN(op->customdata);
1328         op->customdata= NULL;
1329
1330         return OPERATOR_CANCELLED;
1331 }
1332
1333 void NODE_OT_backimage_move(wmOperatorType *ot)
1334 {
1335         /* identifiers */
1336         ot->name= "Background Image Move";
1337         ot->description = "Move Node backdrop";
1338         ot->idname= "NODE_OT_backimage_move";
1339         
1340         /* api callbacks */
1341         ot->invoke= snode_bg_viewmove_invoke;
1342         ot->modal= snode_bg_viewmove_modal;
1343         ot->poll= composite_node_active;
1344         ot->cancel= snode_bg_viewmove_cancel;
1345         
1346         /* flags */
1347         ot->flag= OPTYPE_BLOCKING|OPTYPE_GRAB_POINTER;
1348 }
1349
1350 static int backimage_zoom(bContext *C, wmOperator *op)
1351 {
1352         SpaceNode *snode= CTX_wm_space_node(C);
1353         ARegion *ar= CTX_wm_region(C);
1354         float fac= RNA_float_get(op->ptr, "factor");
1355
1356         snode->zoom *= fac;
1357         ED_region_tag_redraw(ar);
1358
1359         return OPERATOR_FINISHED;
1360 }
1361
1362
1363 void NODE_OT_backimage_zoom(wmOperatorType *ot)
1364 {
1365         
1366         /* identifiers */
1367         ot->name= "Background Image Zoom";
1368         ot->idname= "NODE_OT_backimage_zoom";
1369         
1370         /* api callbacks */
1371         ot->exec= backimage_zoom;
1372         ot->poll= composite_node_active;
1373         
1374         /* flags */
1375         ot->flag= OPTYPE_BLOCKING;
1376
1377         /* internal */
1378         RNA_def_float(ot->srna, "factor", 1.2f, 0.0f, 10.0f, "Factor", "", 0.0f, 10.0f);
1379 }
1380
1381 /******************** sample backdrop operator ********************/
1382
1383 typedef struct ImageSampleInfo {
1384         ARegionType *art;
1385         void *draw_handle;
1386         int x, y;
1387         int channels;
1388         int color_manage;
1389
1390         char col[4];
1391         float colf[4];
1392
1393         int draw;
1394 } ImageSampleInfo;
1395
1396 static void sample_draw(const bContext *C, ARegion *ar, void *arg_info)
1397 {
1398         ImageSampleInfo *info= arg_info;
1399
1400         draw_nodespace_color_info(ar, (CTX_data_scene(C)->r.color_mgt_flag & R_COLOR_MANAGEMENT), info->channels,
1401                                                           info->x, info->y, info->col, info->colf);
1402 }
1403
1404 static void sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1405 {
1406         SpaceNode *snode= CTX_wm_space_node(C);
1407         ARegion *ar= CTX_wm_region(C);
1408         ImageSampleInfo *info= op->customdata;
1409         void *lock;
1410         Image *ima;
1411         ImBuf *ibuf;
1412         float fx, fy, bufx, bufy;
1413         
1414         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1415         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1416         if(!ibuf)
1417                 return;
1418         
1419         if(!ibuf->rect) {
1420                 if(info->color_manage)
1421                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1422                 else
1423                         ibuf->profile = IB_PROFILE_NONE;
1424                 IMB_rect_from_float(ibuf);
1425         }
1426
1427         /* map the mouse coords to the backdrop image space */
1428         bufx = ibuf->x * snode->zoom;
1429         bufy = ibuf->y * snode->zoom;
1430         fx = (bufx > 0.0f ? ((float)event->mval[0] - 0.5f*ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
1431         fy = (bufy > 0.0f ? ((float)event->mval[1] - 0.5f*ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
1432
1433         if(fx>=0.0f && fy>=0.0f && fx<1.0f && fy<1.0f) {
1434                 float *fp;
1435                 char *cp;
1436                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1437
1438                 CLAMP(x, 0, ibuf->x-1);
1439                 CLAMP(y, 0, ibuf->y-1);
1440
1441                 info->x= x;
1442                 info->y= y;
1443                 info->draw= 1;
1444                 info->channels= ibuf->channels;
1445
1446                 if(ibuf->rect) {
1447                         cp= (char *)(ibuf->rect + y*ibuf->x + x);
1448
1449                         info->col[0]= cp[0];
1450                         info->col[1]= cp[1];
1451                         info->col[2]= cp[2];
1452                         info->col[3]= cp[3];
1453
1454                         info->colf[0]= (float)cp[0]/255.0f;
1455                         info->colf[1]= (float)cp[1]/255.0f;
1456                         info->colf[2]= (float)cp[2]/255.0f;
1457                         info->colf[3]= (float)cp[3]/255.0f;
1458                 }
1459                 if(ibuf->rect_float) {
1460                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1461
1462                         info->colf[0]= fp[0];
1463                         info->colf[1]= fp[1];
1464                         info->colf[2]= fp[2];
1465                         info->colf[3]= fp[3];
1466                 }
1467         }
1468         else
1469                 info->draw= 0;
1470
1471         BKE_image_release_ibuf(ima, lock);
1472         
1473         ED_area_tag_redraw(CTX_wm_area(C));
1474 }
1475
1476 static void sample_exit(bContext *C, wmOperator *op)
1477 {
1478         ImageSampleInfo *info= op->customdata;
1479
1480         ED_region_draw_cb_exit(info->art, info->draw_handle);
1481         ED_area_tag_redraw(CTX_wm_area(C));
1482         MEM_freeN(info);
1483 }
1484
1485 static int sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1486 {
1487         SpaceNode *snode= CTX_wm_space_node(C);
1488         ARegion *ar= CTX_wm_region(C);
1489         ImageSampleInfo *info;
1490
1491         if(snode->treetype!=NTREE_COMPOSIT || !(snode->flag & SNODE_BACKDRAW))
1492                 return OPERATOR_CANCELLED;
1493         
1494         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1495         info->art= ar->type;
1496         info->draw_handle = ED_region_draw_cb_activate(ar->type, sample_draw, info, REGION_DRAW_POST_PIXEL);
1497         op->customdata= info;
1498
1499         sample_apply(C, op, event);
1500
1501         WM_event_add_modal_handler(C, op);
1502
1503         return OPERATOR_RUNNING_MODAL;
1504 }
1505
1506 static int sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1507 {
1508         switch(event->type) {
1509                 case LEFTMOUSE:
1510                 case RIGHTMOUSE: // XXX hardcoded
1511                         sample_exit(C, op);
1512                         return OPERATOR_CANCELLED;
1513                 case MOUSEMOVE:
1514                         sample_apply(C, op, event);
1515                         break;
1516         }
1517
1518         return OPERATOR_RUNNING_MODAL;
1519 }
1520
1521 static int sample_cancel(bContext *C, wmOperator *op)
1522 {
1523         sample_exit(C, op);
1524         return OPERATOR_CANCELLED;
1525 }
1526
1527 void NODE_OT_backimage_sample(wmOperatorType *ot)
1528 {
1529         /* identifiers */
1530         ot->name= "Backimage Sample";
1531         ot->idname= "NODE_OT_backimage_sample";
1532         
1533         /* api callbacks */
1534         ot->invoke= sample_invoke;
1535         ot->modal= sample_modal;
1536         ot->cancel= sample_cancel;
1537         ot->poll= ED_operator_node_active;
1538
1539         /* flags */
1540         ot->flag= OPTYPE_BLOCKING;
1541 }
1542
1543 /* ********************** size widget operator ******************** */
1544
1545 typedef struct NodeSizeWidget {
1546         float mxstart, mystart;
1547         float oldwidth, oldheight;
1548         float oldminiwidth;
1549 } NodeSizeWidget;
1550
1551 static int node_resize_modal(bContext *C, wmOperator *op, wmEvent *event)
1552 {
1553         SpaceNode *snode= CTX_wm_space_node(C);
1554         ARegion *ar= CTX_wm_region(C);
1555         bNode *node= editnode_get_active(snode->edittree);
1556         NodeSizeWidget *nsw= op->customdata;
1557         float mx, my;
1558         
1559         switch (event->type) {
1560                 case MOUSEMOVE:
1561                         
1562                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1563                                                                          &mx, &my);
1564                         
1565                         if (node) {
1566                                 if(node->flag & NODE_HIDDEN) {
1567                                         node->miniwidth= nsw->oldminiwidth + mx - nsw->mxstart;
1568                                         CLAMP(node->miniwidth, 0.0f, 100.0f);
1569                                 }
1570                                 else {
1571                                         node->width= nsw->oldwidth + mx - nsw->mxstart;
1572                                         CLAMP(node->width, UI_DPI_FAC*node->typeinfo->minwidth, UI_DPI_FAC*node->typeinfo->maxwidth);
1573                                 }
1574                                 /* height works the other way round ... */
1575                                 node->height= nsw->oldheight - my + nsw->mystart;
1576                                 CLAMP(node->height, node->typeinfo->minheight, node->typeinfo->maxheight);
1577                         }
1578                                 
1579                         ED_region_tag_redraw(ar);
1580
1581                         break;
1582                         
1583                 case LEFTMOUSE:
1584                 case MIDDLEMOUSE:
1585                 case RIGHTMOUSE:
1586                         
1587                         MEM_freeN(nsw);
1588                         op->customdata= NULL;
1589                         
1590                         ED_node_update_hierarchy(C, snode->edittree);
1591                         
1592                         return OPERATOR_FINISHED;
1593         }
1594         
1595         return OPERATOR_RUNNING_MODAL;
1596 }
1597
1598 static int node_resize_invoke(bContext *C, wmOperator *op, wmEvent *event)
1599 {
1600         SpaceNode *snode= CTX_wm_space_node(C);
1601         ARegion *ar= CTX_wm_region(C);
1602         bNode *node= editnode_get_active(snode->edittree);
1603         
1604         if(node) {
1605                 /* convert mouse coordinates to v2d space */
1606                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1607                                                                  &snode->mx, &snode->my);
1608                 
1609                 if(node->typeinfo->resize_area_func(node, snode->mx, snode->my)) {
1610                         NodeSizeWidget *nsw= MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
1611                         
1612                         op->customdata= nsw;
1613                         nsw->mxstart= snode->mx;
1614                         nsw->mystart= snode->my;
1615                         
1616                         /* store old */
1617                         nsw->oldwidth= node->width;
1618                         nsw->oldheight= node->height;
1619                         nsw->oldminiwidth= node->miniwidth;
1620                         
1621                         /* add modal handler */
1622                         WM_event_add_modal_handler(C, op);
1623
1624                         return OPERATOR_RUNNING_MODAL;
1625                 }
1626         }
1627         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
1628 }
1629
1630 static int node_resize_cancel(bContext *UNUSED(C), wmOperator *op)
1631 {
1632         MEM_freeN(op->customdata);
1633         op->customdata= NULL;
1634
1635         return OPERATOR_CANCELLED;
1636 }
1637
1638 void NODE_OT_resize(wmOperatorType *ot)
1639 {
1640         /* identifiers */
1641         ot->name= "Resize Node";
1642         ot->idname= "NODE_OT_resize";
1643         
1644         /* api callbacks */
1645         ot->invoke= node_resize_invoke;
1646         ot->modal= node_resize_modal;
1647         ot->poll= ED_operator_node_active;
1648         ot->cancel= node_resize_cancel;
1649         
1650         /* flags */
1651         ot->flag= OPTYPE_BLOCKING;
1652 }
1653
1654 /* ********************** select ******************** */
1655
1656
1657 /* no undo here! */
1658 void node_deselectall(SpaceNode *snode)
1659 {
1660         bNode *node;
1661         
1662         for(node= snode->edittree->nodes.first; node; node= node->next)
1663                 node->flag &= ~SELECT;
1664 }
1665
1666 /* return 1 if we need redraw otherwise zero. */
1667 int node_select_same_type(SpaceNode *snode)
1668 {
1669         bNode *nac, *p;
1670         int redraw;
1671
1672         /* search for the active node. */
1673         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1674                 if (nac->flag & SELECT)
1675                         break;
1676         }
1677
1678         /* no active node, return. */
1679         if (!nac)
1680                 return(0);
1681
1682         redraw= 0;
1683         for (p= snode->edittree->nodes.first; p; p= p->next) {
1684                 if (p->type != nac->type && p->flag & SELECT) {
1685                         /* if it's selected but different type, unselect */
1686                         redraw= 1;
1687                         p->flag &= ~SELECT;
1688                 }
1689                 else if (p->type == nac->type && (!(p->flag & SELECT))) {
1690                         /* if it's the same type and is not selected, select! */
1691                         redraw= 1;
1692                         p->flag |= SELECT;
1693                 }
1694         }
1695         return(redraw);
1696 }
1697
1698 /* return 1 if we need redraw, otherwise zero.
1699  * dir can be 0 == next or 0 != prev.
1700  */
1701 int node_select_same_type_np(SpaceNode *snode, int dir)
1702 {
1703         bNode *nac, *p;
1704
1705         /* search the active one. */
1706         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1707                 if (nac->flag & SELECT)
1708                         break;
1709         }
1710
1711         /* no active node, return. */
1712         if (!nac)
1713                 return(0);
1714
1715         if (dir == 0)
1716                 p= nac->next;
1717         else
1718                 p= nac->prev;
1719
1720         while (p) {
1721                 /* Now search the next with the same type. */
1722                 if (p->type == nac->type)
1723                         break;
1724
1725                 if (dir == 0)
1726                         p= p->next;
1727                 else
1728                         p= p->prev;
1729         }
1730
1731         if (p) {
1732                 node_deselectall(snode);
1733                 p->flag |= SELECT;
1734                 return(1);
1735         }
1736         return(0);
1737 }
1738
1739 int node_has_hidden_sockets(bNode *node)
1740 {
1741         bNodeSocket *sock;
1742         
1743         for(sock= node->inputs.first; sock; sock= sock->next)
1744                 if(sock->flag & SOCK_HIDDEN)
1745                         return 1;
1746         for(sock= node->outputs.first; sock; sock= sock->next)
1747                 if(sock->flag & SOCK_HIDDEN)
1748                         return 1;
1749         return 0;
1750 }
1751
1752 static void node_link_viewer(SpaceNode *snode, bNode *tonode)
1753 {
1754         bNode *node;
1755
1756         /* context check */
1757         if(tonode==NULL || tonode->outputs.first==NULL)
1758                 return;
1759         if( ELEM(tonode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1760                 return;
1761         
1762         /* get viewer */
1763         for(node= snode->edittree->nodes.first; node; node= node->next)
1764                 if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1765                         if(node->flag & NODE_DO_OUTPUT)
1766                                 break;
1767         /* no viewer, we make one active */
1768         if(node==NULL) {
1769                 for(node= snode->edittree->nodes.first; node; node= node->next) {
1770                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
1771                                 node->flag |= NODE_DO_OUTPUT;
1772                                 break;
1773                         }
1774                 }
1775         }
1776                 
1777         if(node) {
1778                 bNodeLink *link;
1779                 bNodeSocket *sock= NULL;
1780
1781                 /* try to find an already connected socket to cycle to the next */
1782                 for(link= snode->edittree->links.first; link; link= link->next)
1783                         if(link->tonode==node && link->fromnode==tonode)
1784                                 if(link->tosock==node->inputs.first)
1785                                         break;
1786
1787                 if(link) {
1788                         /* unlink existing connection */
1789                         sock= link->fromsock;
1790                         nodeRemLink(snode->edittree, link);
1791
1792                         /* find a socket after the previously connected socket */
1793                         for(sock=sock->next; sock; sock= sock->next)
1794                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1795                                         break;
1796                 }
1797
1798                 /* find a socket starting from the first socket */
1799                 if(!sock) {
1800                         for(sock= tonode->outputs.first; sock; sock= sock->next)
1801                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1802                                         break;
1803                 }
1804                 
1805                 if(sock) {
1806                         /* get link to viewer */
1807                         for(link= snode->edittree->links.first; link; link= link->next)
1808                                 if(link->tonode==node && link->tosock==node->inputs.first)
1809                                         break;
1810                         
1811                         if(link==NULL) {
1812                                 nodeAddLink(snode->edittree, tonode, sock, node, node->inputs.first);
1813                         }
1814                         else {
1815                                 link->fromnode= tonode;
1816                                 link->fromsock= sock;
1817                         }
1818                         ntreeUpdateTree(snode->edittree);
1819                         snode_update(snode, node);
1820                 }
1821         }
1822 }
1823
1824
1825 static int node_active_link_viewer(bContext *C, wmOperator *UNUSED(op))
1826 {
1827         SpaceNode *snode= CTX_wm_space_node(C);
1828         bNode *node;
1829         
1830         node= editnode_get_active(snode->edittree);
1831         
1832         if(!node)
1833                 return OPERATOR_CANCELLED;
1834
1835         ED_preview_kill_jobs(C);
1836
1837         node_link_viewer(snode, node);
1838         snode_notify(C, snode);
1839
1840         return OPERATOR_FINISHED;
1841 }
1842
1843
1844
1845 void NODE_OT_link_viewer(wmOperatorType *ot)
1846 {
1847         /* identifiers */
1848         ot->name= "Link to Viewer Node";
1849         ot->description = "Link to viewer node";
1850         ot->idname= "NODE_OT_link_viewer";
1851         
1852         /* api callbacks */
1853         ot->exec= node_active_link_viewer;
1854         ot->poll= ED_operator_node_active;
1855         
1856         /* flags */
1857         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1858 }
1859
1860
1861
1862 /* return 0, nothing done */
1863 static int UNUSED_FUNCTION(node_mouse_groupheader)(SpaceNode *snode)
1864 {
1865         bNode *gnode;
1866         float mx=0, my=0;
1867 // XXX  int mval[2];
1868         
1869         gnode= node_tree_get_editgroup(snode->nodetree);
1870         if(gnode==NULL) return 0;
1871         
1872 // XXX  getmouseco_areawin(mval);
1873 // XXX  areamouseco_to_ipoco(G.v2d, mval, &mx, &my);
1874         
1875         /* click in header or outside? */
1876         if(BLI_in_rctf(&gnode->totr, mx, my)==0) {
1877                 rctf rect= gnode->totr;
1878                 
1879                 rect.ymax += NODE_DY;
1880                 if(BLI_in_rctf(&rect, mx, my)==0)
1881                         snode_make_group_editable(snode, NULL); /* toggles, so exits editmode */
1882 //              else
1883 // XXX                  transform_nodes(snode->nodetree, 'g', "Move group");
1884                 
1885                 return 1;
1886         }
1887         return 0;
1888 }
1889
1890 /* checks snode->mouse position, and returns found node/socket */
1891 /* type is SOCK_IN and/or SOCK_OUT */
1892 static int find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1893 {
1894         bNode *node;
1895         bNodeSocket *sock;
1896         rctf rect;
1897         
1898         /* check if we click in a socket */
1899         for(node= snode->edittree->nodes.first; node; node= node->next) {
1900                 
1901                 rect.xmin = snode->mx - (NODE_SOCKSIZE+4);
1902                 rect.ymin = snode->my - (NODE_SOCKSIZE+4);
1903                 rect.xmax = snode->mx + (NODE_SOCKSIZE+4);
1904                 rect.ymax = snode->my + (NODE_SOCKSIZE+4);
1905                 
1906                 if (!(node->flag & NODE_HIDDEN)) {
1907                         /* extra padding inside and out - allow dragging on the text areas too */
1908                         if (in_out == SOCK_IN) {
1909                                 rect.xmax += NODE_SOCKSIZE;
1910                                 rect.xmin -= NODE_SOCKSIZE*4;
1911                         } else if (in_out == SOCK_OUT) {
1912                                 rect.xmax += NODE_SOCKSIZE*4;
1913                                 rect.xmin -= NODE_SOCKSIZE;
1914                         }
1915                 }
1916                 
1917                 if(in_out & SOCK_IN) {
1918                         for(sock= node->inputs.first; sock; sock= sock->next) {
1919                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1920                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1921                                                 if(node == visible_node(snode, &rect)) {
1922                                                         *nodep= node;
1923                                                         *sockp= sock;
1924                                                         return 1;
1925                                                 }
1926                                         }
1927                                 }
1928                         }
1929                 }
1930                 if(in_out & SOCK_OUT) {
1931                         for(sock= node->outputs.first; sock; sock= sock->next) {
1932                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1933                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1934                                                 if(node == visible_node(snode, &rect)) {
1935                                                         *nodep= node;
1936                                                         *sockp= sock;
1937                                                         return 1;
1938                                                 }
1939                                         }
1940                                 }
1941                         }
1942                 }
1943         }
1944         
1945         /* check group sockets
1946          * NB: using ngroup->outputs as input sockets and vice versa here!
1947          */
1948         if(in_out & SOCK_IN) {
1949                 for(sock= snode->edittree->outputs.first; sock; sock= sock->next) {
1950                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1951                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1952                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1953                                         *sockp= sock;
1954                                         return 1;
1955                                 }
1956                         }
1957                 }
1958         }
1959         if(in_out & SOCK_OUT) {
1960                 for(sock= snode->edittree->inputs.first; sock; sock= sock->next) {
1961                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1962                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1963                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1964                                         *sockp= sock;
1965                                         return 1;
1966                                 }
1967                         }
1968                 }
1969         }
1970         
1971         return 0;
1972 }
1973
1974 static int node_socket_hilights(SpaceNode *snode, int in_out)
1975 {
1976         bNode *node;
1977         bNodeSocket *sock, *tsock, *socksel= NULL;
1978         short redraw= 0;
1979         
1980         if(snode->edittree==NULL) return 0;
1981         
1982         /* deselect sockets */
1983         for(node= snode->edittree->nodes.first; node; node= node->next) {
1984                 for(sock= node->inputs.first; sock; sock= sock->next) {
1985                         if(sock->flag & SELECT) {
1986                                 sock->flag &= ~SELECT;
1987                                 redraw++;
1988                                 socksel= sock;
1989                         }
1990                 }
1991                 for(sock= node->outputs.first; sock; sock= sock->next) {
1992                         if(sock->flag & SELECT) {
1993                                 sock->flag &= ~SELECT;
1994                                 redraw++;
1995                                 socksel= sock;
1996                         }
1997                 }
1998         }
1999         
2000         // XXX mousepos should be set here!
2001         
2002         if(find_indicated_socket(snode, &node, &tsock, in_out)) {
2003                 tsock->flag |= SELECT;
2004                 if(redraw==1 && tsock==socksel) redraw= 0;
2005                 else redraw= 1;
2006         }
2007         
2008         return redraw;
2009 }
2010
2011 static int outside_group_rect(SpaceNode *snode)
2012 {
2013         bNode *gnode= node_tree_get_editgroup(snode->nodetree);
2014         if (gnode) {
2015                 return (snode->mx < gnode->totr.xmin || snode->mx >= gnode->totr.xmax
2016                                 || snode->my < gnode->totr.ymin || snode->my >= gnode->totr.ymax);
2017         }
2018         return 0;
2019 }
2020
2021 /* ****************** Add *********************** */
2022
2023
2024 typedef struct bNodeListItem {
2025         struct bNodeListItem *next, *prev;
2026         struct bNode *node;     
2027 } bNodeListItem;
2028
2029 static int sort_nodes_locx(void *a, void *b)
2030 {
2031         bNodeListItem *nli1 = (bNodeListItem *)a;
2032         bNodeListItem *nli2 = (bNodeListItem *)b;
2033         bNode *node1 = nli1->node;
2034         bNode *node2 = nli2->node;
2035         
2036         if (node1->locx > node2->locx)
2037                 return 1;
2038         else 
2039                 return 0;
2040 }
2041
2042 static int socket_is_available(bNodeTree *ntree, bNodeSocket *sock, int allow_used)
2043 {
2044         if (sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))
2045                 return 0;
2046         
2047         if (!allow_used) {
2048                 if (nodeCountSocketLinks(ntree, sock) > 0)
2049                         return 0;
2050         }
2051         return 1;
2052 }
2053
2054 static bNodeSocket *best_socket_output(bNodeTree *ntree, bNode *node, bNodeSocket *sock_target, int allow_multiple)
2055 {
2056         bNodeSocket *sock;
2057         
2058         /* first try to find a socket with a matching name */
2059         for (sock=node->outputs.first; sock; sock=sock->next) {
2060
2061                 if (!socket_is_available(ntree, sock, allow_multiple))
2062                         continue;
2063
2064                 /* check for same types */
2065                 if (sock->type == sock_target->type) {
2066                         if (strcmp(sock->name, sock_target->name)==0)
2067                                 return sock;
2068                 }
2069         }
2070         
2071         /* otherwise settle for the first available socket of the right type */
2072         for (sock=node->outputs.first; sock; sock=sock->next) {
2073
2074                 if (!socket_is_available(ntree, sock, allow_multiple))
2075                         continue;
2076                 
2077                 /* check for same types */
2078                 if (sock->type == sock_target->type) {
2079                         return sock;
2080                 }
2081         }
2082         
2083         return NULL;
2084 }
2085
2086 /* this is a bit complicated, but designed to prioritise finding 
2087  * sockets of higher types, such as image, first */
2088 static bNodeSocket *best_socket_input(bNodeTree *ntree, bNode *node, int num, int replace)
2089 {
2090         bNodeSocket *sock;
2091         int socktype, maxtype=0;
2092         int a = 0;
2093         
2094         for (sock=node->inputs.first; sock; sock=sock->next) {
2095                 maxtype = MAX2(sock->type, maxtype);
2096         }
2097         
2098         /* find sockets of higher 'types' first (i.e. image) */
2099         for (socktype=maxtype; socktype >= 0; socktype--) {
2100                 for (sock=node->inputs.first; sock; sock=sock->next) {
2101                         
2102                         if (!socket_is_available(ntree, sock, replace)) {
2103                                 a++;
2104                                 continue;
2105                         }
2106                                 
2107                         if (sock->type == socktype) {
2108                                 /* increment to make sure we don't keep finding 
2109                                  * the same socket on every attempt running this function */
2110                                 a++;
2111                                 if (a > num)
2112                                         return sock;
2113                         }
2114                 }
2115         }
2116         
2117         return NULL;
2118 }
2119
2120 void snode_autoconnect(SpaceNode *snode, int allow_multiple, int replace)
2121 {
2122         ListBase *nodelist = MEM_callocN(sizeof(ListBase), "items_list");
2123         bNodeListItem *nli;
2124         bNode *node;
2125         bNodeLink *link;
2126         int i, numlinks=0;
2127         
2128         for(node= snode->edittree->nodes.first; node; node= node->next) {
2129                 if(node->flag & NODE_SELECT) {
2130                         nli = MEM_mallocN(sizeof(bNodeListItem), "temporary node list item");
2131                         nli->node = node;
2132                         BLI_addtail(nodelist, nli);
2133                 }
2134         }
2135         
2136         /* sort nodes left to right */
2137         BLI_sortlist(nodelist, sort_nodes_locx);
2138         
2139         for (nli=nodelist->first; nli; nli=nli->next) {
2140                 bNode *node_fr, *node_to;
2141                 bNodeSocket *sock_fr, *sock_to;
2142                 
2143                 if (nli->next == NULL) break;
2144                 
2145                 node_fr = nli->node;
2146                 node_to = nli->next->node;
2147                 
2148                 /* check over input sockets first */
2149                 for (i=0; i<BLI_countlist(&node_to->inputs); i++) {
2150                         
2151                         /* find the best guess input socket */
2152                         sock_to = best_socket_input(snode->edittree, node_to, i, replace);
2153                         if (!sock_to) continue;
2154                         
2155                         /* check for an appropriate output socket to connect from */
2156                         sock_fr = best_socket_output(snode->edittree, node_fr, sock_to, allow_multiple);
2157                         if (!sock_fr) continue;
2158                         
2159                         /* then we can connect */
2160                         if (replace)
2161                                 nodeRemSocketLinks(snode->edittree, sock_to);
2162                         
2163                         link = nodeAddLink(snode->edittree, node_fr, sock_fr, node_to, sock_to);
2164                         /* validate the new link */
2165                         ntreeUpdateTree(snode->edittree);
2166                         if (!(link->flag & NODE_LINK_VALID)) {
2167                                 nodeRemLink(snode->edittree, link);
2168                                 continue;
2169                         }
2170                         
2171                         snode_update(snode, node_to);
2172                         ++numlinks;
2173                         break;
2174                 }
2175         }
2176         
2177         if (numlinks > 0) {
2178                 ntreeUpdateTree(snode->edittree);
2179         }
2180         
2181         BLI_freelistN(nodelist);
2182         MEM_freeN(nodelist);
2183 }
2184
2185 /* can be called from menus too, but they should do own undopush and redraws */
2186 bNode *node_add_node(SpaceNode *snode, Main *bmain, Scene *scene, bNodeTemplate *ntemp, float locx, float locy)
2187 {
2188         bNode *node= NULL, *gnode;
2189         
2190         node_deselectall(snode);
2191         
2192         node = nodeAddNode(snode->edittree, ntemp);
2193         
2194         /* generics */
2195         if(node) {
2196                 node->locx= locx;
2197                 node->locy= locy + 60.0f;               // arbitrary.. so its visible, (0,0) is top of node
2198                 node->flag |= SELECT;
2199                 
2200                 gnode= node_tree_get_editgroup(snode->nodetree);
2201                 if(gnode) {
2202                         node->locx -= gnode->locx;
2203                         node->locy -= gnode->locy;
2204                 }
2205
2206                 ntreeUpdateTree(snode->edittree);
2207                 ED_node_set_active(bmain, snode->edittree, node);
2208                 
2209                 if(snode->nodetree->type==NTREE_COMPOSIT) {
2210                         if(ELEM4(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE, CMP_NODE_DEFOCUS, CMP_NODE_OUTPUT_FILE))
2211                                 node->id = &scene->id;
2212                         
2213                         ntreeCompositForceHidden(snode->edittree, scene);
2214                 }
2215                         
2216                 if(node->id)
2217                         id_us_plus(node->id);
2218                         
2219                 snode_update(snode, node);
2220         }
2221         
2222         if(snode->nodetree->type==NTREE_TEXTURE) {
2223                 ntreeTexCheckCyclics(snode->edittree);
2224         }
2225         
2226         return node;
2227 }
2228
2229 /* ****************** Duplicate *********************** */
2230
2231 static int node_duplicate_exec(bContext *C, wmOperator *op)
2232 {
2233         SpaceNode *snode= CTX_wm_space_node(C);
2234         bNodeTree *ntree= snode->edittree;
2235         bNode *node, *newnode, *lastnode;
2236         bNodeLink *link, *newlink, *lastlink;
2237         int keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
2238         
2239         ED_preview_kill_jobs(C);
2240         
2241         lastnode = ntree->nodes.last;
2242         for(node= ntree->nodes.first; node; node= node->next) {
2243                 if(node->flag & SELECT) {
2244                         newnode = nodeCopyNode(ntree, node);
2245                         
2246                         if(newnode->id) {
2247                                 /* simple id user adjustment, node internal functions dont touch this
2248                                  * but operators and readfile.c do. */
2249                                 id_us_plus(newnode->id);
2250                                 /* to ensure redraws or rerenders happen */
2251                                 ED_node_changed_update(snode->id, newnode);
2252                         }
2253                 }
2254                 
2255                 /* make sure we don't copy new nodes again! */
2256                 if (node==lastnode)
2257                         break;
2258         }
2259         
2260         /* copy links between selected nodes
2261          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
2262          */
2263         lastlink = ntree->links.last;
2264         for (link=ntree->links.first; link; link=link->next) {
2265                 /* This creates new links between copied nodes.
2266                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
2267                  */
2268                 if (link->tonode && (link->tonode->flag & NODE_SELECT)
2269                         && (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT)))) {
2270                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
2271                         newlink->flag = link->flag;
2272                         newlink->tonode = link->tonode->new_node;
2273                         newlink->tosock = link->tosock->new_sock;
2274                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
2275                                 newlink->fromnode = link->fromnode->new_node;
2276                                 newlink->fromsock = link->fromsock->new_sock;
2277                         }
2278                         else {
2279                                 /* input node not copied, this keeps the original input linked */
2280                                 newlink->fromnode = link->fromnode;
2281                                 newlink->fromsock = link->fromsock;
2282                         }
2283                         
2284                         BLI_addtail(&ntree->links, newlink);
2285                 }
2286                 
2287                 /* make sure we don't copy new links again! */
2288                 if (link==lastlink)
2289                         break;
2290         }
2291         
2292         /* deselect old nodes, select the copies instead */
2293         for(node= ntree->nodes.first; node; node= node->next) {
2294                 if(node->flag & SELECT) {
2295                         /* has been set during copy above */
2296                         newnode = node->new_node;
2297                         
2298                         node->flag &= ~(NODE_SELECT|NODE_ACTIVE);
2299                         newnode->flag |= NODE_SELECT;
2300                 }
2301                 
2302                 /* make sure we don't copy new nodes again! */
2303                 if (node==lastnode)
2304                         break;
2305         }
2306         
2307         ntreeUpdateTree(snode->edittree);
2308         
2309         snode_notify(C, snode);
2310         snode_dag_update(C, snode);
2311
2312         return OPERATOR_FINISHED;
2313 }
2314
2315 void NODE_OT_duplicate(wmOperatorType *ot)
2316 {
2317         /* identifiers */
2318         ot->name= "Duplicate Nodes";
2319         ot->description = "Duplicate selected nodes";
2320         ot->idname= "NODE_OT_duplicate";
2321         
2322         /* api callbacks */
2323         ot->exec= node_duplicate_exec;
2324         ot->poll= ED_operator_node_active;
2325         
2326         /* flags */
2327         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2328         
2329         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
2330 }
2331
2332 /* *************************** add link op ******************** */
2333
2334 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
2335 {
2336         bNodeLink *tlink;
2337         bNodeSocket *sock;
2338         
2339         if(tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
2340                 
2341                 for(tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
2342                         if(link!=tlink && tlink->tosock==link->tosock)
2343                                 break;
2344                 }
2345                 if(tlink) {
2346                         /* try to move the existing link to the next available socket */
2347                         if (tlink->tonode) {
2348                                 /* is there a free input socket with the target type? */
2349                                 for(sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
2350                                         if(sock->type==tlink->tosock->type)
2351                                                 if(nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
2352                                                         break;
2353                                 }
2354                                 if(sock) {
2355                                         tlink->tosock= sock;
2356                                         sock->flag &= ~SOCK_HIDDEN;
2357                                 }
2358                                 else {
2359                                         nodeRemLink(snode->edittree, tlink);
2360                                 }
2361                         }
2362                         else
2363                                 nodeRemLink(snode->edittree, tlink);
2364                 }
2365         }
2366 }
2367
2368 /* loop that adds a nodelink, called by function below  */
2369 /* in_out = starting socket */
2370 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
2371 {
2372         SpaceNode *snode= CTX_wm_space_node(C);
2373         ARegion *ar= CTX_wm_region(C);
2374         bNodeLinkDrag *nldrag= op->customdata;
2375         bNode *tnode, *node;
2376         bNodeSocket *tsock= NULL, *sock;
2377         bNodeLink *link;
2378         int in_out;
2379
2380         in_out= nldrag->in_out;
2381         node= nldrag->node;
2382         sock= nldrag->sock;
2383         link= nldrag->link;
2384         
2385         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2386                                                          &snode->mx, &snode->my);
2387
2388         switch (event->type) {
2389                 case MOUSEMOVE:
2390                         
2391                         if(in_out==SOCK_OUT) {
2392                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_IN)) {
2393                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2394                                                 if( link->tosock!= tsock && (!tnode || (tnode!=node && link->tonode!=tnode)) ) {
2395                                                         link->tonode= tnode;
2396                                                         link->tosock= tsock;
2397                                                         if (link->prev==NULL && link->next==NULL) {
2398                                                                 BLI_addtail(&snode->edittree->links, link);
2399                                                         }
2400                                                         
2401                                                         snode->edittree->update |= NTREE_UPDATE_LINKS;
2402                                                         ntreeUpdateTree(snode->edittree);
2403                                                 }
2404                                         }
2405                                 }
2406                                 else {
2407                                         if (link->tonode || link->tosock) {
2408                                                 BLI_remlink(&snode->edittree->links, link);
2409                                                 link->prev = link->next = NULL;
2410                                                 link->tonode= NULL;
2411                                                 link->tosock= NULL;
2412                                                 
2413                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2414                                                 ntreeUpdateTree(snode->edittree);
2415                                         }
2416                                 }
2417                         }
2418                         else {
2419                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
2420                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2421                                                 if(nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
2422                                                         if( link->fromsock!= tsock && (!tnode || (tnode!=node && link->fromnode!=tnode)) ) {
2423                                                                 link->fromnode= tnode;
2424                                                                 link->fromsock= tsock;
2425                                                                 if (link->prev==NULL && link->next==NULL) {
2426                                                                         BLI_addtail(&snode->edittree->links, link);
2427                                                                 }
2428                                                                 
2429                                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2430                                                                 ntreeUpdateTree(snode->edittree);
2431                                                         }
2432                                                 }
2433                                         }
2434                                 }
2435                                 else {
2436                                         if (link->tonode || link->tosock) {
2437                                                 BLI_remlink(&snode->edittree->links, link);
2438                                                 link->prev = link->next = NULL;
2439                                                 link->fromnode= NULL;
2440                                                 link->fromsock= NULL;
2441                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2442                                                 ntreeUpdateTree(snode->edittree);
2443                                         }
2444                                 }
2445                         }
2446                         /* hilight target sockets only */
2447                         node_socket_hilights(snode, in_out==SOCK_OUT?SOCK_IN:SOCK_OUT);
2448                         ED_region_tag_redraw(ar);
2449                         break;
2450                         
2451                 case LEFTMOUSE:
2452                 case RIGHTMOUSE:
2453                 case MIDDLEMOUSE:
2454                         if(link->tosock && link->fromsock) {
2455                                 /* send changed events for original tonode and new */
2456                                 snode_update(snode, link->tonode);
2457                                 
2458                                 /* we might need to remove a link */
2459                                 if(in_out==SOCK_OUT)
2460                                         node_remove_extra_links(snode, link->tosock, link);
2461                                 
2462                                 /* when linking to group outputs, update the socket type */
2463                                 /* XXX this should all be part of a generic update system */
2464                                 if (!link->tonode) {
2465                                         link->tosock->type = link->fromsock->type;
2466                                 }
2467                         }
2468                         else if (outside_group_rect(snode) && (link->tonode || link->fromnode)) {
2469                                 /* automatically add new group socket */
2470                                 if (link->tonode && link->tosock) {
2471                                         link->fromsock = node_group_expose_socket(snode->edittree, link->tosock, SOCK_IN);
2472                                         link->fromnode = NULL;
2473                                         if (link->prev==NULL && link->next==NULL) {
2474                                                 BLI_addtail(&snode->edittree->links, link);
2475                                         }
2476                                         snode->edittree->update |= NTREE_UPDATE_GROUP_IN | NTREE_UPDATE_LINKS;
2477                                 }
2478                                 else if (link->fromnode && link->fromsock) {
2479                                         link->tosock = node_group_expose_socket(snode->edittree, link->fromsock, SOCK_OUT);
2480                                         link->tonode = NULL;
2481                                         if (link->prev==NULL && link->next==NULL) {
2482                                                 BLI_addtail(&snode->edittree->links, link);
2483                                         }
2484                                         snode->edittree->update |= NTREE_UPDATE_GROUP_OUT | NTREE_UPDATE_LINKS;
2485                                 }
2486                         }
2487                         else
2488                                 nodeRemLink(snode->edittree, link);
2489                         
2490                         ntreeUpdateTree(snode->edittree);
2491                         snode_notify(C, snode);
2492                         snode_dag_update(C, snode);
2493                         
2494                         BLI_remlink(&snode->linkdrag, nldrag);
2495                         MEM_freeN(nldrag);
2496                         
2497                         return OPERATOR_FINISHED;
2498         }
2499         
2500         return OPERATOR_RUNNING_MODAL;
2501 }
2502
2503 /* return 1 when socket clicked */
2504 static int node_link_init(SpaceNode *snode, bNodeLinkDrag *nldrag)
2505 {
2506         bNodeLink *link;
2507
2508         /* output indicated? */
2509         if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
2510                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2511                         return SOCK_OUT;
2512                 else {
2513                         /* find if we break a link */
2514                         for(link= snode->edittree->links.first; link; link= link->next) {
2515                                 if(link->fromsock==nldrag->sock)
2516                                         break;
2517                         }
2518                         if(link) {
2519                                 nldrag->node= link->tonode;
2520                                 nldrag->sock= link->tosock;
2521                                 nodeRemLink(snode->edittree, link);
2522                                 return SOCK_IN;
2523                         }
2524                 }
2525         }
2526         /* or an input? */
2527         else if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
2528                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2529                         return SOCK_IN;
2530                 else {
2531                         /* find if we break a link */
2532                         for(link= snode->edittree->links.first; link; link= link->next) {
2533                                 if(link->tosock==nldrag->sock)
2534                                         break;
2535                         }
2536                         if(link) {
2537                                 /* send changed event to original tonode */
2538                                 if(link->tonode) 
2539                                         snode_update(snode, link->tonode);
2540                                 
2541                                 nldrag->node= link->fromnode;
2542                                 nldrag->sock= link->fromsock;
2543                                 nodeRemLink(snode->edittree, link);
2544                                 return SOCK_OUT;
2545                         }
2546                 }
2547         }
2548         
2549         return 0;
2550 }
2551
2552 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
2553 {
2554         SpaceNode *snode= CTX_wm_space_node(C);
2555         ARegion *ar= CTX_wm_region(C);
2556         bNodeLinkDrag *nldrag= MEM_callocN(sizeof(bNodeLinkDrag), "drag link op customdata");
2557         
2558         
2559         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2560                                                          &snode->mx, &snode->my);
2561
2562         ED_preview_kill_jobs(C);
2563
2564         nldrag->in_out= node_link_init(snode, nldrag);
2565         
2566         if(nldrag->in_out) {
2567                 op->customdata= nldrag;
2568                 
2569                 /* we make a temporal link */
2570                 if(nldrag->in_out==SOCK_OUT) {
2571                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2572                         nldrag->link->fromnode= nldrag->node;
2573                         nldrag->link->fromsock= nldrag->sock;
2574                         nldrag->link->tonode= NULL;
2575                         nldrag->link->tosock= NULL;
2576                 }
2577                 else {
2578                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2579                         nldrag->link->fromnode= NULL;
2580                         nldrag->link->fromsock= NULL;
2581                         nldrag->link->tonode= nldrag->node;
2582                         nldrag->link->tosock= nldrag->sock;
2583                 }
2584                 BLI_addtail(&snode->linkdrag, nldrag);
2585                 
2586                 /* add modal handler */
2587                 WM_event_add_modal_handler(C, op);
2588                 
2589                 return OPERATOR_RUNNING_MODAL;
2590         }
2591         else {
2592                 MEM_freeN(nldrag);
2593                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2594         }
2595 }
2596
2597 static int node_link_cancel(bContext *C, wmOperator *op)
2598 {
2599         SpaceNode *snode= CTX_wm_space_node(C);
2600         bNodeLinkDrag *nldrag= op->customdata;
2601
2602         nodeRemLink(snode->edittree, nldrag->link);
2603         BLI_remlink(&snode->linkdrag, nldrag);
2604         MEM_freeN(nldrag);
2605
2606         return OPERATOR_CANCELLED;
2607 }
2608
2609 void NODE_OT_link(wmOperatorType *ot)
2610 {
2611         /* identifiers */
2612         ot->name= "Link Nodes";
2613         ot->idname= "NODE_OT_link";
2614         
2615         /* api callbacks */
2616         ot->invoke= node_link_invoke;
2617         ot->modal= node_link_modal;
2618 //      ot->exec= node_link_exec;
2619         ot->poll= ED_operator_node_active;
2620         ot->cancel= node_link_cancel;
2621         
2622         /* flags */
2623         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2624 }
2625
2626 /* ********************** Make Link operator ***************** */
2627
2628 /* makes a link between selected output and input sockets */
2629 static int node_make_link_exec(bContext *C, wmOperator *op)
2630 {
2631         SpaceNode *snode= CTX_wm_space_node(C);
2632         int replace = RNA_boolean_get(op->ptr, "replace");
2633
2634         ED_preview_kill_jobs(C);
2635
2636         snode_autoconnect(snode, 1, replace);
2637
2638         ntreeUpdateTree(snode->edittree);
2639         snode_notify(C, snode);
2640         snode_dag_update(C, snode);
2641         
2642         return OPERATOR_FINISHED;
2643 }
2644
2645 void NODE_OT_link_make(wmOperatorType *ot)
2646 {
2647         /* identifiers */
2648         ot->name= "Make Links";
2649         ot->description= "Makes a link between selected output in input sockets";
2650         ot->idname= "NODE_OT_link_make";
2651         
2652         /* callbacks */
2653         ot->exec= node_make_link_exec;
2654         ot->poll= ED_operator_node_active; // XXX we need a special poll which checks that there are selected input/output sockets
2655         
2656         /* flags */
2657         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2658         
2659         RNA_def_boolean(ot->srna, "replace", 0, "Replace", "Replace socket connections with the new links");
2660 }
2661
2662 /* ********************** Cut Link operator ***************** */
2663
2664 #define LINK_RESOL 12
2665 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2666 {
2667         float coord_array[LINK_RESOL+1][2];
2668         int i, b;
2669         
2670         if(node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2671
2672                 for(i=0; i<tot-1; i++)
2673                         for(b=0; b<LINK_RESOL; b++)
2674                                 if(isect_line_line_v2(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2675                                         return 1;
2676         }
2677         return 0;
2678 }
2679
2680 static int cut_links_exec(bContext *C, wmOperator *op)
2681 {
2682         SpaceNode *snode= CTX_wm_space_node(C);
2683         ARegion *ar= CTX_wm_region(C);
2684         float mcoords[256][2];
2685         int i= 0;
2686         
2687         RNA_BEGIN(op->ptr, itemptr, "path") {
2688                 float loc[2];
2689                 
2690                 RNA_float_get_array(&itemptr, "loc", loc);
2691                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2692                                                                  &mcoords[i][0], &mcoords[i][1]);
2693                 i++;
2694                 if(i>= 256) break;
2695         }
2696         RNA_END;
2697         
2698         if(i>1) {
2699                 bNodeLink *link, *next;
2700
2701                 ED_preview_kill_jobs(C);
2702                 
2703                 for(link= snode->edittree->links.first; link; link= next) {
2704                         next= link->next;
2705                         
2706                         if(cut_links_intersect(link, mcoords, i)) {
2707                                 snode_update(snode, link->tonode);
2708                                 nodeRemLink(snode->edittree, link);
2709                         }
2710                 }
2711                 
2712                 ntreeUpdateTree(snode->edittree);
2713                 snode_notify(C, snode);
2714                 snode_dag_update(C, snode);
2715                 
2716                 return OPERATOR_FINISHED;
2717         }
2718         
2719         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2720 }
2721
2722 void NODE_OT_links_cut(wmOperatorType *ot)
2723 {
2724         PropertyRNA *prop;
2725         
2726         ot->name= "Cut links";
2727         ot->idname= "NODE_OT_links_cut";
2728         
2729         ot->invoke= WM_gesture_lines_invoke;
2730         ot->modal= WM_gesture_lines_modal;
2731         ot->exec= cut_links_exec;
2732         ot->cancel= WM_gesture_lines_cancel;
2733         
2734         ot->poll= ED_operator_node_active;
2735         
2736         /* flags */
2737         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2738         
2739         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2740         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2741         /* internal */
2742         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2743 }
2744
2745 /* *********************  automatic node insert on dragging ******************* */
2746
2747 /* assumes sockets in list */
2748 static bNodeSocket *socket_best_match(ListBase *sockets, int type)
2749 {
2750         bNodeSocket *sock;
2751         
2752         /* first, match type */
2753         for(sock= sockets->first; sock; sock= sock->next)
2754                 if(!(sock->flag & SOCK_HIDDEN))
2755                         if(type == sock->type)
2756                                 return sock;
2757         
2758         /* then just use first unhidden socket */
2759         for(sock= sockets->first; sock; sock= sock->next)
2760                 if(!(sock->flag & SOCK_HIDDEN))
2761                         return sock;
2762
2763         /* OK, let's unhide proper one */
2764         for(sock= sockets->first; sock; sock= sock->next) {
2765                 if(type == sock->type) {
2766                         sock->flag &= ~SOCK_HIDDEN;
2767                         return sock;
2768                 }
2769         }
2770         
2771         /* just the first */
2772         sock= sockets->first;
2773         sock->flag &= ~SOCK_HIDDEN;
2774         
2775         return sockets->first;
2776 }
2777
2778 /* prevent duplicate testing code below */
2779 static SpaceNode *ed_node_link_conditions(ScrArea *sa, bNode **select)
2780 {
2781         SpaceNode *snode= sa?sa->spacedata.first:NULL;
2782         bNode *node;
2783         bNodeLink *link;
2784         
2785         /* no unlucky accidents */
2786         if(sa==NULL || sa->spacetype!=SPACE_NODE) return NULL;
2787         
2788         *select= NULL;
2789         
2790         for(node= snode->edittree->nodes.first; node; node= node->next) {
2791                 if(node->flag & SELECT) {
2792                         if(*select)
2793                                 break;
2794                         else
2795                                 *select= node;
2796                 }
2797         }
2798         /* only one selected */
2799         if(node || *select==NULL) return NULL;
2800         
2801         /* correct node */
2802         if((*select)->inputs.first==NULL || (*select)->outputs.first==NULL) return NULL;
2803         
2804         /* test node for links */
2805         for(link= snode->edittree->links.first; link; link=link->next) {
2806                 if(link->tonode == *select || link->fromnode == *select)
2807                         return NULL;
2808         }
2809         
2810         return snode;
2811 }
2812
2813 /* assumes link with NODE_LINKFLAG_HILITE set */
2814 void ED_node_link_insert(ScrArea *sa)
2815 {
2816         bNode *node, *select;
2817         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2818         bNodeLink *link;
2819         bNodeSocket *sockto;
2820         
2821         if(snode==NULL) return;
2822         
2823         /* get the link */
2824         for(link= snode->edittree->links.first; link; link=link->next)
2825                 if(link->flag & NODE_LINKFLAG_HILITE)
2826                         break;
2827         
2828         if(link) {
2829                 node= link->tonode;
2830                 sockto= link->tosock;
2831                 
2832                 link->tonode= select;
2833                 link->tosock= socket_best_match(&select->inputs, link->fromsock->type);
2834                 link->flag &= ~NODE_LINKFLAG_HILITE;
2835                 
2836                 nodeAddLink(snode->edittree, select, socket_best_match(&select->outputs, sockto->type), node, sockto);
2837                 ntreeUpdateTree(snode->edittree);       /* needed for pointers */
2838                 snode_update(snode, select);
2839                 ED_node_changed_update(snode->id, select);
2840         }
2841 }
2842
2843
2844 /* test == 0, clear all intersect flags */
2845 void ED_node_link_intersect_test(ScrArea *sa, int test)
2846 {
2847         bNode *select;
2848         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2849         bNodeLink *link, *selink=NULL;
2850         float mcoords[6][2];
2851         
2852         if(snode==NULL) return;
2853         
2854         /* clear flags */
2855         for(link= snode->edittree->links.first; link; link=link->next)
2856                 link->flag &= ~NODE_LINKFLAG_HILITE;
2857         
2858         if(test==0) return;
2859         
2860         /* okay, there's 1 node, without links, now intersect */
2861         mcoords[0][0]= select->totr.xmin;
2862         mcoords[0][1]= select->totr.ymin;
2863         mcoords[1][0]= select->totr.xmax;
2864         mcoords[1][1]= select->totr.ymin;
2865         mcoords[2][0]= select->totr.xmax;
2866         mcoords[2][1]= select->totr.ymax;
2867         mcoords[3][0]= select->totr.xmin;
2868         mcoords[3][1]= select->totr.ymax;
2869         mcoords[4][0]= select->totr.xmin;
2870         mcoords[4][1]= select->totr.ymin;
2871         mcoords[5][0]= select->totr.xmax;
2872         mcoords[5][1]= select->totr.ymax;
2873         
2874         /* we only tag a single link for intersect now */
2875         /* idea; use header dist when more? */
2876         for(link= snode->edittree->links.first; link; link=link->next) {
2877                 
2878                 if(cut_links_intersect(link, mcoords, 5)) { /* intersect code wants edges */
2879                         if(selink) 
2880                                 break;
2881                         selink= link;
2882                 }
2883         }
2884                 
2885         if(link==NULL && selink)
2886                 selink->flag |= NODE_LINKFLAG_HILITE;
2887 }
2888
2889
2890 /* ******************************** */
2891 // XXX some code needing updating to operators...
2892
2893
2894 /* goes over all scenes, reads render layers */
2895 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
2896 {
2897         Main *bmain= CTX_data_main(C);
2898         SpaceNode *snode= CTX_wm_space_node(C);
2899         Scene *curscene= CTX_data_scene(C), *scene;
2900         bNode *node;
2901
2902         ED_preview_kill_jobs(C);
2903
2904         /* first tag scenes unread */
2905         for(scene= bmain->scene.first; scene; scene= scene->id.next) 
2906                 scene->id.flag |= LIB_DOIT;
2907
2908         for(node= snode->edittree->nodes.first; node; node= node->next) {
2909                 if(node->type==CMP_NODE_R_LAYERS) {
2910                         ID *id= node->id;
2911                         if(id->flag & LIB_DOIT) {
2912                                 RE_ReadRenderResult(curscene, (Scene *)id);
2913                                 ntreeCompositTagRender((Scene *)id);
2914                                 id->flag &= ~LIB_DOIT;
2915                         }
2916                 }
2917         }
2918         
2919         snode_notify(C, snode);
2920         snode_dag_update(C, snode);
2921
2922         return OPERATOR_FINISHED;
2923 }
2924
2925 void NODE_OT_read_renderlayers(wmOperatorType *ot)
2926 {
2927         
2928         ot->name= "Read Render Layers";
2929         ot->idname= "NODE_OT_read_renderlayers";
2930         
2931         ot->exec= node_read_renderlayers_exec;
2932         
2933         ot->poll= composite_node_active;
2934         
2935         /* flags */
2936         ot->flag= 0;
2937 }
2938
2939 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
2940 {
2941         Main *bmain= CTX_data_main(C);
2942         SpaceNode *snode= CTX_wm_space_node(C);
2943         Scene *curscene= CTX_data_scene(C);
2944         Render *re= RE_NewRender(curscene->id.name);
2945
2946         WM_cursor_wait(1);
2947         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
2948         WM_cursor_wait(0);
2949
2950         /* note we are careful to send the right notifier, as otherwise the
2951            compositor would reexecute and overwrite the full sample result */
2952         WM_event_add_notifier(C, NC_SCENE|ND_COMPO_RESULT, NULL);
2953
2954         return OPERATOR_FINISHED;
2955 }
2956
2957
2958 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
2959 {
2960         
2961         ot->name= "Read Full Sample Layers";
2962         ot->idname= "NODE_OT_read_fullsamplelayers";
2963         
2964         ot->exec= node_read_fullsamplelayers_exec;
2965         
2966         ot->poll= composite_node_active;
2967         
2968         /* flags */
2969         ot->flag= 0;
2970 }
2971
2972 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
2973 {
2974         Scene *sce= CTX_data_scene(C);
2975         bNode *node;
2976         
2977         for(node= sce->nodetree->nodes.first; node; node= node->next) {
2978                 if(node->id==(ID *)sce && node->need_exec) {
2979                         break;
2980                 }
2981         }
2982         if(node) {
2983                 SceneRenderLayer *srl= BLI_findlink(&sce->r.layers, node->custom1);
2984                 
2985                 if(srl) {
2986                         PointerRNA op_ptr;
2987                         
2988                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
2989                         RNA_string_set(&op_ptr, "layer", srl->name);
2990                         RNA_string_set(&op_ptr, "scene", sce->id.name+2);
2991                         
2992                         /* to keep keypositions */
2993                         sce->r.scemode |= R_NO_FRAME_UPDATE;
2994                         
2995                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
2996
2997                         WM_operator_properties_free(&op_ptr);
2998                         
2999                         return OPERATOR_FINISHED;
3000                 }
3001                    
3002         }
3003         return OPERATOR_CANCELLED;
3004 }
3005
3006 void NODE_OT_render_changed(wmOperatorType *ot)
3007 {
3008         
3009         ot->name= "Render Changed Layer";
3010         ot->idname= "NODE_OT_render_changed";
3011         
3012         ot->exec= node_render_changed_exec;
3013         
3014         ot->poll= composite_node_active;
3015         
3016         /* flags */
3017         ot->flag= 0;
3018 }
3019
3020
3021 /* ****************** Make Group operator ******************* */
3022
3023 static int node_group_make_exec(bContext *C, wmOperator *op)
3024 {
3025         SpaceNode *snode = CTX_wm_space_node(C);
3026         bNode *gnode;
3027         
3028         if(snode->edittree!=snode->nodetree) {
3029                 BKE_report(op->reports, RPT_WARNING, "Can not add a new Group in a Group");
3030                 return OPERATOR_CANCELLED;
3031         }
3032         
3033         /* for time being... is too complex to handle */
3034         if(snode->treetype==NTREE_COMPOSIT) {
3035                 for(gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
3036                         if(gnode->flag & SELECT)
3037                                 if(gnode->type==CMP_NODE_R_LAYERS)
3038                                         break;
3039                 }
3040                 
3041                 if(gnode) {
3042                         BKE_report(op->reports, RPT_WARNING, "Can not add RenderLayer in a Group");
3043                         return OPERATOR_CANCELLED;
3044                 }
3045         }
3046
3047         ED_preview_kill_jobs(C);
3048         
3049         gnode= node_group_make_from_selected(snode->nodetree);
3050         if(gnode==NULL) {
3051                 BKE_report(op->reports, RPT_WARNING, "Can not make Group");
3052                 return OPERATOR_CANCELLED;
3053         }
3054         else {
3055                 nodeSetActive(snode->nodetree, gnode);
3056                 ntreeUpdateTree(snode->nodetree);
3057         }
3058         
3059         snode_notify(C, snode);
3060         snode_dag_update(C, snode);
3061         
3062         return OPERATOR_FINISHED;
3063 }
3064
3065 void NODE_OT_group_make(wmOperatorType *ot)
3066 {
3067         /* identifiers */
3068         ot->name = "Group";
3069         ot->description = "Make group from selected nodes";
3070         ot->idname = "NODE_OT_group_make";
3071         
3072         /* api callbacks */
3073         ot->exec = node_group_make_exec;
3074         ot->poll = ED_operator_node_active;
3075         
3076         /* flags */
3077         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
3078 }
3079
3080 /* ****************** Hide operator *********************** */
3081
3082 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
3083 {
3084         int tot_eq= 0, tot_neq= 0;
3085         bNode *node;
3086
3087         for(node= snode->edittree->nodes.first; node; node= node->next) {
3088                 if(node->flag & SELECT) {
3089
3090                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
3091                                 continue;
3092
3093                         if(node->flag & toggle_flag)
3094                                 tot_eq++;
3095                         else
3096                                 tot_neq++;
3097                 }
3098         }
3099         for(node= snode->edittree->nodes.first; node; node= node->next) {
3100                 if(node->flag & SELECT) {
3101
3102                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
3103                                 continue;
3104
3105                         if( (tot_eq && tot_neq) || tot_eq==0)
3106                                 node->flag |= toggle_flag;
3107                         else
3108                                 node->flag &= ~toggle_flag;
3109                 }
3110         }
3111 }
3112
3113 static int node_hide_exec(bContext *C, wmOperator *UNUSED(op))
3114 {
3115         SpaceNode *snode= CTX_wm_space_node(C);
3116         
3117         /* sanity checking (poll callback checks this already) */
3118         if((snode == NULL) || (snode->edittree == NULL))
3119                 return OPERATOR_CANCELLED;
3120         
3121         node_flag_toggle_exec(snode, NODE_HIDDEN);
3122         
3123         snode_notify(C, snode);
3124         
3125         return OPERATOR_FINISHED;
3126 }
3127
3128 void NODE_OT_hide_toggle(wmOperatorType *ot)
3129 {
3130         /* identifiers */
3131         ot->name= "Hide";
3132         ot->description= "Toggle hiding of selected nodes";
3133         ot->idname= "NODE_OT_hide_toggle";
3134         
3135         /* callbacks */
3136         ot->exec= node_hide_exec;
3137         ot->poll= ED_operator_node_active;
3138
3139         /* flags */
3140         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3141 }
3142
3143 static int node_preview_exec(bContext *C, wmOperator *UNUSED(op))
3144 {
3145         SpaceNode *snode= CTX_wm_space_node(C);
3146
3147         /* sanity checking (poll callback checks this already) */
3148         if((snode == NULL) || (snode->edittree == NULL))
3149                 return OPERATOR_CANCELLED;
3150
3151         ED_preview_kill_jobs(C);
3152
3153         node_flag_toggle_exec(snode, NODE_PREVIEW);
3154
3155         snode_notify(C, snode);
3156
3157         return OPERATOR_FINISHED;
3158 }
3159
3160 void NODE_OT_preview_toggle(wmOperatorType *ot)
3161 {
3162         /* identifiers */
3163         ot->name= "Toggle Node Preview";
3164         ot->description= "Toggle preview display for selected nodes";
3165         ot->idname= "NODE_OT_preview_toggle";
3166
3167         /* callbacks */
3168         ot->exec= node_preview_exec;
3169         ot->poll= ED_operator_node_active;
3170
3171         /* flags */
3172         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3173 }
3174
3175 static int node_socket_toggle_exec(bContext *C, wmOperator *UNUSED(op))
3176 {
3177         SpaceNode *snode= CTX_wm_space_node(C);