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