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