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