Updating render layer and image output sockets was not working due to changes in...
[blender-staging.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         
611         /* if one is an ancestor of the other */
612         /* XXX there might be a better sorting algorithm for stable topological sort, this is O(n^2) worst case */
613         for (parent = a->parent; parent; parent=parent->parent) {
614                 if (parent==b)
615                         return 1;
616         }
617         for (parent = b->parent; parent; parent=parent->parent) {
618                 if (parent==a)
619                         return 0;
620         }
621
622         /* if one of the nodes is in the background and the other not */
623         if ((a->flag & NODE_BACKGROUND) && !(b->typeinfo->flag & NODE_BACKGROUND))
624                 return 0;
625         else if (!(a->flag & NODE_BACKGROUND) && (b->typeinfo->flag & NODE_BACKGROUND))
626                 return 1;
627         
628         /* if one has a higher selection state (active > selected > nothing) */
629         if (!(b->flag & NODE_ACTIVE) && (a->flag & NODE_ACTIVE))
630                 return 1;
631         else if (!(b->flag & NODE_SELECT) && ((a->flag & NODE_ACTIVE) || (a->flag & NODE_SELECT)))
632                 return 1;
633         
634         return 0;
635 }
636 /* Sorts nodes by selection: unselected nodes first, then selected,
637  * then the active node at the very end. Relative order is kept intact!
638  */
639 void node_sort(bNodeTree *ntree)
640 {
641         /* merge sort is the algorithm of choice here */
642         bNode *first_a, *first_b, *node_a, *node_b, *tmp;
643         int totnodes= BLI_countlist(&ntree->nodes);
644         int k, a, b;
645         
646         k = 1;
647         while (k < totnodes) {
648                 first_a = first_b = ntree->nodes.first;
649                 
650                 do {
651                         /* setup first_b pointer */
652                         for (b=0; b < k && first_b; ++b) {
653                                 first_b = first_b->next;
654                         }
655                         /* all batches merged? */
656                         if (first_b==NULL)
657                                 break;
658                         
659                         /* merge batches */
660                         node_a = first_a;
661                         node_b = first_b;
662                         a = b = 0;
663                         while (a < k && b < k && node_b) {
664                                 if (compare_nodes(node_a, node_b)==0) {
665                                         node_a = node_a->next;
666                                         ++a;
667                                 }
668                                 else {
669                                         tmp = node_b;
670                                         node_b = node_b->next;
671                                         ++b;
672                                         BLI_remlink(&ntree->nodes, tmp);
673                                         BLI_insertlinkbefore(&ntree->nodes, node_a, tmp);
674                                 }
675                         }
676
677                         /* setup first pointers for next batch */
678                         first_b = node_b;
679                         for (; b < k; ++b) {
680                                 /* all nodes sorted? */
681                                 if (first_b==NULL)
682                                         break;
683                                 first_b = first_b->next;
684                         }
685                         first_a = first_b;
686                 } while (first_b);
687                 
688                 k = k << 1;
689         }
690 }
691
692 static int inside_rctf(rctf *bounds, rctf *rect)
693 {
694         return (bounds->xmin <= rect->xmin && bounds->xmax >= rect->xmax
695                         && bounds->ymin <= rect->ymin && bounds->ymax >= rect->ymax);
696 }
697
698 static void node_frame_attach_nodes(bNodeTree *UNUSED(ntree), bNode *frame)
699 {
700         bNode *node;
701         
702         /* only check nodes on top of the frame for attaching */
703         for (node=frame->next; node; node=node->next) {
704                 if (node->parent==frame) {
705                         /* detach nodes that went outside the frame */
706                         if (!inside_rctf(&frame->totr, &node->totr))
707                                 nodeDetachNode(node);
708                 }
709                 else if (node->flag & NODE_SELECT && node->parent==NULL) {
710                         /* attach selected, still unparented nodes */
711                         if (inside_rctf(&frame->totr, &node->totr))
712                                 nodeAttachNode(node, frame);
713                 }
714         }
715 }
716
717 void ED_node_update_hierarchy(bContext *UNUSED(C), bNodeTree *ntree)
718 {
719         bNode *node;
720         
721         /* XXX This does not work due to layout functions relying on node->block,
722          * which only exists during actual drawing. Can we rely on valid totr rects?
723          */
724         /* make sure nodes have correct bounding boxes after transform */
725 //      node_update_nodetree(C, ntree, 0.0f, 0.0f);
726         
727         /* all selected nodes are re-parented */
728         for (node=ntree->nodes.last; node; node=node->prev) {
729                 if (node->flag & NODE_SELECT && node->parent)
730                         nodeDetachNode(node);
731         }
732         
733         /* update higher Z-level nodes first */
734         for (node=ntree->nodes.last; node; node=node->prev) {
735                 /* XXX callback? */
736                 if (node->type==NODE_FRAME)
737                         node_frame_attach_nodes(ntree, node);
738         }
739 }
740
741 /* ***************** generic operator functions for nodes ***************** */
742
743 static int edit_node_poll(bContext *C)
744 {
745         return ED_operator_node_active(C);
746 }
747
748 static void edit_node_properties(wmOperatorType *ot)
749 {
750         /* XXX could node be a context pointer? */
751         RNA_def_string(ot->srna, "node", "", 32, "Node", "");
752         RNA_def_int(ot->srna, "socket", 0, 0, MAX_SOCKET, "Socket", "", 0, MAX_SOCKET);
753         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Side", "");
754 }
755
756 static int edit_node_invoke_properties(bContext *C, wmOperator *op)
757 {
758         if (!RNA_property_is_set(op->ptr, "node")) {
759                 bNode *node= CTX_data_pointer_get_type(C, "node", &RNA_Node).data;
760                 if (!node)
761                         return 0;
762                 else
763                         RNA_string_set(op->ptr, "node", node->name);
764         }
765         
766         if (!RNA_property_is_set(op->ptr, "in_out"))
767                 RNA_enum_set(op->ptr, "in_out", SOCK_IN);
768         
769         if (!RNA_property_is_set(op->ptr, "socket"))
770                 RNA_int_set(op->ptr, "socket", 0);
771         
772         return 1;
773 }
774
775 static void edit_node_properties_get(wmOperator *op, bNodeTree *ntree, bNode **rnode, bNodeSocket **rsock, int *rin_out)
776 {
777         bNode *node;
778         bNodeSocket *sock;
779         char nodename[32];
780         int sockindex;
781         int in_out;
782         
783         RNA_string_get(op->ptr, "node", nodename);
784         node = nodeFindNodebyName(ntree, nodename);
785         
786         in_out = RNA_enum_get(op->ptr, "in_out");
787         
788         sockindex = RNA_int_get(op->ptr, "socket");
789         switch (in_out) {
790         case SOCK_IN:   sock = BLI_findlink(&node->inputs, sockindex);  break;
791         case SOCK_OUT:  sock = BLI_findlink(&node->outputs, sockindex); break;
792         }
793         
794         if (rnode)
795                 *rnode = node;
796         if (rsock)
797                 *rsock = sock;
798         if (rin_out)
799                 *rin_out = in_out;
800 }
801
802 /* ***************** Edit Group operator ************* */
803
804 void snode_make_group_editable(SpaceNode *snode, bNode *gnode)
805 {
806         bNode *node;
807         
808         /* make sure nothing has group editing on */
809         for(node=snode->nodetree->nodes.first; node; node=node->next)
810                 nodeGroupEditClear(node);
811         
812         if(gnode==NULL) {
813                 /* with NULL argument we do a toggle */
814                 if(snode->edittree==snode->nodetree)
815                         gnode= nodeGetActive(snode->nodetree);
816         }
817         
818         if (gnode) {
819                 snode->edittree = nodeGroupEditSet(gnode, 1);
820                 
821                 /* deselect all other nodes, so we can also do grabbing of entire subtree */
822                 for(node= snode->nodetree->nodes.first; node; node= node->next)
823                         node->flag &= ~SELECT;
824                 gnode->flag |= SELECT;
825         }
826         else 
827                 snode->edittree= snode->nodetree;
828 }
829
830 static int node_group_edit_exec(bContext *C, wmOperator *UNUSED(op))
831 {
832         SpaceNode *snode = CTX_wm_space_node(C);
833
834         ED_preview_kill_jobs(C);
835
836         if (snode->nodetree==snode->edittree) {
837                 bNode *gnode= nodeGetActive(snode->nodetree);
838                 snode_make_group_editable(snode, gnode);
839         }
840         else
841                 snode_make_group_editable(snode, NULL);
842
843         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL);
844
845         return OPERATOR_FINISHED;
846 }
847
848 static int node_group_edit_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(event))
849 {
850         SpaceNode *snode = CTX_wm_space_node(C);
851         bNode *gnode;
852
853         gnode= nodeGetActive(snode->edittree);
854         /* XXX callback? */
855         if(gnode && gnode->id && GS(gnode->id->name)==ID_NT && gnode->id->lib) {
856                 uiPupMenuOkee(C, op->type->idname, "Make group local?");
857                 return OPERATOR_CANCELLED;
858         }
859
860         return node_group_edit_exec(C, op);
861 }
862
863 void NODE_OT_group_edit(wmOperatorType *ot)
864 {
865         /* identifiers */
866         ot->name = "Edit Group";
867         ot->description = "Edit node group";
868         ot->idname = "NODE_OT_group_edit";
869         
870         /* api callbacks */
871         ot->invoke = node_group_edit_invoke;
872         ot->exec = node_group_edit_exec;
873         ot->poll = ED_operator_node_active;
874         
875         /* flags */
876         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
877 }
878
879 /* ***************** Add Group Socket operator ************* */
880
881 static int node_group_socket_add_exec(bContext *C, wmOperator *op)
882 {
883         SpaceNode *snode = CTX_wm_space_node(C);
884         int in_out= -1;
885         char name[32]= "";
886         int type= SOCK_FLOAT;
887         bNodeTree *ngroup= snode->edittree;
888         bNodeSocket *sock;
889         
890         ED_preview_kill_jobs(C);
891         
892         if (RNA_property_is_set(op->ptr, "name"))
893                 RNA_string_get(op->ptr, "name", name);
894         
895         if (RNA_property_is_set(op->ptr, "type"))
896                 type = RNA_enum_get(op->ptr, "type");
897         
898         if (RNA_property_is_set(op->ptr, "in_out"))
899                 in_out = RNA_enum_get(op->ptr, "in_out");
900         else
901                 return OPERATOR_CANCELLED;
902         
903         /* using placeholder subtype first */
904         sock = node_group_add_socket(ngroup, name, type, in_out);
905         
906         ntreeUpdateTree(ngroup);
907         
908         snode_notify(C, snode);
909         
910         return OPERATOR_FINISHED;
911 }
912
913 void NODE_OT_group_socket_add(wmOperatorType *ot)
914 {
915         /* identifiers */
916         ot->name = "Add Group Socket";
917         ot->description = "Add node group socket";
918         ot->idname = "NODE_OT_group_socket_add";
919         
920         /* api callbacks */
921         ot->exec = node_group_socket_add_exec;
922         ot->poll = ED_operator_node_active;
923         
924         /* flags */
925         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
926         
927         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
928         RNA_def_string(ot->srna, "name", "", 32, "Name", "Group socket name");
929         RNA_def_enum(ot->srna, "type", node_socket_type_items, SOCK_FLOAT, "Type", "Type of the group socket");
930 }
931
932 /* ***************** Remove Group Socket operator ************* */
933
934 static int node_group_socket_remove_exec(bContext *C, wmOperator *op)
935 {
936         SpaceNode *snode = CTX_wm_space_node(C);
937         int index= -1;
938         int in_out= -1;
939         bNodeTree *ngroup= snode->edittree;
940         bNodeSocket *sock;
941         
942         ED_preview_kill_jobs(C);
943         
944         if (RNA_property_is_set(op->ptr, "index"))
945                 index = RNA_int_get(op->ptr, "index");
946         else
947                 return OPERATOR_CANCELLED;
948         
949         if (RNA_property_is_set(op->ptr, "in_out"))
950                 in_out = RNA_enum_get(op->ptr, "in_out");
951         else
952                 return OPERATOR_CANCELLED;
953         
954         sock = (bNodeSocket*)BLI_findlink(in_out==SOCK_IN ? &ngroup->inputs : &ngroup->outputs, index);
955         if (sock) {
956                 node_group_remove_socket(ngroup, sock, in_out);
957                 ntreeUpdateTree(ngroup);
958                 
959                 snode_notify(C, snode);
960         }
961         
962         return OPERATOR_FINISHED;
963 }
964
965 void NODE_OT_group_socket_remove(wmOperatorType *ot)
966 {
967         /* identifiers */
968         ot->name = "Remove Group Socket";
969         ot->description = "Removed node group socket";
970         ot->idname = "NODE_OT_group_socket_remove";
971         
972         /* api callbacks */
973         ot->exec = node_group_socket_remove_exec;
974         ot->poll = ED_operator_node_active;
975         
976         /* flags */
977         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
978         
979         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
980         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
981 }
982
983 /* ***************** Move Group Socket Up operator ************* */
984
985 static int node_group_socket_move_up_exec(bContext *C, wmOperator *op)
986 {
987         SpaceNode *snode = CTX_wm_space_node(C);
988         int index= -1;
989         int in_out= -1;
990         bNodeTree *ngroup= snode->edittree;
991         bNodeSocket *sock, *prev;
992         
993         ED_preview_kill_jobs(C);
994         
995         if (RNA_property_is_set(op->ptr, "index"))
996                 index = RNA_int_get(op->ptr, "index");
997         else
998                 return OPERATOR_CANCELLED;
999         
1000         if (RNA_property_is_set(op->ptr, "in_out"))
1001                 in_out = RNA_enum_get(op->ptr, "in_out");
1002         else
1003                 return OPERATOR_CANCELLED;
1004         
1005         /* swap */
1006         if (in_out==SOCK_IN) {
1007                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
1008                 prev = sock->prev;
1009                 /* can't move up the first socket */
1010                 if (!prev)
1011                         return OPERATOR_CANCELLED;
1012                 BLI_remlink(&ngroup->inputs, sock);
1013                 BLI_insertlinkbefore(&ngroup->inputs, prev, sock);
1014                 
1015                 ngroup->update |= NTREE_UPDATE_GROUP_IN;
1016         }
1017         else if (in_out==SOCK_OUT) {
1018                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
1019                 prev = sock->prev;
1020                 /* can't move up the first socket */
1021                 if (!prev)
1022                         return OPERATOR_CANCELLED;
1023                 BLI_remlink(&ngroup->outputs, sock);
1024                 BLI_insertlinkbefore(&ngroup->outputs, prev, sock);
1025                 
1026                 ngroup->update |= NTREE_UPDATE_GROUP_OUT;
1027         }
1028         ntreeUpdateTree(ngroup);
1029         
1030         snode_notify(C, snode);
1031         
1032         return OPERATOR_FINISHED;
1033 }
1034
1035 void NODE_OT_group_socket_move_up(wmOperatorType *ot)
1036 {
1037         /* identifiers */
1038         ot->name = "Move Group Socket Up";
1039         ot->description = "Move up node group socket";
1040         ot->idname = "NODE_OT_group_socket_move_up";
1041         
1042         /* api callbacks */
1043         ot->exec = node_group_socket_move_up_exec;
1044         ot->poll = ED_operator_node_active;
1045         
1046         /* flags */
1047         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1048         
1049         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
1050         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
1051 }
1052
1053 /* ***************** Move Group Socket Up operator ************* */
1054
1055 static int node_group_socket_move_down_exec(bContext *C, wmOperator *op)
1056 {
1057         SpaceNode *snode = CTX_wm_space_node(C);
1058         int index= -1;
1059         int in_out= -1;
1060         bNodeTree *ngroup= snode->edittree;
1061         bNodeSocket *sock, *next;
1062         
1063         ED_preview_kill_jobs(C);
1064         
1065         if (RNA_property_is_set(op->ptr, "index"))
1066                 index = RNA_int_get(op->ptr, "index");
1067         else
1068                 return OPERATOR_CANCELLED;
1069         
1070         if (RNA_property_is_set(op->ptr, "in_out"))
1071                 in_out = RNA_enum_get(op->ptr, "in_out");
1072         else
1073                 return OPERATOR_CANCELLED;
1074         
1075         /* swap */
1076         if (in_out==SOCK_IN) {
1077                 sock = (bNodeSocket*)BLI_findlink(&ngroup->inputs, index);
1078                 next = sock->next;
1079                 /* can't move down the last socket */
1080                 if (!next)
1081                         return OPERATOR_CANCELLED;
1082                 BLI_remlink(&ngroup->inputs, sock);
1083                 BLI_insertlinkafter(&ngroup->inputs, next, sock);
1084                 
1085                 ngroup->update |= NTREE_UPDATE_GROUP_IN;
1086         }
1087         else if (in_out==SOCK_OUT) {
1088                 sock = (bNodeSocket*)BLI_findlink(&ngroup->outputs, index);
1089                 next = sock->next;
1090                 /* can't move down the last socket */
1091                 if (!next)
1092                         return OPERATOR_CANCELLED;
1093                 BLI_remlink(&ngroup->outputs, sock);
1094                 BLI_insertlinkafter(&ngroup->outputs, next, sock);
1095                 
1096                 ngroup->update |= NTREE_UPDATE_GROUP_OUT;
1097         }
1098         ntreeUpdateTree(ngroup);
1099         
1100         snode_notify(C, snode);
1101         
1102         return OPERATOR_FINISHED;
1103 }
1104
1105 void NODE_OT_group_socket_move_down(wmOperatorType *ot)
1106 {
1107         /* identifiers */
1108         ot->name = "Move Group Socket Down";
1109         ot->description = "Move down node group socket";
1110         ot->idname = "NODE_OT_group_socket_move_down";
1111         
1112         /* api callbacks */
1113         ot->exec = node_group_socket_move_down_exec;
1114         ot->poll = ED_operator_node_active;
1115         
1116         /* flags */
1117         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1118         
1119         RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, INT_MAX);
1120         RNA_def_enum(ot->srna, "in_out", socket_in_out_items, SOCK_IN, "Socket Type", "Input or Output");
1121 }
1122
1123 /* ******************** Ungroup operator ********************** */
1124
1125 static int node_group_ungroup_exec(bContext *C, wmOperator *op)
1126 {
1127         SpaceNode *snode = CTX_wm_space_node(C);
1128         bNode *gnode;
1129
1130         ED_preview_kill_jobs(C);
1131
1132         /* are we inside of a group? */
1133         gnode= node_tree_get_editgroup(snode->nodetree);
1134         if(gnode)
1135                 snode_make_group_editable(snode, NULL);
1136         
1137         gnode= nodeGetActive(snode->edittree);
1138         if(gnode==NULL)
1139                 return OPERATOR_CANCELLED;
1140         
1141         if(gnode->type!=NODE_GROUP) {
1142                 BKE_report(op->reports, RPT_WARNING, "Not a group");
1143                 return OPERATOR_CANCELLED;
1144         }
1145         else if(!node_group_ungroup(snode->edittree, gnode)) {
1146                 BKE_report(op->reports, RPT_WARNING, "Can't ungroup");
1147                 return OPERATOR_CANCELLED;
1148         }
1149
1150         snode_notify(C, snode);
1151         snode_dag_update(C, snode);
1152
1153         return OPERATOR_FINISHED;
1154 }
1155
1156 void NODE_OT_group_ungroup(wmOperatorType *ot)
1157 {
1158         /* identifiers */
1159         ot->name = "Ungroup";
1160         ot->description = "Ungroup selected nodes";
1161         ot->idname = "NODE_OT_group_ungroup";
1162         
1163         /* api callbacks */
1164         ot->exec = node_group_ungroup_exec;
1165         ot->poll = ED_operator_node_active;
1166         
1167         /* flags */
1168         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1169 }
1170
1171 /* ************************** Node generic ************** */
1172
1173 /* is rct in visible part of node? */
1174 static bNode *visible_node(SpaceNode *snode, rctf *rct)
1175 {
1176         bNode *node;
1177         
1178         for(node=snode->edittree->nodes.last; node; node=node->prev) {
1179                 if(BLI_isect_rctf(&node->totr, rct, NULL))
1180                         break;
1181         }
1182         return node;
1183 }
1184
1185 /* **************************** */
1186
1187 typedef struct NodeViewMove {
1188         int mvalo[2];
1189         int xmin, ymin, xmax, ymax;
1190 } NodeViewMove;
1191
1192 static int snode_bg_viewmove_modal(bContext *C, wmOperator *op, wmEvent *event)
1193 {
1194         SpaceNode *snode= CTX_wm_space_node(C);
1195         ARegion *ar= CTX_wm_region(C);
1196         NodeViewMove *nvm= op->customdata;
1197
1198         switch (event->type) {
1199                 case MOUSEMOVE:
1200                         
1201                         snode->xof -= (nvm->mvalo[0]-event->mval[0]);
1202                         snode->yof -= (nvm->mvalo[1]-event->mval[1]);
1203                         nvm->mvalo[0]= event->mval[0];
1204                         nvm->mvalo[1]= event->mval[1];
1205                         
1206                         /* prevent dragging image outside of the window and losing it! */
1207                         CLAMP(snode->xof, nvm->xmin, nvm->xmax);
1208                         CLAMP(snode->yof, nvm->ymin, nvm->ymax);
1209                         
1210                         ED_region_tag_redraw(ar);
1211                         
1212                         break;
1213                         
1214                 case LEFTMOUSE:
1215                 case MIDDLEMOUSE:
1216                 case RIGHTMOUSE:
1217                         
1218                         MEM_freeN(nvm);
1219                         op->customdata= NULL;
1220
1221                         WM_event_add_notifier(C, NC_SPACE|ND_SPACE_NODE, NULL);
1222                         
1223                         return OPERATOR_FINISHED;
1224         }
1225         
1226         return OPERATOR_RUNNING_MODAL;
1227 }
1228
1229 static int snode_bg_viewmove_invoke(bContext *C, wmOperator *op, wmEvent *event)
1230 {
1231         ARegion *ar= CTX_wm_region(C);
1232         NodeViewMove *nvm;
1233         Image *ima;
1234         ImBuf *ibuf;
1235         int pad= 10;
1236         void *lock;
1237         
1238         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1239         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1240         
1241         if(ibuf == NULL) {
1242                 BKE_image_release_ibuf(ima, lock);
1243                 return OPERATOR_CANCELLED;
1244         }
1245
1246         nvm= MEM_callocN(sizeof(NodeViewMove), "NodeViewMove struct");
1247         op->customdata= nvm;
1248         nvm->mvalo[0]= event->mval[0];
1249         nvm->mvalo[1]= event->mval[1];
1250
1251         nvm->xmin = -(ar->winx/2) - ibuf->x/2 + pad;
1252         nvm->xmax = ar->winx/2 + ibuf->x/2 - pad;
1253         nvm->ymin = -(ar->winy/2) - ibuf->y/2 + pad;
1254         nvm->ymax = ar->winy/2 + ibuf->y/2 - pad;
1255
1256         BKE_image_release_ibuf(ima, lock);
1257         
1258         /* add modal handler */
1259         WM_event_add_modal_handler(C, op);
1260         
1261         return OPERATOR_RUNNING_MODAL;
1262 }
1263
1264 static int snode_bg_viewmove_cancel(bContext *UNUSED(C), wmOperator *op)
1265 {
1266         MEM_freeN(op->customdata);
1267         op->customdata= NULL;
1268
1269         return OPERATOR_CANCELLED;
1270 }
1271
1272 void NODE_OT_backimage_move(wmOperatorType *ot)
1273 {
1274         /* identifiers */
1275         ot->name= "Background Image Move";
1276         ot->description = "Move Node backdrop";
1277         ot->idname= "NODE_OT_backimage_move";
1278         
1279         /* api callbacks */
1280         ot->invoke= snode_bg_viewmove_invoke;
1281         ot->modal= snode_bg_viewmove_modal;
1282         ot->poll= composite_node_active;
1283         ot->cancel= snode_bg_viewmove_cancel;
1284         
1285         /* flags */
1286         ot->flag= OPTYPE_BLOCKING|OPTYPE_GRAB_POINTER;
1287 }
1288
1289 static int backimage_zoom(bContext *C, wmOperator *op)
1290 {
1291         SpaceNode *snode= CTX_wm_space_node(C);
1292         ARegion *ar= CTX_wm_region(C);
1293         float fac= RNA_float_get(op->ptr, "factor");
1294
1295         snode->zoom *= fac;
1296         ED_region_tag_redraw(ar);
1297
1298         return OPERATOR_FINISHED;
1299 }
1300
1301
1302 void NODE_OT_backimage_zoom(wmOperatorType *ot)
1303 {
1304         
1305         /* identifiers */
1306         ot->name= "Background Image Zoom";
1307         ot->idname= "NODE_OT_backimage_zoom";
1308         
1309         /* api callbacks */
1310         ot->exec= backimage_zoom;
1311         ot->poll= composite_node_active;
1312         
1313         /* flags */
1314         ot->flag= OPTYPE_BLOCKING;
1315
1316         /* internal */
1317         RNA_def_float(ot->srna, "factor", 1.2f, 0.0f, 10.0f, "Factor", "", 0.0f, 10.0f);
1318 }
1319
1320 /******************** sample backdrop operator ********************/
1321
1322 typedef struct ImageSampleInfo {
1323         ARegionType *art;
1324         void *draw_handle;
1325         int x, y;
1326         int channels;
1327         int color_manage;
1328
1329         char col[4];
1330         float colf[4];
1331
1332         int draw;
1333 } ImageSampleInfo;
1334
1335 static void sample_draw(const bContext *C, ARegion *ar, void *arg_info)
1336 {
1337         ImageSampleInfo *info= arg_info;
1338
1339         draw_nodespace_color_info(ar, (CTX_data_scene(C)->r.color_mgt_flag & R_COLOR_MANAGEMENT), info->channels,
1340                                                           info->x, info->y, info->col, info->colf);
1341 }
1342
1343 static void sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1344 {
1345         SpaceNode *snode= CTX_wm_space_node(C);
1346         ARegion *ar= CTX_wm_region(C);
1347         ImageSampleInfo *info= op->customdata;
1348         void *lock;
1349         Image *ima;
1350         ImBuf *ibuf;
1351         float fx, fy, bufx, bufy;
1352         
1353         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1354         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1355         if(!ibuf)
1356                 return;
1357         
1358         if(!ibuf->rect) {
1359                 if(info->color_manage)
1360                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1361                 else
1362                         ibuf->profile = IB_PROFILE_NONE;
1363                 IMB_rect_from_float(ibuf);
1364         }
1365
1366         /* map the mouse coords to the backdrop image space */
1367         bufx = ibuf->x * snode->zoom;
1368         bufy = ibuf->y * snode->zoom;
1369         fx = (bufx > 0.0f ? ((float)event->mval[0] - 0.5f*ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
1370         fy = (bufy > 0.0f ? ((float)event->mval[1] - 0.5f*ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
1371
1372         if(fx>=0.0f && fy>=0.0f && fx<1.0f && fy<1.0f) {
1373                 float *fp;
1374                 char *cp;
1375                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1376
1377                 CLAMP(x, 0, ibuf->x-1);
1378                 CLAMP(y, 0, ibuf->y-1);
1379
1380                 info->x= x;
1381                 info->y= y;
1382                 info->draw= 1;
1383                 info->channels= ibuf->channels;
1384
1385                 if(ibuf->rect) {
1386                         cp= (char *)(ibuf->rect + y*ibuf->x + x);
1387
1388                         info->col[0]= cp[0];
1389                         info->col[1]= cp[1];
1390                         info->col[2]= cp[2];
1391                         info->col[3]= cp[3];
1392
1393                         info->colf[0]= (float)cp[0]/255.0f;
1394                         info->colf[1]= (float)cp[1]/255.0f;
1395                         info->colf[2]= (float)cp[2]/255.0f;
1396                         info->colf[3]= (float)cp[3]/255.0f;
1397                 }
1398                 if(ibuf->rect_float) {
1399                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1400
1401                         info->colf[0]= fp[0];
1402                         info->colf[1]= fp[1];
1403                         info->colf[2]= fp[2];
1404                         info->colf[3]= fp[3];
1405                 }
1406         }
1407         else
1408                 info->draw= 0;
1409
1410         BKE_image_release_ibuf(ima, lock);
1411         
1412         ED_area_tag_redraw(CTX_wm_area(C));
1413 }
1414
1415 static void sample_exit(bContext *C, wmOperator *op)
1416 {
1417         ImageSampleInfo *info= op->customdata;
1418
1419         ED_region_draw_cb_exit(info->art, info->draw_handle);
1420         ED_area_tag_redraw(CTX_wm_area(C));
1421         MEM_freeN(info);
1422 }
1423
1424 static int sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1425 {
1426         SpaceNode *snode= CTX_wm_space_node(C);
1427         ARegion *ar= CTX_wm_region(C);
1428         ImageSampleInfo *info;
1429
1430         if(snode->treetype!=NTREE_COMPOSIT || !(snode->flag & SNODE_BACKDRAW))
1431                 return OPERATOR_CANCELLED;
1432         
1433         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1434         info->art= ar->type;
1435         info->draw_handle = ED_region_draw_cb_activate(ar->type, sample_draw, info, REGION_DRAW_POST_PIXEL);
1436         op->customdata= info;
1437
1438         sample_apply(C, op, event);
1439
1440         WM_event_add_modal_handler(C, op);
1441
1442         return OPERATOR_RUNNING_MODAL;
1443 }
1444
1445 static int sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1446 {
1447         switch(event->type) {
1448                 case LEFTMOUSE:
1449                 case RIGHTMOUSE: // XXX hardcoded
1450                         sample_exit(C, op);
1451                         return OPERATOR_CANCELLED;
1452                 case MOUSEMOVE:
1453                         sample_apply(C, op, event);
1454                         break;
1455         }
1456
1457         return OPERATOR_RUNNING_MODAL;
1458 }
1459
1460 static int sample_cancel(bContext *C, wmOperator *op)
1461 {
1462         sample_exit(C, op);
1463         return OPERATOR_CANCELLED;
1464 }
1465
1466 void NODE_OT_backimage_sample(wmOperatorType *ot)
1467 {
1468         /* identifiers */
1469         ot->name= "Backimage Sample";
1470         ot->idname= "NODE_OT_backimage_sample";
1471         
1472         /* api callbacks */
1473         ot->invoke= sample_invoke;
1474         ot->modal= sample_modal;
1475         ot->cancel= sample_cancel;
1476         ot->poll= ED_operator_node_active;
1477
1478         /* flags */
1479         ot->flag= OPTYPE_BLOCKING;
1480 }
1481
1482 /* ********************** size widget operator ******************** */
1483
1484 typedef struct NodeSizeWidget {
1485         float mxstart, mystart;
1486         float oldwidth, oldheight;
1487         float oldminiwidth;
1488 } NodeSizeWidget;
1489
1490 static int node_resize_modal(bContext *C, wmOperator *op, wmEvent *event)
1491 {
1492         SpaceNode *snode= CTX_wm_space_node(C);
1493         ARegion *ar= CTX_wm_region(C);
1494         bNode *node= editnode_get_active(snode->edittree);
1495         NodeSizeWidget *nsw= op->customdata;
1496         float mx, my;
1497         
1498         switch (event->type) {
1499                 case MOUSEMOVE:
1500                         
1501                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1502                                                                          &mx, &my);
1503                         
1504                         if (node) {
1505                                 if(node->flag & NODE_HIDDEN) {
1506                                         node->miniwidth= nsw->oldminiwidth + mx - nsw->mxstart;
1507                                         CLAMP(node->miniwidth, 0.0f, 100.0f);
1508                                 }
1509                                 else {
1510                                         node->width= nsw->oldwidth + mx - nsw->mxstart;
1511                                         CLAMP(node->width, UI_DPI_FAC*node->typeinfo->minwidth, UI_DPI_FAC*node->typeinfo->maxwidth);
1512                                 }
1513                                 /* height works the other way round ... */
1514                                 node->height= nsw->oldheight - my + nsw->mystart;
1515                                 CLAMP(node->height, node->typeinfo->minheight, node->typeinfo->maxheight);
1516                         }
1517                                 
1518                         ED_region_tag_redraw(ar);
1519
1520                         break;
1521                         
1522                 case LEFTMOUSE:
1523                 case MIDDLEMOUSE:
1524                 case RIGHTMOUSE:
1525                         
1526                         MEM_freeN(nsw);
1527                         op->customdata= NULL;
1528                         
1529                         ED_node_update_hierarchy(C, snode->edittree);
1530                         
1531                         return OPERATOR_FINISHED;
1532         }
1533         
1534         return OPERATOR_RUNNING_MODAL;
1535 }
1536
1537 static int node_resize_invoke(bContext *C, wmOperator *op, wmEvent *event)
1538 {
1539         SpaceNode *snode= CTX_wm_space_node(C);
1540         ARegion *ar= CTX_wm_region(C);
1541         bNode *node= editnode_get_active(snode->edittree);
1542         
1543         if(node) {
1544                 /* convert mouse coordinates to v2d space */
1545                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1546                                                                  &snode->mx, &snode->my);
1547                 
1548                 if(node->typeinfo->resize_area_func(node, snode->mx, snode->my)) {
1549                         NodeSizeWidget *nsw= MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
1550                         
1551                         op->customdata= nsw;
1552                         nsw->mxstart= snode->mx;
1553                         nsw->mystart= snode->my;
1554                         
1555                         /* store old */
1556                         nsw->oldwidth= node->width;
1557                         nsw->oldheight= node->height;
1558                         nsw->oldminiwidth= node->miniwidth;
1559                         
1560                         /* add modal handler */
1561                         WM_event_add_modal_handler(C, op);
1562
1563                         return OPERATOR_RUNNING_MODAL;
1564                 }
1565         }
1566         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
1567 }
1568
1569 static int node_resize_cancel(bContext *UNUSED(C), wmOperator *op)
1570 {
1571         MEM_freeN(op->customdata);
1572         op->customdata= NULL;
1573
1574         return OPERATOR_CANCELLED;
1575 }
1576
1577 void NODE_OT_resize(wmOperatorType *ot)
1578 {
1579         /* identifiers */
1580         ot->name= "Resize Node";
1581         ot->idname= "NODE_OT_resize";
1582         
1583         /* api callbacks */
1584         ot->invoke= node_resize_invoke;
1585         ot->modal= node_resize_modal;
1586         ot->poll= ED_operator_node_active;
1587         ot->cancel= node_resize_cancel;
1588         
1589         /* flags */
1590         ot->flag= OPTYPE_BLOCKING;
1591 }
1592
1593 /* ********************** select ******************** */
1594
1595
1596 /* no undo here! */
1597 void node_deselectall(SpaceNode *snode)
1598 {
1599         bNode *node;
1600         
1601         for(node= snode->edittree->nodes.first; node; node= node->next)
1602                 node->flag &= ~SELECT;
1603 }
1604
1605 /* return 1 if we need redraw otherwise zero. */
1606 int node_select_same_type(SpaceNode *snode)
1607 {
1608         bNode *nac, *p;
1609         int redraw;
1610
1611         /* search for the active node. */
1612         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1613                 if (nac->flag & SELECT)
1614                         break;
1615         }
1616
1617         /* no active node, return. */
1618         if (!nac)
1619                 return(0);
1620
1621         redraw= 0;
1622         for (p= snode->edittree->nodes.first; p; p= p->next) {
1623                 if (p->type != nac->type && p->flag & SELECT) {
1624                         /* if it's selected but different type, unselect */
1625                         redraw= 1;
1626                         p->flag &= ~SELECT;
1627                 }
1628                 else if (p->type == nac->type && (!(p->flag & SELECT))) {
1629                         /* if it's the same type and is not selected, select! */
1630                         redraw= 1;
1631                         p->flag |= SELECT;
1632                 }
1633         }
1634         return(redraw);
1635 }
1636
1637 /* return 1 if we need redraw, otherwise zero.
1638  * dir can be 0 == next or 0 != prev.
1639  */
1640 int node_select_same_type_np(SpaceNode *snode, int dir)
1641 {
1642         bNode *nac, *p;
1643
1644         /* search the active one. */
1645         for (nac= snode->edittree->nodes.first; nac; nac= nac->next) {
1646                 if (nac->flag & SELECT)
1647                         break;
1648         }
1649
1650         /* no active node, return. */
1651         if (!nac)
1652                 return(0);
1653
1654         if (dir == 0)
1655                 p= nac->next;
1656         else
1657                 p= nac->prev;
1658
1659         while (p) {
1660                 /* Now search the next with the same type. */
1661                 if (p->type == nac->type)
1662                         break;
1663
1664                 if (dir == 0)
1665                         p= p->next;
1666                 else
1667                         p= p->prev;
1668         }
1669
1670         if (p) {
1671                 node_deselectall(snode);
1672                 p->flag |= SELECT;
1673                 return(1);
1674         }
1675         return(0);
1676 }
1677
1678 int node_has_hidden_sockets(bNode *node)
1679 {
1680         bNodeSocket *sock;
1681         
1682         for(sock= node->inputs.first; sock; sock= sock->next)
1683                 if(sock->flag & SOCK_HIDDEN)
1684                         return 1;
1685         for(sock= node->outputs.first; sock; sock= sock->next)
1686                 if(sock->flag & SOCK_HIDDEN)
1687                         return 1;
1688         return 0;
1689 }
1690
1691 static void node_link_viewer(SpaceNode *snode, bNode *tonode)
1692 {
1693         bNode *node;
1694
1695         /* context check */
1696         if(tonode==NULL || tonode->outputs.first==NULL)
1697                 return;
1698         if( ELEM(tonode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1699                 return;
1700         
1701         /* get viewer */
1702         for(node= snode->edittree->nodes.first; node; node= node->next)
1703                 if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1704                         if(node->flag & NODE_DO_OUTPUT)
1705                                 break;
1706         /* no viewer, we make one active */
1707         if(node==NULL) {
1708                 for(node= snode->edittree->nodes.first; node; node= node->next) {
1709                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
1710                                 node->flag |= NODE_DO_OUTPUT;
1711                                 break;
1712                         }
1713                 }
1714         }
1715                 
1716         if(node) {
1717                 bNodeLink *link;
1718                 bNodeSocket *sock= NULL;
1719
1720                 /* try to find an already connected socket to cycle to the next */
1721                 for(link= snode->edittree->links.first; link; link= link->next)
1722                         if(link->tonode==node && link->fromnode==tonode)
1723                                 if(link->tosock==node->inputs.first)
1724                                         break;
1725
1726                 if(link) {
1727                         /* unlink existing connection */
1728                         sock= link->fromsock;
1729                         nodeRemLink(snode->edittree, link);
1730
1731                         /* find a socket after the previously connected socket */
1732                         for(sock=sock->next; sock; sock= sock->next)
1733                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1734                                         break;
1735                 }
1736
1737                 /* find a socket starting from the first socket */
1738                 if(!sock) {
1739                         for(sock= tonode->outputs.first; sock; sock= sock->next)
1740                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL)))
1741                                         break;
1742                 }
1743                 
1744                 if(sock) {
1745                         /* get link to viewer */
1746                         for(link= snode->edittree->links.first; link; link= link->next)
1747                                 if(link->tonode==node && link->tosock==node->inputs.first)
1748                                         break;
1749                         
1750                         if(link==NULL) {
1751                                 nodeAddLink(snode->edittree, tonode, sock, node, node->inputs.first);
1752                         }
1753                         else {
1754                                 link->fromnode= tonode;
1755                                 link->fromsock= sock;
1756                         }
1757                         ntreeUpdateTree(snode->edittree);
1758                         snode_tag_changed(snode, node);
1759                 }
1760         }
1761 }
1762
1763
1764 static int node_active_link_viewer(bContext *C, wmOperator *UNUSED(op))
1765 {
1766         SpaceNode *snode= CTX_wm_space_node(C);
1767         bNode *node;
1768         
1769         node= editnode_get_active(snode->edittree);
1770         
1771         if(!node)
1772                 return OPERATOR_CANCELLED;
1773
1774         ED_preview_kill_jobs(C);
1775
1776         node_link_viewer(snode, node);
1777         snode_notify(C, snode);
1778
1779         return OPERATOR_FINISHED;
1780 }
1781
1782
1783
1784 void NODE_OT_link_viewer(wmOperatorType *ot)
1785 {
1786         /* identifiers */
1787         ot->name= "Link to Viewer Node";
1788         ot->description = "Link to Viewer Node";
1789         ot->idname= "NODE_OT_link_viewer";
1790         
1791         /* api callbacks */
1792         ot->exec= node_active_link_viewer;
1793         ot->poll= ED_operator_node_active;
1794         
1795         /* flags */
1796         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1797 }
1798
1799
1800
1801 /* return 0, nothing done */
1802 static int UNUSED_FUNCTION(node_mouse_groupheader)(SpaceNode *snode)
1803 {
1804         bNode *gnode;
1805         float mx=0, my=0;
1806 // XXX  int mval[2];
1807         
1808         gnode= node_tree_get_editgroup(snode->nodetree);
1809         if(gnode==NULL) return 0;
1810         
1811 // XXX  getmouseco_areawin(mval);
1812 // XXX  areamouseco_to_ipoco(G.v2d, mval, &mx, &my);
1813         
1814         /* click in header or outside? */
1815         if(BLI_in_rctf(&gnode->totr, mx, my)==0) {
1816                 rctf rect= gnode->totr;
1817                 
1818                 rect.ymax += NODE_DY;
1819                 if(BLI_in_rctf(&rect, mx, my)==0)
1820                         snode_make_group_editable(snode, NULL); /* toggles, so exits editmode */
1821 //              else
1822 // XXX                  transform_nodes(snode->nodetree, 'g', "Move group");
1823                 
1824                 return 1;
1825         }
1826         return 0;
1827 }
1828
1829 /* checks snode->mouse position, and returns found node/socket */
1830 /* type is SOCK_IN and/or SOCK_OUT */
1831 static int find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1832 {
1833         bNode *node;
1834         bNodeSocket *sock;
1835         rctf rect;
1836         
1837         /* check if we click in a socket */
1838         for(node= snode->edittree->nodes.first; node; node= node->next) {
1839                 
1840                 rect.xmin = snode->mx - (NODE_SOCKSIZE+4);
1841                 rect.ymin = snode->my - (NODE_SOCKSIZE+4);
1842                 rect.xmax = snode->mx + (NODE_SOCKSIZE+4);
1843                 rect.ymax = snode->my + (NODE_SOCKSIZE+4);
1844                 
1845                 if (!(node->flag & NODE_HIDDEN)) {
1846                         /* extra padding inside and out - allow dragging on the text areas too */
1847                         if (in_out == SOCK_IN) {
1848                                 rect.xmax += NODE_SOCKSIZE;
1849                                 rect.xmin -= NODE_SOCKSIZE*4;
1850                         } else if (in_out == SOCK_OUT) {
1851                                 rect.xmax += NODE_SOCKSIZE*4;
1852                                 rect.xmin -= NODE_SOCKSIZE;
1853                         }
1854                 }
1855                 
1856                 if(in_out & SOCK_IN) {
1857                         for(sock= node->inputs.first; sock; sock= sock->next) {
1858                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1859                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1860                                                 if(node == visible_node(snode, &rect)) {
1861                                                         *nodep= node;
1862                                                         *sockp= sock;
1863                                                         return 1;
1864                                                 }
1865                                         }
1866                                 }
1867                         }
1868                 }
1869                 if(in_out & SOCK_OUT) {
1870                         for(sock= node->outputs.first; sock; sock= sock->next) {
1871                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1872                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1873                                                 if(node == visible_node(snode, &rect)) {
1874                                                         *nodep= node;
1875                                                         *sockp= sock;
1876                                                         return 1;
1877                                                 }
1878                                         }
1879                                 }
1880                         }
1881                 }
1882         }
1883         
1884         /* check group sockets
1885          * NB: using ngroup->outputs as input sockets and vice versa here!
1886          */
1887         if(in_out & SOCK_IN) {
1888                 for(sock= snode->edittree->outputs.first; sock; sock= sock->next) {
1889                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1890                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1891                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1892                                         *sockp= sock;
1893                                         return 1;
1894                                 }
1895                         }
1896                 }
1897         }
1898         if(in_out & SOCK_OUT) {
1899                 for(sock= snode->edittree->inputs.first; sock; sock= sock->next) {
1900                         if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1901                                 if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1902                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1903                                         *sockp= sock;
1904                                         return 1;
1905                                 }
1906                         }
1907                 }
1908         }
1909         
1910         return 0;
1911 }
1912
1913 static int node_socket_hilights(SpaceNode *snode, int in_out)
1914 {
1915         bNode *node;
1916         bNodeSocket *sock, *tsock, *socksel= NULL;
1917         short redraw= 0;
1918         
1919         if(snode->edittree==NULL) return 0;
1920         
1921         /* deselect sockets */
1922         for(node= snode->edittree->nodes.first; node; node= node->next) {
1923                 for(sock= node->inputs.first; sock; sock= sock->next) {
1924                         if(sock->flag & SELECT) {
1925                                 sock->flag &= ~SELECT;
1926                                 redraw++;
1927                                 socksel= sock;
1928                         }
1929                 }
1930                 for(sock= node->outputs.first; sock; sock= sock->next) {
1931                         if(sock->flag & SELECT) {
1932                                 sock->flag &= ~SELECT;
1933                                 redraw++;
1934                                 socksel= sock;
1935                         }
1936                 }
1937         }
1938         
1939         // XXX mousepos should be set here!
1940         
1941         if(find_indicated_socket(snode, &node, &tsock, in_out)) {
1942                 tsock->flag |= SELECT;
1943                 if(redraw==1 && tsock==socksel) redraw= 0;
1944                 else redraw= 1;
1945         }
1946         
1947         return redraw;
1948 }
1949
1950 static int outside_group_rect(SpaceNode *snode)
1951 {
1952         bNode *gnode= node_tree_get_editgroup(snode->nodetree);
1953         if (gnode) {
1954                 return (snode->mx < gnode->totr.xmin || snode->mx >= gnode->totr.xmax
1955                                 || snode->my < gnode->totr.ymin || snode->my >= gnode->totr.ymax);
1956         }
1957         return 0;
1958 }
1959
1960 /* ****************** Add *********************** */
1961
1962
1963 typedef struct bNodeListItem {
1964         struct bNodeListItem *next, *prev;
1965         struct bNode *node;     
1966 } bNodeListItem;
1967
1968 static int sort_nodes_locx(void *a, void *b)
1969 {
1970         bNodeListItem *nli1 = (bNodeListItem *)a;
1971         bNodeListItem *nli2 = (bNodeListItem *)b;
1972         bNode *node1 = nli1->node;
1973         bNode *node2 = nli2->node;
1974         
1975         if (node1->locx > node2->locx)
1976                 return 1;
1977         else 
1978                 return 0;
1979 }
1980
1981 static int socket_is_available(bNodeTree *ntree, bNodeSocket *sock, int allow_used)
1982 {
1983         if (sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))
1984                 return 0;
1985         
1986         if (!allow_used) {
1987                 if (nodeCountSocketLinks(ntree, sock) > 0)
1988                         return 0;
1989         }
1990         return 1;
1991 }
1992
1993 static bNodeSocket *best_socket_output(bNodeTree *ntree, bNode *node, bNodeSocket *sock_target, int allow_multiple)
1994 {
1995         bNodeSocket *sock;
1996         
1997         /* first try to find a socket with a matching name */
1998         for (sock=node->outputs.first; sock; sock=sock->next) {
1999
2000                 if (!socket_is_available(ntree, sock, allow_multiple))
2001                         continue;
2002
2003                 /* check for same types */
2004                 if (sock->type == sock_target->type) {
2005                         if (strcmp(sock->name, sock_target->name)==0)
2006                                 return sock;
2007                 }
2008         }
2009         
2010         /* otherwise settle for the first available socket of the right type */
2011         for (sock=node->outputs.first; sock; sock=sock->next) {
2012
2013                 if (!socket_is_available(ntree, sock, allow_multiple))
2014                         continue;
2015                 
2016                 /* check for same types */
2017                 if (sock->type == sock_target->type) {
2018                         return sock;
2019                 }
2020         }
2021         
2022         return NULL;
2023 }
2024
2025 /* this is a bit complicated, but designed to prioritise finding 
2026  * sockets of higher types, such as image, first */
2027 static bNodeSocket *best_socket_input(bNodeTree *ntree, bNode *node, int num, int replace)
2028 {
2029         bNodeSocket *sock;
2030         int socktype, maxtype=0;
2031         int a = 0;
2032         
2033         for (sock=node->inputs.first; sock; sock=sock->next) {
2034                 maxtype = MAX2(sock->type, maxtype);
2035         }
2036         
2037         /* find sockets of higher 'types' first (i.e. image) */
2038         for (socktype=maxtype; socktype >= 0; socktype--) {
2039                 for (sock=node->inputs.first; sock; sock=sock->next) {
2040                         
2041                         if (!socket_is_available(ntree, sock, replace)) {
2042                                 a++;
2043                                 continue;
2044                         }
2045                                 
2046                         if (sock->type == socktype) {
2047                                 /* increment to make sure we don't keep finding 
2048                                  * the same socket on every attempt running this function */
2049                                 a++;
2050                                 if (a > num)
2051                                         return sock;
2052                         }
2053                 }
2054         }
2055         
2056         return NULL;
2057 }
2058
2059 void snode_autoconnect(SpaceNode *snode, int allow_multiple, int replace)
2060 {
2061         ListBase *nodelist = MEM_callocN(sizeof(ListBase), "items_list");
2062         bNodeListItem *nli;
2063         bNode *node;
2064         bNodeLink *link;
2065         int i, numlinks=0;
2066         
2067         for(node= snode->edittree->nodes.first; node; node= node->next) {
2068                 if(node->flag & NODE_SELECT) {
2069                         nli = MEM_mallocN(sizeof(bNodeListItem), "temporary node list item");
2070                         nli->node = node;
2071                         BLI_addtail(nodelist, nli);
2072                 }
2073         }
2074         
2075         /* sort nodes left to right */
2076         BLI_sortlist(nodelist, sort_nodes_locx);
2077         
2078         for (nli=nodelist->first; nli; nli=nli->next) {
2079                 bNode *node_fr, *node_to;
2080                 bNodeSocket *sock_fr, *sock_to;
2081                 
2082                 if (nli->next == NULL) break;
2083                 
2084                 node_fr = nli->node;
2085                 node_to = nli->next->node;
2086                 
2087                 /* check over input sockets first */
2088                 for (i=0; i<BLI_countlist(&node_to->inputs); i++) {
2089                         
2090                         /* find the best guess input socket */
2091                         sock_to = best_socket_input(snode->edittree, node_to, i, replace);
2092                         if (!sock_to) continue;
2093                         
2094                         /* check for an appropriate output socket to connect from */
2095                         sock_fr = best_socket_output(snode->edittree, node_fr, sock_to, allow_multiple);
2096                         if (!sock_fr) continue;
2097                         
2098                         /* then we can connect */
2099                         if (replace)
2100                                 nodeRemSocketLinks(snode->edittree, sock_to);
2101                         
2102                         link = nodeAddLink(snode->edittree, node_fr, sock_fr, node_to, sock_to);
2103                         /* validate the new link */
2104                         ntreeUpdateTree(snode->edittree);
2105                         if (!(link->flag & NODE_LINK_VALID)) {
2106                                 nodeRemLink(snode->edittree, link);
2107                                 continue;
2108                         }
2109                         
2110                         snode_tag_changed(snode, node_to);
2111                         ++numlinks;
2112                         break;
2113                 }
2114         }
2115         
2116         if (numlinks > 0) {
2117                 ntreeUpdateTree(snode->edittree);
2118         }
2119         
2120         BLI_freelistN(nodelist);
2121         MEM_freeN(nodelist);
2122 }
2123
2124 /* can be called from menus too, but they should do own undopush and redraws */
2125 bNode *node_add_node(SpaceNode *snode, Main *bmain, Scene *scene, bNodeTemplate *ntemp, float locx, float locy)
2126 {
2127         bNode *node= NULL, *gnode;
2128         
2129         node_deselectall(snode);
2130         
2131         node = nodeAddNode(snode->edittree, ntemp);
2132         
2133         /* generics */
2134         if(node) {
2135                 node->locx= locx;
2136                 node->locy= locy + 60.0f;               // arbitrary.. so its visible, (0,0) is top of node
2137                 node->flag |= SELECT;
2138                 
2139                 gnode= node_tree_get_editgroup(snode->nodetree);
2140                 if(gnode) {
2141                         node->locx -= gnode->locx;
2142                         node->locy -= gnode->locy;
2143                 }
2144
2145                 ntreeUpdateTree(snode->edittree);
2146                 ED_node_set_active(bmain, snode->edittree, node);
2147                 
2148                 if(snode->nodetree->type==NTREE_COMPOSIT) {
2149                         if(ELEM4(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE, CMP_NODE_DEFOCUS, CMP_NODE_OUTPUT_FILE))
2150                                 node->id = &scene->id;
2151                         
2152                         ntreeCompositForceHidden(snode->edittree, scene);
2153                 }
2154                         
2155                 if(node->id)
2156                         id_us_plus(node->id);
2157                         
2158                 snode_tag_changed(snode, node);
2159         }
2160         
2161         if(snode->nodetree->type==NTREE_TEXTURE) {
2162                 ntreeTexCheckCyclics(snode->edittree);
2163         }
2164         
2165         return node;
2166 }
2167
2168 /* ****************** Duplicate *********************** */
2169
2170 static int node_duplicate_exec(bContext *C, wmOperator *op)
2171 {
2172         SpaceNode *snode= CTX_wm_space_node(C);
2173         bNodeTree *ntree= snode->edittree;
2174         bNode *node, *newnode, *lastnode;
2175         bNodeLink *link, *newlink, *lastlink;
2176         int keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
2177         
2178         ED_preview_kill_jobs(C);
2179         
2180         lastnode = ntree->nodes.last;
2181         for(node= ntree->nodes.first; node; node= node->next) {
2182                 if(node->flag & SELECT) {
2183                         newnode = nodeCopyNode(ntree, node);
2184                         
2185                         if(newnode->id) {
2186                                 /* simple id user adjustment, node internal functions dont touch this
2187                                  * but operators and readfile.c do. */
2188                                 id_us_plus(newnode->id);
2189                                 /* to ensure redraws or rerenders happen */
2190                                 ED_node_changed_update(snode->id, newnode);
2191                         }
2192                 }
2193                 
2194                 /* make sure we don't copy new nodes again! */
2195                 if (node==lastnode)
2196                         break;
2197         }
2198         
2199         /* copy links between selected nodes
2200          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
2201          */
2202         lastlink = ntree->links.last;
2203         for (link=ntree->links.first; link; link=link->next) {
2204                 /* This creates new links between copied nodes.
2205                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
2206                  */
2207                 if (link->tonode && (link->tonode->flag & NODE_SELECT)
2208                         && (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT)))) {
2209                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
2210                         newlink->flag = link->flag;
2211                         newlink->tonode = link->tonode->new_node;
2212                         newlink->tosock = link->tosock->new_sock;
2213                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
2214                                 newlink->fromnode = link->fromnode->new_node;
2215                                 newlink->fromsock = link->fromsock->new_sock;
2216                         }
2217                         else {
2218                                 /* input node not copied, this keeps the original input linked */
2219                                 newlink->fromnode = link->fromnode;
2220                                 newlink->fromsock = link->fromsock;
2221                         }
2222                         
2223                         BLI_addtail(&ntree->links, newlink);
2224                 }
2225                 
2226                 /* make sure we don't copy new links again! */
2227                 if (link==lastlink)
2228                         break;
2229         }
2230         
2231         /* deselect old nodes, select the copies instead */
2232         for(node= ntree->nodes.first; node; node= node->next) {
2233                 if(node->flag & SELECT) {
2234                         /* has been set during copy above */
2235                         newnode = node->new_node;
2236                         
2237                         node->flag &= ~(NODE_SELECT|NODE_ACTIVE);
2238                         newnode->flag |= NODE_SELECT;
2239                 }
2240                 
2241                 /* make sure we don't copy new nodes again! */
2242                 if (node==lastnode)
2243                         break;
2244         }
2245         
2246         ntreeUpdateTree(snode->edittree);
2247         
2248         snode_notify(C, snode);
2249         snode_dag_update(C, snode);
2250
2251         return OPERATOR_FINISHED;
2252 }
2253
2254 void NODE_OT_duplicate(wmOperatorType *ot)
2255 {
2256         /* identifiers */
2257         ot->name= "Duplicate Nodes";
2258         ot->description = "Duplicate the nodes";
2259         ot->idname= "NODE_OT_duplicate";
2260         
2261         /* api callbacks */
2262         ot->exec= node_duplicate_exec;
2263         ot->poll= ED_operator_node_active;
2264         
2265         /* flags */
2266         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2267         
2268         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
2269 }
2270
2271 /* *************************** add link op ******************** */
2272
2273 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
2274 {
2275         bNodeLink *tlink;
2276         bNodeSocket *sock;
2277         
2278         if(tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
2279                 
2280                 for(tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
2281                         if(link!=tlink && tlink->tosock==link->tosock)
2282                                 break;
2283                 }
2284                 if(tlink) {
2285                         /* try to move the existing link to the next available socket */
2286                         if (tlink->tonode) {
2287                                 /* is there a free input socket with the target type? */
2288                                 for(sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
2289                                         if(sock->type==tlink->tosock->type)
2290                                                 if(nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
2291                                                         break;
2292                                 }
2293                                 if(sock) {
2294                                         tlink->tosock= sock;
2295                                         sock->flag &= ~SOCK_HIDDEN;
2296                                 }
2297                                 else {
2298                                         nodeRemLink(snode->edittree, tlink);
2299                                 }
2300                         }
2301                         else
2302                                 nodeRemLink(snode->edittree, tlink);
2303                 }
2304         }
2305 }
2306
2307 /* loop that adds a nodelink, called by function below  */
2308 /* in_out = starting socket */
2309 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
2310 {
2311         SpaceNode *snode= CTX_wm_space_node(C);
2312         ARegion *ar= CTX_wm_region(C);
2313         bNodeLinkDrag *nldrag= op->customdata;
2314         bNode *tnode, *node;
2315         bNodeSocket *tsock= NULL, *sock;
2316         bNodeLink *link;
2317         int in_out;
2318
2319         in_out= nldrag->in_out;
2320         node= nldrag->node;
2321         sock= nldrag->sock;
2322         link= nldrag->link;
2323         
2324         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2325                                                          &snode->mx, &snode->my);
2326
2327         switch (event->type) {
2328                 case MOUSEMOVE:
2329                         
2330                         if(in_out==SOCK_OUT) {
2331                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_IN)) {
2332                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2333                                                 if( link->tosock!= tsock && (!tnode || (tnode!=node && link->tonode!=tnode)) ) {
2334                                                         link->tonode= tnode;
2335                                                         link->tosock= tsock;
2336                                                         if (link->prev==NULL && link->next==NULL) {
2337                                                                 BLI_addtail(&snode->edittree->links, link);
2338                                                         }
2339                                                         
2340                                                         snode->edittree->update |= NTREE_UPDATE_LINKS;
2341                                                         ntreeUpdateTree(snode->edittree);
2342                                                 }
2343                                         }
2344                                 }
2345                                 else {
2346                                         if (link->tonode || link->tosock) {
2347                                                 BLI_remlink(&snode->edittree->links, link);
2348                                                 link->prev = link->next = NULL;
2349                                                 link->tonode= NULL;
2350                                                 link->tosock= NULL;
2351                                                 
2352                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2353                                                 ntreeUpdateTree(snode->edittree);
2354                                         }
2355                                 }
2356                         }
2357                         else {
2358                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
2359                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2360                                                 if(nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
2361                                                         if( link->fromsock!= tsock && (!tnode || (tnode!=node && link->fromnode!=tnode)) ) {
2362                                                                 link->fromnode= tnode;
2363                                                                 link->fromsock= tsock;
2364                                                                 if (link->prev==NULL && link->next==NULL) {
2365                                                                         BLI_addtail(&snode->edittree->links, link);
2366                                                                 }
2367                                                                 
2368                                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2369                                                                 ntreeUpdateTree(snode->edittree);
2370                                                         }
2371                                                 }
2372                                         }
2373                                 }
2374                                 else {
2375                                         if (link->tonode || link->tosock) {
2376                                                 BLI_remlink(&snode->edittree->links, link);
2377                                                 link->prev = link->next = NULL;
2378                                                 link->fromnode= NULL;
2379                                                 link->fromsock= NULL;
2380                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2381                                                 ntreeUpdateTree(snode->edittree);
2382                                         }
2383                                 }
2384                         }
2385                         /* hilight target sockets only */
2386                         node_socket_hilights(snode, in_out==SOCK_OUT?SOCK_IN:SOCK_OUT);
2387                         ED_region_tag_redraw(ar);
2388                         break;
2389                         
2390                 case LEFTMOUSE:
2391                 case RIGHTMOUSE:
2392                 case MIDDLEMOUSE:
2393                         if(link->tosock && link->fromsock) {
2394                                 /* send changed events for original tonode and new */
2395                                 snode_tag_changed(snode, link->tonode);
2396                                 
2397                                 /* we might need to remove a link */
2398                                 if(in_out==SOCK_OUT)
2399                                         node_remove_extra_links(snode, link->tosock, link);
2400                                 
2401                                 /* when linking to group outputs, update the socket type */
2402                                 /* XXX this should all be part of a generic update system */
2403                                 if (!link->tonode) {
2404                                         link->tosock->type = link->fromsock->type;
2405                                 }
2406                         }
2407                         else if (outside_group_rect(snode) && (link->tonode || link->fromnode)) {
2408                                 /* automatically add new group socket */
2409                                 if (link->tonode && link->tosock) {
2410                                         link->fromsock = node_group_expose_socket(snode->edittree, link->tosock, SOCK_IN);
2411                                         link->fromnode = NULL;
2412                                         if (link->prev==NULL && link->next==NULL) {
2413                                                 BLI_addtail(&snode->edittree->links, link);
2414                                         }
2415                                         snode->edittree->update |= NTREE_UPDATE_GROUP_IN | NTREE_UPDATE_LINKS;
2416                                 }
2417                                 else if (link->fromnode && link->fromsock) {
2418                                         link->tosock = node_group_expose_socket(snode->edittree, link->fromsock, SOCK_OUT);
2419                                         link->tonode = NULL;
2420                                         if (link->prev==NULL && link->next==NULL) {
2421                                                 BLI_addtail(&snode->edittree->links, link);
2422                                         }
2423                                         snode->edittree->update |= NTREE_UPDATE_GROUP_OUT | NTREE_UPDATE_LINKS;
2424                                 }
2425                         }
2426                         else
2427                                 nodeRemLink(snode->edittree, link);
2428                         
2429                         ntreeUpdateTree(snode->edittree);
2430                         snode_notify(C, snode);
2431                         snode_dag_update(C, snode);
2432                         
2433                         BLI_remlink(&snode->linkdrag, nldrag);
2434                         MEM_freeN(nldrag);
2435                         
2436                         return OPERATOR_FINISHED;
2437         }
2438         
2439         return OPERATOR_RUNNING_MODAL;
2440 }
2441
2442 /* return 1 when socket clicked */
2443 static int node_link_init(SpaceNode *snode, bNodeLinkDrag *nldrag)
2444 {
2445         bNodeLink *link;
2446
2447         /* output indicated? */
2448         if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
2449                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2450                         return SOCK_OUT;
2451                 else {
2452                         /* find if we break a link */
2453                         for(link= snode->edittree->links.first; link; link= link->next) {
2454                                 if(link->fromsock==nldrag->sock)
2455                                         break;
2456                         }
2457                         if(link) {
2458                                 nldrag->node= link->tonode;
2459                                 nldrag->sock= link->tosock;
2460                                 nodeRemLink(snode->edittree, link);
2461                                 return SOCK_IN;
2462                         }
2463                 }
2464         }
2465         /* or an input? */
2466         else if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
2467                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2468                         return SOCK_IN;
2469                 else {
2470                         /* find if we break a link */
2471                         for(link= snode->edittree->links.first; link; link= link->next) {
2472                                 if(link->tosock==nldrag->sock)
2473                                         break;
2474                         }
2475                         if(link) {
2476                                 /* send changed event to original tonode */
2477                                 if(link->tonode) 
2478                                         snode_tag_changed(snode, link->tonode);
2479                                 
2480                                 nldrag->node= link->fromnode;
2481                                 nldrag->sock= link->fromsock;
2482                                 nodeRemLink(snode->edittree, link);
2483                                 return SOCK_OUT;
2484                         }
2485                 }
2486         }
2487         
2488         return 0;
2489 }
2490
2491 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
2492 {
2493         SpaceNode *snode= CTX_wm_space_node(C);
2494         ARegion *ar= CTX_wm_region(C);
2495         bNodeLinkDrag *nldrag= MEM_callocN(sizeof(bNodeLinkDrag), "drag link op customdata");
2496         
2497         
2498         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2499                                                          &snode->mx, &snode->my);
2500
2501         ED_preview_kill_jobs(C);
2502
2503         nldrag->in_out= node_link_init(snode, nldrag);
2504         
2505         if(nldrag->in_out) {
2506                 op->customdata= nldrag;
2507                 
2508                 /* we make a temporal link */
2509                 if(nldrag->in_out==SOCK_OUT) {
2510                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2511                         nldrag->link->fromnode= nldrag->node;
2512                         nldrag->link->fromsock= nldrag->sock;
2513                         nldrag->link->tonode= NULL;
2514                         nldrag->link->tosock= NULL;
2515                 }
2516                 else {
2517                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2518                         nldrag->link->fromnode= NULL;
2519                         nldrag->link->fromsock= NULL;
2520                         nldrag->link->tonode= nldrag->node;
2521                         nldrag->link->tosock= nldrag->sock;
2522                 }
2523                 BLI_addtail(&snode->linkdrag, nldrag);
2524                 
2525                 /* add modal handler */
2526                 WM_event_add_modal_handler(C, op);
2527                 
2528                 return OPERATOR_RUNNING_MODAL;
2529         }
2530         else {
2531                 MEM_freeN(nldrag);
2532                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2533         }
2534 }
2535
2536 static int node_link_cancel(bContext *C, wmOperator *op)
2537 {
2538         SpaceNode *snode= CTX_wm_space_node(C);
2539         bNodeLinkDrag *nldrag= op->customdata;
2540
2541         nodeRemLink(snode->edittree, nldrag->link);
2542         BLI_remlink(&snode->linkdrag, nldrag);
2543         MEM_freeN(nldrag);
2544
2545         return OPERATOR_CANCELLED;
2546 }
2547
2548 void NODE_OT_link(wmOperatorType *ot)
2549 {
2550         /* identifiers */
2551         ot->name= "Link Nodes";
2552         ot->idname= "NODE_OT_link";
2553         
2554         /* api callbacks */
2555         ot->invoke= node_link_invoke;
2556         ot->modal= node_link_modal;
2557 //      ot->exec= node_link_exec;
2558         ot->poll= ED_operator_node_active;
2559         ot->cancel= node_link_cancel;
2560         
2561         /* flags */
2562         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2563 }
2564
2565 /* ********************** Make Link operator ***************** */
2566
2567 /* makes a link between selected output and input sockets */
2568 static int node_make_link_exec(bContext *C, wmOperator *op)
2569 {
2570         SpaceNode *snode= CTX_wm_space_node(C);
2571         int replace = RNA_boolean_get(op->ptr, "replace");
2572
2573         ED_preview_kill_jobs(C);
2574
2575         snode_autoconnect(snode, 1, replace);
2576
2577         ntreeUpdateTree(snode->edittree);
2578         snode_notify(C, snode);
2579         snode_dag_update(C, snode);
2580         
2581         return OPERATOR_FINISHED;
2582 }
2583
2584 void NODE_OT_link_make(wmOperatorType *ot)
2585 {
2586         /* identifiers */
2587         ot->name= "Make Links";
2588         ot->description= "Makes a link between selected output in input sockets";
2589         ot->idname= "NODE_OT_link_make";
2590         
2591         /* callbacks */
2592         ot->exec= node_make_link_exec;
2593         ot->poll= ED_operator_node_active; // XXX we need a special poll which checks that there are selected input/output sockets
2594         
2595         /* flags */
2596         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2597         
2598         RNA_def_boolean(ot->srna, "replace", 0, "Replace", "Replace socket connections with the new links");
2599 }
2600
2601 /* ********************** Cut Link operator ***************** */
2602
2603 #define LINK_RESOL 12
2604 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2605 {
2606         float coord_array[LINK_RESOL+1][2];
2607         int i, b;
2608         
2609         if(node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2610
2611                 for(i=0; i<tot-1; i++)
2612                         for(b=0; b<LINK_RESOL; b++)
2613                                 if(isect_line_line_v2(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2614                                         return 1;
2615         }
2616         return 0;
2617 }
2618
2619 static int cut_links_exec(bContext *C, wmOperator *op)
2620 {
2621         SpaceNode *snode= CTX_wm_space_node(C);
2622         ARegion *ar= CTX_wm_region(C);
2623         float mcoords[256][2];
2624         int i= 0;
2625         
2626         RNA_BEGIN(op->ptr, itemptr, "path") {
2627                 float loc[2];
2628                 
2629                 RNA_float_get_array(&itemptr, "loc", loc);
2630                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2631                                                                  &mcoords[i][0], &mcoords[i][1]);
2632                 i++;
2633                 if(i>= 256) break;
2634         }
2635         RNA_END;
2636         
2637         if(i>1) {
2638                 bNodeLink *link, *next;
2639
2640                 ED_preview_kill_jobs(C);
2641                 
2642                 for(link= snode->edittree->links.first; link; link= next) {
2643                         next= link->next;
2644                         
2645                         if(cut_links_intersect(link, mcoords, i)) {
2646                                 snode_tag_changed(snode, link->tonode);
2647                                 nodeRemLink(snode->edittree, link);
2648                         }
2649                 }
2650                 
2651                 ntreeUpdateTree(snode->edittree);
2652                 snode_notify(C, snode);
2653                 snode_dag_update(C, snode);
2654                 
2655                 return OPERATOR_FINISHED;
2656         }
2657         
2658         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2659 }
2660
2661 void NODE_OT_links_cut(wmOperatorType *ot)
2662 {
2663         PropertyRNA *prop;
2664         
2665         ot->name= "Cut links";
2666         ot->idname= "NODE_OT_links_cut";
2667         
2668         ot->invoke= WM_gesture_lines_invoke;
2669         ot->modal= WM_gesture_lines_modal;
2670         ot->exec= cut_links_exec;
2671         ot->cancel= WM_gesture_lines_cancel;
2672         
2673         ot->poll= ED_operator_node_active;
2674         
2675         /* flags */
2676         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2677         
2678         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2679         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2680         /* internal */
2681         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2682 }
2683
2684 /* *********************  automatic node insert on dragging ******************* */
2685
2686 /* assumes sockets in list */
2687 static bNodeSocket *socket_best_match(ListBase *sockets, int type)
2688 {
2689         bNodeSocket *sock;
2690         
2691         /* first, match type */
2692         for(sock= sockets->first; sock; sock= sock->next)
2693                 if(!(sock->flag & SOCK_HIDDEN))
2694                         if(type == sock->type)
2695                                 return sock;
2696         
2697         /* then just use first unhidden socket */
2698         for(sock= sockets->first; sock; sock= sock->next)
2699                 if(!(sock->flag & SOCK_HIDDEN))
2700                         return sock;
2701
2702         /* OK, let's unhide proper one */
2703         for(sock= sockets->first; sock; sock= sock->next) {
2704                 if(type == sock->type) {
2705                         sock->flag &= ~SOCK_HIDDEN;
2706                         return sock;
2707                 }
2708         }
2709         
2710         /* just the first */
2711         sock= sockets->first;
2712         sock->flag &= ~SOCK_HIDDEN;
2713         
2714         return sockets->first;
2715 }
2716
2717 /* prevent duplicate testing code below */
2718 static SpaceNode *ed_node_link_conditions(ScrArea *sa, bNode **select)
2719 {
2720         SpaceNode *snode= sa?sa->spacedata.first:NULL;
2721         bNode *node;
2722         bNodeLink *link;
2723         
2724         /* no unlucky accidents */
2725         if(sa==NULL || sa->spacetype!=SPACE_NODE) return NULL;
2726         
2727         *select= NULL;
2728         
2729         for(node= snode->edittree->nodes.first; node; node= node->next) {
2730                 if(node->flag & SELECT) {
2731                         if(*select)
2732                                 break;
2733                         else
2734                                 *select= node;
2735                 }
2736         }
2737         /* only one selected */
2738         if(node || *select==NULL) return NULL;
2739         
2740         /* correct node */
2741         if((*select)->inputs.first==NULL || (*select)->outputs.first==NULL) return NULL;
2742         
2743         /* test node for links */
2744         for(link= snode->edittree->links.first; link; link=link->next) {
2745                 if(link->tonode == *select || link->fromnode == *select)
2746                         return NULL;
2747         }
2748         
2749         return snode;
2750 }
2751
2752 /* assumes link with NODE_LINKFLAG_HILITE set */
2753 void ED_node_link_insert(ScrArea *sa)
2754 {
2755         bNode *node, *select;
2756         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2757         bNodeLink *link;
2758         bNodeSocket *sockto;
2759         
2760         if(snode==NULL) return;
2761         
2762         /* get the link */
2763         for(link= snode->edittree->links.first; link; link=link->next)
2764                 if(link->flag & NODE_LINKFLAG_HILITE)
2765                         break;
2766         
2767         if(link) {
2768                 node= link->tonode;
2769                 sockto= link->tosock;
2770                 
2771                 link->tonode= select;
2772                 link->tosock= socket_best_match(&select->inputs, link->fromsock->type);
2773                 link->flag &= ~NODE_LINKFLAG_HILITE;
2774                 
2775                 nodeAddLink(snode->edittree, select, socket_best_match(&select->outputs, sockto->type), node, sockto);
2776                 ntreeUpdateTree(snode->edittree);       /* needed for pointers */
2777                 snode_tag_changed(snode, select);
2778                 ED_node_changed_update(snode->id, select);
2779         }
2780 }
2781
2782
2783 /* test == 0, clear all intersect flags */
2784 void ED_node_link_intersect_test(ScrArea *sa, int test)
2785 {
2786         bNode *select;
2787         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2788         bNodeLink *link, *selink=NULL;
2789         float mcoords[6][2];
2790         
2791         if(snode==NULL) return;
2792         
2793         /* clear flags */
2794         for(link= snode->edittree->links.first; link; link=link->next)
2795                 link->flag &= ~NODE_LINKFLAG_HILITE;
2796         
2797         if(test==0) return;
2798         
2799         /* okay, there's 1 node, without links, now intersect */
2800         mcoords[0][0]= select->totr.xmin;
2801         mcoords[0][1]= select->totr.ymin;
2802         mcoords[1][0]= select->totr.xmax;
2803         mcoords[1][1]= select->totr.ymin;
2804         mcoords[2][0]= select->totr.xmax;
2805         mcoords[2][1]= select->totr.ymax;
2806         mcoords[3][0]= select->totr.xmin;
2807         mcoords[3][1]= select->totr.ymax;
2808         mcoords[4][0]= select->totr.xmin;
2809         mcoords[4][1]= select->totr.ymin;
2810         mcoords[5][0]= select->totr.xmax;
2811         mcoords[5][1]= select->totr.ymax;
2812         
2813         /* we only tag a single link for intersect now */
2814         /* idea; use header dist when more? */
2815         for(link= snode->edittree->links.first; link; link=link->next) {
2816                 
2817                 if(cut_links_intersect(link, mcoords, 5)) { /* intersect code wants edges */
2818                         if(selink) 
2819                                 break;
2820                         selink= link;
2821                 }
2822         }
2823                 
2824         if(link==NULL && selink)
2825                 selink->flag |= NODE_LINKFLAG_HILITE;
2826 }
2827
2828
2829 /* ******************************** */
2830 // XXX some code needing updating to operators...
2831
2832
2833 /* goes over all scenes, reads render layers */
2834 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
2835 {
2836         Main *bmain= CTX_data_main(C);
2837         SpaceNode *snode= CTX_wm_space_node(C);
2838         Scene *curscene= CTX_data_scene(C), *scene;
2839         bNode *node;
2840
2841         ED_preview_kill_jobs(C);
2842
2843         /* first tag scenes unread */
2844         for(scene= bmain->scene.first; scene; scene= scene->id.next) 
2845                 scene->id.flag |= LIB_DOIT;
2846
2847         for(node= snode->edittree->nodes.first; node; node= node->next) {
2848                 if(node->type==CMP_NODE_R_LAYERS) {
2849                         ID *id= node->id;
2850                         if(id->flag & LIB_DOIT) {
2851                                 RE_ReadRenderResult(curscene, (Scene *)id);
2852                                 ntreeCompositTagRender((Scene *)id);
2853                                 id->flag &= ~LIB_DOIT;
2854                         }
2855                 }
2856         }
2857         
2858         snode_notify(C, snode);
2859         snode_dag_update(C, snode);
2860
2861         return OPERATOR_FINISHED;
2862 }
2863
2864 void NODE_OT_read_renderlayers(wmOperatorType *ot)
2865 {
2866         
2867         ot->name= "Read Render Layers";
2868         ot->idname= "NODE_OT_read_renderlayers";
2869         
2870         ot->exec= node_read_renderlayers_exec;
2871         
2872         ot->poll= composite_node_active;
2873         
2874         /* flags */
2875         ot->flag= 0;
2876 }
2877
2878 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
2879 {
2880         Main *bmain= CTX_data_main(C);
2881         SpaceNode *snode= CTX_wm_space_node(C);
2882         Scene *curscene= CTX_data_scene(C);
2883         Render *re= RE_NewRender(curscene->id.name);
2884
2885         WM_cursor_wait(1);
2886
2887         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
2888         snode_notify(C, snode);
2889         snode_dag_update(C, snode);
2890         
2891         WM_cursor_wait(0);
2892         return OPERATOR_FINISHED;
2893 }
2894
2895
2896 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
2897 {
2898         
2899         ot->name= "Read Full Sample Layers";
2900         ot->idname= "NODE_OT_read_fullsamplelayers";
2901         
2902         ot->exec= node_read_fullsamplelayers_exec;
2903         
2904         ot->poll= composite_node_active;
2905         
2906         /* flags */
2907         ot->flag= 0;
2908 }
2909
2910 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
2911 {
2912         Scene *sce= CTX_data_scene(C);
2913         bNode *node;
2914         
2915         for(node= sce->nodetree->nodes.first; node; node= node->next) {
2916                 if(node->id==(ID *)sce && node->need_exec) {
2917                         break;
2918                 }
2919         }
2920         if(node) {
2921                 SceneRenderLayer *srl= BLI_findlink(&sce->r.layers, node->custom1);
2922                 
2923                 if(srl) {
2924                         PointerRNA op_ptr;
2925                         
2926                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
2927                         RNA_string_set(&op_ptr, "layer", srl->name);
2928                         RNA_string_set(&op_ptr, "scene", sce->id.name+2);
2929                         
2930                         /* to keep keypositions */
2931                         sce->r.scemode |= R_NO_FRAME_UPDATE;
2932                         
2933                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
2934
2935                         WM_operator_properties_free(&op_ptr);
2936                         
2937                         return OPERATOR_FINISHED;
2938                 }
2939                    
2940         }
2941         return OPERATOR_CANCELLED;
2942 }
2943
2944 void NODE_OT_render_changed(wmOperatorType *ot)
2945 {
2946         
2947         ot->name= "Render Changed Layer";
2948         ot->idname= "NODE_OT_render_changed";
2949         
2950         ot->exec= node_render_changed_exec;
2951         
2952         ot->poll= composite_node_active;
2953         
2954         /* flags */
2955         ot->flag= 0;
2956 }
2957
2958
2959 /* ****************** Make Group operator ******************* */
2960
2961 static int node_group_make_exec(bContext *C, wmOperator *op)
2962 {
2963         SpaceNode *snode = CTX_wm_space_node(C);
2964         bNode *gnode;
2965         
2966         if(snode->edittree!=snode->nodetree) {
2967                 BKE_report(op->reports, RPT_WARNING, "Can not add a new Group in a Group");
2968                 return OPERATOR_CANCELLED;
2969         }
2970         
2971         /* for time being... is too complex to handle */
2972         if(snode->treetype==NTREE_COMPOSIT) {
2973                 for(gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
2974                         if(gnode->flag & SELECT)
2975                                 if(gnode->type==CMP_NODE_R_LAYERS)
2976                                         break;
2977                 }
2978                 
2979                 if(gnode) {
2980                         BKE_report(op->reports, RPT_WARNING, "Can not add RenderLayer in a Group");
2981                         return OPERATOR_CANCELLED;
2982                 }
2983         }
2984
2985         ED_preview_kill_jobs(C);
2986         
2987         gnode= node_group_make_from_selected(snode->nodetree);
2988         if(gnode==NULL) {
2989                 BKE_report(op->reports, RPT_WARNING, "Can not make Group");
2990                 return OPERATOR_CANCELLED;
2991         }
2992         else {
2993                 nodeSetActive(snode->nodetree, gnode);
2994                 ntreeUpdateTree(snode->nodetree);
2995         }
2996         
2997         snode_notify(C, snode);
2998         snode_dag_update(C, snode);
2999         
3000         return OPERATOR_FINISHED;
3001 }
3002
3003 void NODE_OT_group_make(wmOperatorType *ot)
3004 {
3005         /* identifiers */
3006         ot->name = "Group";
3007         ot->description = "Make group from selected nodes";
3008         ot->idname = "NODE_OT_group_make";
3009         
3010         /* api callbacks */
3011         ot->exec = node_group_make_exec;
3012         ot->poll = ED_operator_node_active;
3013         
3014         /* flags */
3015         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
3016 }
3017
3018 /* ****************** Hide operator *********************** */
3019
3020 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
3021 {
3022         int tot_eq= 0, tot_neq= 0;
3023         bNode *node;
3024
3025         for(node= snode->edittree->nodes.first; node; node= node->next) {
3026                 if(node->flag & SELECT) {
3027
3028                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
3029                                 continue;
3030
3031                         if(node->flag & toggle_flag)
3032                                 tot_eq++;
3033                         else
3034                                 tot_neq++;
3035                 }
3036         }
3037         for(node= snode->edittree->nodes.first; node; node= node->next) {
3038                 if(node->flag & SELECT) {
3039
3040                         if(toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
3041                                 continue;
3042
3043                         if( (tot_eq && tot_neq) || tot_eq==0)
3044                                 node->flag |= toggle_flag;
3045                         else
3046                                 node->flag &= ~toggle_flag;
3047                 }
3048         }
3049 }
3050
3051 static int node_hide_exec(bContext *C, wmOperator *UNUSED(op))
3052 {
3053         SpaceNode *snode= CTX_wm_space_node(C);
3054         
3055         /* sanity checking (poll callback checks this already) */
3056         if((snode == NULL) || (snode->edittree == NULL))
3057                 return OPERATOR_CANCELLED;
3058         
3059         node_flag_toggle_exec(snode, NODE_HIDDEN);
3060         
3061         snode_notify(C, snode);
3062         
3063         return OPERATOR_FINISHED;
3064 }
3065
3066 void NODE_OT_hide_toggle(wmOperatorType *ot)
3067 {
3068         /* identifiers */
3069         ot->name= "Hide";
3070         ot->description= "Toggle hiding of selected nodes";
3071         ot->idname= "NODE_OT_hide_toggle";
3072         
3073         /* callbacks */
3074         ot->exec= node_hide_exec;
3075         ot->poll= ED_operator_node_active;
3076
3077         /* flags */
3078         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3079 }
3080
3081 static int node_preview_exec(bContext *C, wmOperator *UNUSED(op))
3082 {
3083         SpaceNode *snode= CTX_wm_space_node(C);
3084
3085         /* sanity checking (poll callback checks this already) */
3086         if((snode == NULL) || (snode->edittree == NULL))
3087                 return OPERATOR_CANCELLED;
3088
3089         ED_preview_kill_jobs(C);
3090
3091         node_flag_toggle_exec(snode, NODE_PREVIEW);
3092
3093         snode_notify(C, snode);
3094
3095         return OPERATOR_FINISHED;
3096 }
3097
3098 void NODE_OT_preview_toggle(wmOperatorType *ot)
3099 {
3100         /* identifiers */
3101         ot->name= "Toggle Node Preview";
3102         ot->description= "Toggle preview display for selected nodes";
3103         ot->idname= "NODE_OT_preview_toggle";
3104
3105         /* callbacks */
3106         ot->exec= node_preview_exec;
3107         ot->poll= ED_operator_node_active;
3108
3109         /* flags */
3110         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
3111 }
3112
3113 static int node_socket_toggle_exec(bContext *C, wmOperator *UNUSED(op))
3114 {
3115         SpaceNode *snode= CTX_wm_space_node(C);
3116         bNode *node;
3117         int hidden= 0;
3118