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