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