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