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