Second part of fix for [#31157]: Some (actually, 172) operators have no tooltip.
[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 (BKE_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 (BKE_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         ot->description = "Zoom in/out the brackground image";
1320         
1321         /* api callbacks */
1322         ot->exec = backimage_zoom;
1323         ot->poll = composite_node_active;
1324         
1325         /* flags */
1326         ot->flag = OPTYPE_BLOCKING;
1327
1328         /* internal */
1329         RNA_def_float(ot->srna, "factor", 1.2f, 0.0f, 10.0f, "Factor", "", 0.0f, 10.0f);
1330 }
1331
1332 /******************** sample backdrop operator ********************/
1333
1334 typedef struct ImageSampleInfo {
1335         ARegionType *art;
1336         void *draw_handle;
1337         int x, y;
1338         int channels;
1339         int color_manage;
1340
1341         unsigned char col[4];
1342         float colf[4];
1343
1344         int draw;
1345 } ImageSampleInfo;
1346
1347 static void sample_draw(const bContext *C, ARegion *ar, void *arg_info)
1348 {
1349         Scene *scene = CTX_data_scene(C);
1350         ImageSampleInfo *info= arg_info;
1351
1352         ED_image_draw_info(ar, (scene->r.color_mgt_flag & R_COLOR_MANAGEMENT), info->channels,
1353                            info->x, info->y, info->col, info->colf,
1354                            NULL, NULL /* zbuf - unused for nodes */
1355                            );
1356 }
1357
1358 static void sample_apply(bContext *C, wmOperator *op, wmEvent *event)
1359 {
1360         SpaceNode *snode= CTX_wm_space_node(C);
1361         ARegion *ar= CTX_wm_region(C);
1362         ImageSampleInfo *info= op->customdata;
1363         void *lock;
1364         Image *ima;
1365         ImBuf *ibuf;
1366         float fx, fy, bufx, bufy;
1367         
1368         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1369         ibuf= BKE_image_acquire_ibuf(ima, NULL, &lock);
1370         if (!ibuf)
1371                 return;
1372         
1373         if (!ibuf->rect) {
1374                 if (info->color_manage)
1375                         ibuf->profile = IB_PROFILE_LINEAR_RGB;
1376                 else
1377                         ibuf->profile = IB_PROFILE_NONE;
1378                 IMB_rect_from_float(ibuf);
1379         }
1380
1381         /* map the mouse coords to the backdrop image space */
1382         bufx = ibuf->x * snode->zoom;
1383         bufy = ibuf->y * snode->zoom;
1384         fx = (bufx > 0.0f ? ((float)event->mval[0] - 0.5f*ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
1385         fy = (bufy > 0.0f ? ((float)event->mval[1] - 0.5f*ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
1386
1387         if (fx>=0.0f && fy>=0.0f && fx<1.0f && fy<1.0f) {
1388                 float *fp;
1389                 char *cp;
1390                 int x= (int)(fx*ibuf->x), y= (int)(fy*ibuf->y);
1391
1392                 CLAMP(x, 0, ibuf->x-1);
1393                 CLAMP(y, 0, ibuf->y-1);
1394
1395                 info->x= x;
1396                 info->y= y;
1397                 info->draw= 1;
1398                 info->channels= ibuf->channels;
1399
1400                 if (ibuf->rect) {
1401                         cp= (char *)(ibuf->rect + y*ibuf->x + x);
1402
1403                         info->col[0]= cp[0];
1404                         info->col[1]= cp[1];
1405                         info->col[2]= cp[2];
1406                         info->col[3]= cp[3];
1407
1408                         info->colf[0]= (float)cp[0]/255.0f;
1409                         info->colf[1]= (float)cp[1]/255.0f;
1410                         info->colf[2]= (float)cp[2]/255.0f;
1411                         info->colf[3]= (float)cp[3]/255.0f;
1412                 }
1413                 if (ibuf->rect_float) {
1414                         fp= (ibuf->rect_float + (ibuf->channels)*(y*ibuf->x + x));
1415
1416                         info->colf[0]= fp[0];
1417                         info->colf[1]= fp[1];
1418                         info->colf[2]= fp[2];
1419                         info->colf[3]= fp[3];
1420                 }
1421         }
1422         else
1423                 info->draw= 0;
1424
1425         BKE_image_release_ibuf(ima, lock);
1426         
1427         ED_area_tag_redraw(CTX_wm_area(C));
1428 }
1429
1430 static void sample_exit(bContext *C, wmOperator *op)
1431 {
1432         ImageSampleInfo *info= op->customdata;
1433
1434         ED_region_draw_cb_exit(info->art, info->draw_handle);
1435         ED_area_tag_redraw(CTX_wm_area(C));
1436         MEM_freeN(info);
1437 }
1438
1439 static int sample_invoke(bContext *C, wmOperator *op, wmEvent *event)
1440 {
1441         SpaceNode *snode= CTX_wm_space_node(C);
1442         ARegion *ar= CTX_wm_region(C);
1443         ImageSampleInfo *info;
1444
1445         if (snode->treetype!=NTREE_COMPOSIT || !(snode->flag & SNODE_BACKDRAW))
1446                 return OPERATOR_CANCELLED;
1447         
1448         info= MEM_callocN(sizeof(ImageSampleInfo), "ImageSampleInfo");
1449         info->art= ar->type;
1450         info->draw_handle = ED_region_draw_cb_activate(ar->type, sample_draw, info, REGION_DRAW_POST_PIXEL);
1451         op->customdata= info;
1452
1453         sample_apply(C, op, event);
1454
1455         WM_event_add_modal_handler(C, op);
1456
1457         return OPERATOR_RUNNING_MODAL;
1458 }
1459
1460 static int sample_modal(bContext *C, wmOperator *op, wmEvent *event)
1461 {
1462         switch (event->type) {
1463                 case LEFTMOUSE:
1464                 case RIGHTMOUSE: // XXX hardcoded
1465                         sample_exit(C, op);
1466                         return OPERATOR_CANCELLED;
1467                 case MOUSEMOVE:
1468                         sample_apply(C, op, event);
1469                         break;
1470         }
1471
1472         return OPERATOR_RUNNING_MODAL;
1473 }
1474
1475 static int sample_cancel(bContext *C, wmOperator *op)
1476 {
1477         sample_exit(C, op);
1478         return OPERATOR_CANCELLED;
1479 }
1480
1481 void NODE_OT_backimage_sample(wmOperatorType *ot)
1482 {
1483         /* identifiers */
1484         ot->name = "Backimage Sample";
1485         ot->idname = "NODE_OT_backimage_sample";
1486         ot->description = "Use mouse to sample background image";
1487         
1488         /* api callbacks */
1489         ot->invoke = sample_invoke;
1490         ot->modal = sample_modal;
1491         ot->cancel = sample_cancel;
1492         ot->poll = ED_operator_node_active;
1493
1494         /* flags */
1495         ot->flag = OPTYPE_BLOCKING;
1496 }
1497
1498 /* ********************** size widget operator ******************** */
1499
1500 typedef struct NodeSizeWidget {
1501         float mxstart, mystart;
1502         float oldwidth, oldheight;
1503         float oldminiwidth;
1504 } NodeSizeWidget;
1505
1506 static int node_resize_modal(bContext *C, wmOperator *op, wmEvent *event)
1507 {
1508         SpaceNode *snode= CTX_wm_space_node(C);
1509         ARegion *ar= CTX_wm_region(C);
1510         bNode *node= editnode_get_active(snode->edittree);
1511         NodeSizeWidget *nsw= op->customdata;
1512         float mx, my;
1513         
1514         switch (event->type) {
1515                 case MOUSEMOVE:
1516                         
1517                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1518                                                                          &mx, &my);
1519                         
1520                         if (node) {
1521                                 if (node->flag & NODE_HIDDEN) {
1522                                         node->miniwidth= nsw->oldminiwidth + mx - nsw->mxstart;
1523                                         CLAMP(node->miniwidth, 0.0f, 100.0f);
1524                                 }
1525                                 else {
1526                                         node->width= nsw->oldwidth + mx - nsw->mxstart;
1527                                         CLAMP(node->width, UI_DPI_FAC*node->typeinfo->minwidth, UI_DPI_FAC*node->typeinfo->maxwidth);
1528                                 }
1529                                 /* height works the other way round ... */
1530                                 node->height= nsw->oldheight - my + nsw->mystart;
1531                                 CLAMP(node->height, node->typeinfo->minheight, node->typeinfo->maxheight);
1532                         }
1533                                 
1534                         ED_region_tag_redraw(ar);
1535
1536                         break;
1537                         
1538                 case LEFTMOUSE:
1539                 case MIDDLEMOUSE:
1540                 case RIGHTMOUSE:
1541                         
1542                         MEM_freeN(nsw);
1543                         op->customdata= NULL;
1544                         
1545                         ED_node_update_hierarchy(C, snode->edittree);
1546                         
1547                         return OPERATOR_FINISHED;
1548         }
1549         
1550         return OPERATOR_RUNNING_MODAL;
1551 }
1552
1553 static int node_resize_invoke(bContext *C, wmOperator *op, wmEvent *event)
1554 {
1555         SpaceNode *snode= CTX_wm_space_node(C);
1556         ARegion *ar= CTX_wm_region(C);
1557         bNode *node= editnode_get_active(snode->edittree);
1558         
1559         if (node) {
1560                 /* convert mouse coordinates to v2d space */
1561                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
1562                                                                  &snode->mx, &snode->my);
1563                 
1564                 if (node->typeinfo->resize_area_func(node, snode->mx, snode->my)) {
1565                         NodeSizeWidget *nsw= MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
1566                         
1567                         op->customdata= nsw;
1568                         nsw->mxstart= snode->mx;
1569                         nsw->mystart= snode->my;
1570                         
1571                         /* store old */
1572                         nsw->oldwidth= node->width;
1573                         nsw->oldheight= node->height;
1574                         nsw->oldminiwidth= node->miniwidth;
1575                         
1576                         /* add modal handler */
1577                         WM_event_add_modal_handler(C, op);
1578
1579                         return OPERATOR_RUNNING_MODAL;
1580                 }
1581         }
1582         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
1583 }
1584
1585 static int node_resize_cancel(bContext *UNUSED(C), wmOperator *op)
1586 {
1587         MEM_freeN(op->customdata);
1588         op->customdata= NULL;
1589
1590         return OPERATOR_CANCELLED;
1591 }
1592
1593 void NODE_OT_resize(wmOperatorType *ot)
1594 {
1595         /* identifiers */
1596         ot->name = "Resize Node";
1597         ot->idname = "NODE_OT_resize";
1598         ot->description = "Resize a node";
1599         
1600         /* api callbacks */
1601         ot->invoke = node_resize_invoke;
1602         ot->modal = node_resize_modal;
1603         ot->poll = ED_operator_node_active;
1604         ot->cancel = node_resize_cancel;
1605         
1606         /* flags */
1607         ot->flag = OPTYPE_BLOCKING;
1608 }
1609
1610
1611 /* ********************** hidden sockets ******************** */
1612
1613 int node_has_hidden_sockets(bNode *node)
1614 {
1615         bNodeSocket *sock;
1616         
1617         for (sock= node->inputs.first; sock; sock= sock->next)
1618                 if (sock->flag & SOCK_HIDDEN)
1619                         return 1;
1620         for (sock= node->outputs.first; sock; sock= sock->next)
1621                 if (sock->flag & SOCK_HIDDEN)
1622                         return 1;
1623         return 0;
1624 }
1625
1626 void node_set_hidden_sockets(SpaceNode *snode, bNode *node, int set)
1627 {       
1628         bNodeSocket *sock;
1629
1630         if (set==0) {
1631                 for (sock= node->inputs.first; sock; sock= sock->next)
1632                         sock->flag &= ~SOCK_HIDDEN;
1633                 for (sock= node->outputs.first; sock; sock= sock->next)
1634                         sock->flag &= ~SOCK_HIDDEN;
1635         }
1636         else {
1637                 /* hide unused sockets */
1638                 for (sock= node->inputs.first; sock; sock= sock->next) {
1639                         if (sock->link==NULL)
1640                                 sock->flag |= SOCK_HIDDEN;
1641                 }
1642                 for (sock= node->outputs.first; sock; sock= sock->next) {
1643                         if (nodeCountSocketLinks(snode->edittree, sock)==0)
1644                                 sock->flag |= SOCK_HIDDEN;
1645                 }
1646         }
1647 }
1648
1649 static int node_link_viewer(const bContext *C, bNode *tonode)
1650 {
1651         SpaceNode *snode = CTX_wm_space_node(C);
1652         bNode *node;
1653         bNodeLink *link;
1654         bNodeSocket *sock;
1655
1656         /* context check */
1657         if (tonode==NULL || tonode->outputs.first==NULL)
1658                 return OPERATOR_CANCELLED;
1659         if ( ELEM(tonode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
1660                 return OPERATOR_CANCELLED;
1661         
1662         /* get viewer */
1663         for (node= snode->edittree->nodes.first; node; node= node->next)
1664                 if ( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
1665                         if (node->flag & NODE_DO_OUTPUT)
1666                                 break;
1667         /* no viewer, we make one active */
1668         if (node==NULL) {
1669                 for (node= snode->edittree->nodes.first; node; node= node->next) {
1670                         if ( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
1671                                 node->flag |= NODE_DO_OUTPUT;
1672                                 break;
1673                         }
1674                 }
1675         }
1676         
1677         sock = NULL;
1678         
1679         /* try to find an already connected socket to cycle to the next */
1680         if (node) {
1681                 link = NULL;
1682                 for (link= snode->edittree->links.first; link; link= link->next)
1683                         if (link->tonode==node && link->fromnode==tonode)
1684                                 if (link->tosock==node->inputs.first)
1685                                         break;
1686                 if (link) {
1687                         /* unlink existing connection */
1688                         sock= link->fromsock;
1689                         nodeRemLink(snode->edittree, link);
1690                         
1691                         /* find a socket after the previously connected socket */
1692                         for (sock=sock->next; sock; sock= sock->next)
1693                                 if (!nodeSocketIsHidden(sock))
1694                                         break;
1695                 }
1696         }
1697         
1698         /* find a socket starting from the first socket */
1699         if (!sock) {
1700                 for (sock= tonode->outputs.first; sock; sock= sock->next)
1701                         if (!nodeSocketIsHidden(sock))
1702                                 break;
1703         }
1704         
1705         if (sock) {
1706                 /* add a new viewer if none exists yet */
1707                 if (!node) {
1708                         Main *bmain = CTX_data_main(C);
1709                         Scene *scene = CTX_data_scene(C);
1710                         bNodeTemplate ntemp;
1711                         
1712                         ntemp.type = CMP_NODE_VIEWER;
1713                         /* XXX location is a quick hack, just place it next to the linked socket */
1714                         node = node_add_node(snode, bmain, scene, &ntemp, sock->locx + 100, sock->locy);
1715                         if (!node)
1716                                 return OPERATOR_CANCELLED;
1717                         
1718                         link = NULL;
1719                 }
1720                 else {
1721                         /* get link to viewer */
1722                         for (link= snode->edittree->links.first; link; link= link->next)
1723                                 if (link->tonode==node && link->tosock==node->inputs.first)
1724                                         break;
1725                 }
1726                 
1727                 if (link==NULL) {
1728                         nodeAddLink(snode->edittree, tonode, sock, node, node->inputs.first);
1729                 }
1730                 else {
1731                         link->fromnode= tonode;
1732                         link->fromsock= sock;
1733                 }
1734                 ntreeUpdateTree(snode->edittree);
1735                 snode_update(snode, node);
1736         }
1737         
1738         return OPERATOR_FINISHED;
1739 }
1740
1741
1742 static int node_active_link_viewer(bContext *C, wmOperator *UNUSED(op))
1743 {
1744         SpaceNode *snode= CTX_wm_space_node(C);
1745         bNode *node;
1746         
1747         node= editnode_get_active(snode->edittree);
1748         
1749         if (!node)
1750                 return OPERATOR_CANCELLED;
1751
1752         ED_preview_kill_jobs(C);
1753
1754         if (node_link_viewer(C, node) == OPERATOR_CANCELLED)
1755                 return OPERATOR_CANCELLED;
1756
1757         snode_notify(C, snode);
1758
1759         return OPERATOR_FINISHED;
1760 }
1761
1762
1763
1764 void NODE_OT_link_viewer(wmOperatorType *ot)
1765 {
1766         /* identifiers */
1767         ot->name = "Link to Viewer Node";
1768         ot->description = "Link to viewer node";
1769         ot->idname = "NODE_OT_link_viewer";
1770         
1771         /* api callbacks */
1772         ot->exec = node_active_link_viewer;
1773         ot->poll = composite_node_active;
1774         
1775         /* flags */
1776         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
1777 }
1778
1779
1780
1781 /* return 0, nothing done */
1782 static int UNUSED_FUNCTION(node_mouse_groupheader)(SpaceNode *snode)
1783 {
1784         bNode *gnode;
1785         float mx=0, my=0;
1786 // XXX  int mval[2];
1787         
1788         gnode= node_tree_get_editgroup(snode->nodetree);
1789         if (gnode==NULL) return 0;
1790         
1791 // XXX  getmouseco_areawin(mval);
1792 // XXX  areamouseco_to_ipoco(G.v2d, mval, &mx, &my);
1793         
1794         /* click in header or outside? */
1795         if (BLI_in_rctf(&gnode->totr, mx, my)==0) {
1796                 rctf rect= gnode->totr;
1797                 
1798                 rect.ymax += NODE_DY;
1799                 if (BLI_in_rctf(&rect, mx, my)==0)
1800                         snode_make_group_editable(snode, NULL); /* toggles, so exits editmode */
1801 //              else
1802 // XXX                  transform_nodes(snode->nodetree, 'g', "Move group");
1803                 
1804                 return 1;
1805         }
1806         return 0;
1807 }
1808
1809 /* checks snode->mouse position, and returns found node/socket */
1810 /* type is SOCK_IN and/or SOCK_OUT */
1811 int node_find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1812 {
1813         bNode *node;
1814         bNodeSocket *sock;
1815         rctf rect;
1816         
1817         *nodep= NULL;
1818         *sockp= NULL;
1819         
1820         /* check if we click in a socket */
1821         for (node= snode->edittree->nodes.first; node; node= node->next) {
1822                 
1823                 rect.xmin = snode->mx - (NODE_SOCKSIZE+4);
1824                 rect.ymin = snode->my - (NODE_SOCKSIZE+4);
1825                 rect.xmax = snode->mx + (NODE_SOCKSIZE+4);
1826                 rect.ymax = snode->my + (NODE_SOCKSIZE+4);
1827                 
1828                 if (!(node->flag & NODE_HIDDEN)) {
1829                         /* extra padding inside and out - allow dragging on the text areas too */
1830                         if (in_out == SOCK_IN) {
1831                                 rect.xmax += NODE_SOCKSIZE;
1832                                 rect.xmin -= NODE_SOCKSIZE*4;
1833                         }
1834                         else if (in_out == SOCK_OUT) {
1835                                 rect.xmax += NODE_SOCKSIZE*4;
1836                                 rect.xmin -= NODE_SOCKSIZE;
1837                         }
1838                 }
1839                 
1840                 if (in_out & SOCK_IN) {
1841                         for (sock= node->inputs.first; sock; sock= sock->next) {
1842                                 if (!nodeSocketIsHidden(sock)) {
1843                                         if (BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1844                                                 if (node == visible_node(snode, &rect)) {
1845                                                         *nodep= node;
1846                                                         *sockp= sock;
1847                                                         return 1;
1848                                                 }
1849                                         }
1850                                 }
1851                         }
1852                 }
1853                 if (in_out & SOCK_OUT) {
1854                         for (sock= node->outputs.first; sock; sock= sock->next) {
1855                                 if (!nodeSocketIsHidden(sock)) {
1856                                         if (BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1857                                                 if (node == visible_node(snode, &rect)) {
1858                                                         *nodep= node;
1859                                                         *sockp= sock;
1860                                                         return 1;
1861                                                 }
1862                                         }
1863                                 }
1864                         }
1865                 }
1866         }
1867         
1868         /* check group sockets
1869          * NB: using ngroup->outputs as input sockets and vice versa here!
1870          */
1871         if (in_out & SOCK_IN) {
1872                 for (sock= snode->edittree->outputs.first; sock; sock= sock->next) {
1873                         if (!nodeSocketIsHidden(sock)) {
1874                                 if (BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1875                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1876                                         *sockp= sock;
1877                                         return 1;
1878                                 }
1879                         }
1880                 }
1881         }
1882         if (in_out & SOCK_OUT) {
1883                 for (sock= snode->edittree->inputs.first; sock; sock= sock->next) {
1884                         if (!nodeSocketIsHidden(sock)) {
1885                                 if (BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1886                                         *nodep= NULL;   /* NULL node pointer indicates group socket */
1887                                         *sockp= sock;
1888                                         return 1;
1889                                 }
1890                         }
1891                 }
1892         }
1893         
1894         return 0;
1895 }
1896
1897 static int outside_group_rect(SpaceNode *snode)
1898 {
1899         bNode *gnode= node_tree_get_editgroup(snode->nodetree);
1900         if (gnode) {
1901                 return (snode->mx <  gnode->totr.xmin ||
1902                         snode->mx >= gnode->totr.xmax ||
1903                         snode->my <  gnode->totr.ymin ||
1904                         snode->my >= gnode->totr.ymax);
1905         }
1906         return 0;
1907 }
1908
1909 /* ****************** Add *********************** */
1910
1911
1912 typedef struct bNodeListItem {
1913         struct bNodeListItem *next, *prev;
1914         struct bNode *node;     
1915 } bNodeListItem;
1916
1917 static int sort_nodes_locx(void *a, void *b)
1918 {
1919         bNodeListItem *nli1 = (bNodeListItem *)a;
1920         bNodeListItem *nli2 = (bNodeListItem *)b;
1921         bNode *node1 = nli1->node;
1922         bNode *node2 = nli2->node;
1923         
1924         if (node1->locx > node2->locx)
1925                 return 1;
1926         else 
1927                 return 0;
1928 }
1929
1930 static int socket_is_available(bNodeTree *UNUSED(ntree), bNodeSocket *sock, int allow_used)
1931 {
1932         if (nodeSocketIsHidden(sock))
1933                 return 0;
1934         
1935         if (!allow_used && (sock->flag & SOCK_IN_USE))
1936                 return 0;
1937         
1938         return 1;
1939 }
1940
1941 static bNodeSocket *best_socket_output(bNodeTree *ntree, bNode *node, bNodeSocket *sock_target, int allow_multiple)
1942 {
1943         bNodeSocket *sock;
1944         
1945         /* first look for selected output */
1946         for (sock=node->outputs.first; sock; sock=sock->next) {
1947                 if (!socket_is_available(ntree, sock, allow_multiple))
1948                         continue;
1949                 
1950                 if (sock->flag & SELECT)
1951                         return sock;
1952         }
1953         
1954         /* try to find a socket with a matching name */
1955         for (sock=node->outputs.first; sock; sock=sock->next) {
1956                 if (!socket_is_available(ntree, sock, allow_multiple))
1957                         continue;
1958
1959                 /* check for same types */
1960                 if (sock->type == sock_target->type) {
1961                         if (strcmp(sock->name, sock_target->name)==0)
1962                                 return sock;
1963                 }
1964         }
1965         
1966         /* otherwise settle for the first available socket of the right type */
1967         for (sock=node->outputs.first; sock; sock=sock->next) {
1968
1969                 if (!socket_is_available(ntree, sock, allow_multiple))
1970                         continue;
1971                 
1972                 /* check for same types */
1973                 if (sock->type == sock_target->type) {
1974                         return sock;
1975                 }
1976         }
1977         
1978         return NULL;
1979 }
1980
1981 /* this is a bit complicated, but designed to prioritize finding
1982  * sockets of higher types, such as image, first */
1983 static bNodeSocket *best_socket_input(bNodeTree *ntree, bNode *node, int num, int replace)
1984 {
1985         bNodeSocket *sock;
1986         int socktype, maxtype=0;
1987         int a = 0;
1988         
1989         for (sock=node->inputs.first; sock; sock=sock->next) {
1990                 maxtype = MAX2(sock->type, maxtype);
1991         }
1992         
1993         /* find sockets of higher 'types' first (i.e. image) */
1994         for (socktype=maxtype; socktype >= 0; socktype--) {
1995                 for (sock=node->inputs.first; sock; sock=sock->next) {
1996                         
1997                         if (!socket_is_available(ntree, sock, replace)) {
1998                                 a++;
1999                                 continue;
2000                         }
2001                                 
2002                         if (sock->type == socktype) {
2003                                 /* increment to make sure we don't keep finding 
2004                                  * the same socket on every attempt running this function */
2005                                 a++;
2006                                 if (a > num)
2007                                         return sock;
2008                         }
2009                 }
2010         }
2011         
2012         return NULL;
2013 }
2014
2015 static int snode_autoconnect_input(SpaceNode *snode, bNode *node_fr, bNodeSocket *sock_fr, bNode *node_to, bNodeSocket *sock_to, int replace)
2016 {
2017         bNodeTree *ntree = snode->edittree;
2018         bNodeLink *link;
2019         
2020         /* then we can connect */
2021         if (replace)
2022                 nodeRemSocketLinks(ntree, sock_to);
2023         
2024         link = nodeAddLink(ntree, node_fr, sock_fr, node_to, sock_to);
2025         /* validate the new link */
2026         ntreeUpdateTree(ntree);
2027         if (!(link->flag & NODE_LINK_VALID)) {
2028                 nodeRemLink(ntree, link);
2029                 return 0;
2030         }
2031         
2032         snode_update(snode, node_to);
2033         return 1;
2034 }
2035
2036 void snode_autoconnect(SpaceNode *snode, int allow_multiple, int replace)
2037 {
2038         bNodeTree *ntree = snode->edittree;
2039         ListBase *nodelist = MEM_callocN(sizeof(ListBase), "items_list");
2040         bNodeListItem *nli;
2041         bNode *node;
2042         int i, numlinks=0;
2043         
2044         for (node= ntree->nodes.first; node; node= node->next) {
2045                 if (node->flag & NODE_SELECT) {
2046                         nli = MEM_mallocN(sizeof(bNodeListItem), "temporary node list item");
2047                         nli->node = node;
2048                         BLI_addtail(nodelist, nli);
2049                 }
2050         }
2051         
2052         /* sort nodes left to right */
2053         BLI_sortlist(nodelist, sort_nodes_locx);
2054         
2055         for (nli=nodelist->first; nli; nli=nli->next) {
2056                 bNode *node_fr, *node_to;
2057                 bNodeSocket *sock_fr, *sock_to;
2058                 int has_selected_inputs = 0;
2059                 
2060                 if (nli->next == NULL) break;
2061                 
2062                 node_fr = nli->node;
2063                 node_to = nli->next->node;
2064                 
2065                 /* if there are selected sockets, connect those */
2066                 for (sock_to = node_to->inputs.first; sock_to; sock_to=sock_to->next) {
2067                         if (sock_to->flag & SELECT) {
2068                                 has_selected_inputs = 1;
2069                                 
2070                                 if (!socket_is_available(ntree, sock_to, replace))
2071                                         continue;
2072                                 
2073                                 /* check for an appropriate output socket to connect from */
2074                                 sock_fr = best_socket_output(ntree, node_fr, sock_to, allow_multiple);
2075                                 if (!sock_fr)
2076                                         continue;
2077         
2078                                 if (snode_autoconnect_input(snode, node_fr, sock_fr, node_to, sock_to, replace))
2079                                         ++numlinks;
2080                         }
2081                 }
2082                 
2083                 if (!has_selected_inputs) {
2084                         /* no selected inputs, connect by finding suitable match */
2085                         int num_inputs = BLI_countlist(&node_to->inputs);
2086                         
2087                         for (i=0; i<num_inputs; i++) {
2088                                 
2089                                 /* find the best guess input socket */
2090                                 sock_to = best_socket_input(ntree, node_to, i, replace);
2091                                 if (!sock_to)
2092                                         continue;
2093                                 
2094                                 /* check for an appropriate output socket to connect from */
2095                                 sock_fr = best_socket_output(ntree, node_fr, sock_to, allow_multiple);
2096                                 if (!sock_fr)
2097                                         continue;
2098         
2099                                 if (snode_autoconnect_input(snode, node_fr, sock_fr, node_to, sock_to, replace)) {
2100                                         ++numlinks;
2101                                         break;
2102                                 }
2103                         }
2104                 }
2105         }
2106         
2107         if (numlinks > 0) {
2108                 ntreeUpdateTree(ntree);
2109         }
2110         
2111         BLI_freelistN(nodelist);
2112         MEM_freeN(nodelist);
2113 }
2114
2115 /* can be called from menus too, but they should do own undopush and redraws */
2116 bNode *node_add_node(SpaceNode *snode, Main *bmain, Scene *scene, bNodeTemplate *ntemp, float locx, float locy)
2117 {
2118         bNode *node= NULL, *gnode;
2119         
2120         node_deselect_all(snode);
2121         
2122         node = nodeAddNode(snode->edittree, ntemp);
2123         
2124         /* generics */
2125         if (node) {
2126                 node->locx= locx;
2127                 node->locy= locy + 60.0f;               // arbitrary.. so its visible, (0,0) is top of node
2128                 node_select(node);
2129                 
2130                 gnode= node_tree_get_editgroup(snode->nodetree);
2131                 if (gnode) {
2132                         node->locx -= gnode->locx;
2133                         node->locy -= gnode->locy;
2134                 }
2135
2136                 ntreeUpdateTree(snode->edittree);
2137                 ED_node_set_active(bmain, snode->edittree, node);
2138                 
2139                 if (snode->nodetree->type==NTREE_COMPOSIT) {
2140                         if (ELEM4(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE, CMP_NODE_DEFOCUS, CMP_NODE_OUTPUT_FILE)) {
2141                                 node->id = &scene->id;
2142                         }
2143                         else if (ELEM3(node->type, CMP_NODE_MOVIECLIP, CMP_NODE_MOVIEDISTORTION, CMP_NODE_STABILIZE2D)) {
2144                                 node->id = (ID *)scene->clip;
2145                         }
2146                         
2147                         ntreeCompositForceHidden(snode->edittree, scene);
2148                 }
2149                         
2150                 if (node->id)
2151                         id_us_plus(node->id);
2152                         
2153                 snode_update(snode, node);
2154         }
2155         
2156         if (snode->nodetree->type==NTREE_TEXTURE) {
2157                 ntreeTexCheckCyclics(snode->edittree);
2158         }
2159         
2160         return node;
2161 }
2162
2163 /* ****************** Duplicate *********************** */
2164
2165 static int node_duplicate_exec(bContext *C, wmOperator *op)
2166 {
2167         SpaceNode *snode= CTX_wm_space_node(C);
2168         bNodeTree *ntree= snode->edittree;
2169         bNode *node, *newnode, *lastnode;
2170         bNodeLink *link, *newlink, *lastlink;
2171         int keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
2172         
2173         ED_preview_kill_jobs(C);
2174         
2175         lastnode = ntree->nodes.last;
2176         for (node= ntree->nodes.first; node; node= node->next) {
2177                 if (node->flag & SELECT) {
2178                         newnode = nodeCopyNode(ntree, node);
2179                         
2180                         if (newnode->id) {
2181                                 /* simple id user adjustment, node internal functions don't touch this
2182                                  * but operators and readfile.c do. */
2183                                 id_us_plus(newnode->id);
2184                                 /* to ensure redraws or rerenders happen */
2185                                 ED_node_changed_update(snode->id, newnode);
2186                         }
2187                 }
2188                 
2189                 /* make sure we don't copy new nodes again! */
2190                 if (node==lastnode)
2191                         break;
2192         }
2193         
2194         /* copy links between selected nodes
2195          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
2196          */
2197         lastlink = ntree->links.last;
2198         for (link=ntree->links.first; link; link=link->next) {
2199                 /* This creates new links between copied nodes.
2200                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
2201                  */
2202                 if (link->tonode && (link->tonode->flag & NODE_SELECT) &&
2203                     (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT))))
2204                 {
2205                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
2206                         newlink->flag = link->flag;
2207                         newlink->tonode = link->tonode->new_node;
2208                         newlink->tosock = link->tosock->new_sock;
2209                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
2210                                 newlink->fromnode = link->fromnode->new_node;
2211                                 newlink->fromsock = link->fromsock->new_sock;
2212                         }
2213                         else {
2214                                 /* input node not copied, this keeps the original input linked */
2215                                 newlink->fromnode = link->fromnode;
2216                                 newlink->fromsock = link->fromsock;
2217                         }
2218                         
2219                         BLI_addtail(&ntree->links, newlink);
2220                 }
2221                 
2222                 /* make sure we don't copy new links again! */
2223                 if (link==lastlink)
2224                         break;
2225         }
2226         
2227         /* deselect old nodes, select the copies instead */
2228         for (node= ntree->nodes.first; node; node= node->next) {
2229                 if (node->flag & SELECT) {
2230                         /* has been set during copy above */
2231                         newnode = node->new_node;
2232                         
2233                         node_deselect(node);
2234                         node->flag &= ~NODE_ACTIVE;
2235                         node_select(newnode);
2236                 }
2237                 
2238                 /* make sure we don't copy new nodes again! */
2239                 if (node==lastnode)
2240                         break;
2241         }
2242         
2243         ntreeUpdateTree(snode->edittree);
2244         
2245         snode_notify(C, snode);
2246         snode_dag_update(C, snode);
2247
2248         return OPERATOR_FINISHED;
2249 }
2250
2251 void NODE_OT_duplicate(wmOperatorType *ot)
2252 {
2253         /* identifiers */
2254         ot->name = "Duplicate Nodes";
2255         ot->description = "Duplicate selected nodes";
2256         ot->idname = "NODE_OT_duplicate";
2257         
2258         /* api callbacks */
2259         ot->exec = node_duplicate_exec;
2260         ot->poll = ED_operator_node_active;
2261         
2262         /* flags */
2263         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2264         
2265         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
2266 }
2267
2268 /* *************************** add link op ******************** */
2269
2270 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
2271 {
2272         bNodeLink *tlink;
2273         bNodeSocket *sock;
2274         
2275         if (tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
2276                 
2277                 for (tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
2278                         if (link!=tlink && tlink->tosock==link->tosock)
2279                                 break;
2280                 }
2281                 if (tlink) {
2282                         /* try to move the existing link to the next available socket */
2283                         if (tlink->tonode) {
2284                                 /* is there a free input socket with the target type? */
2285                                 for (sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
2286                                         if (sock->type==tlink->tosock->type)
2287                                                 if (nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
2288                                                         break;
2289                                 }
2290                                 if (sock) {
2291                                         tlink->tosock= sock;
2292                                         sock->flag &= ~SOCK_HIDDEN;
2293                                 }
2294                                 else {
2295                                         nodeRemLink(snode->edittree, tlink);
2296                                 }
2297                         }
2298                         else
2299                                 nodeRemLink(snode->edittree, tlink);
2300                         
2301                         snode->edittree->update |= NTREE_UPDATE_LINKS;
2302                 }
2303         }
2304 }
2305
2306 /* loop that adds a nodelink, called by function below  */
2307 /* in_out = starting socket */
2308 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
2309 {
2310         SpaceNode *snode= CTX_wm_space_node(C);
2311         ARegion *ar= CTX_wm_region(C);
2312         bNodeLinkDrag *nldrag= op->customdata;
2313         bNode *tnode, *node;
2314         bNodeSocket *tsock= NULL, *sock;
2315         bNodeLink *link;
2316         int in_out;
2317
2318         in_out= nldrag->in_out;
2319         node= nldrag->node;
2320         sock= nldrag->sock;
2321         link= nldrag->link;
2322         
2323         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2324                                                          &snode->mx, &snode->my);
2325
2326         switch (event->type) {
2327                 case MOUSEMOVE:
2328                         
2329                         if (in_out==SOCK_OUT) {
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                                 else {
2345                                         if (link->tonode || link->tosock) {
2346                                                 BLI_remlink(&snode->edittree->links, link);
2347                                                 link->prev = link->next = NULL;
2348                                                 link->tonode= NULL;
2349                                                 link->tosock= NULL;
2350                                                 
2351                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2352                                                 ntreeUpdateTree(snode->edittree);
2353                                         }
2354                                 }
2355                         }
2356                         else {
2357                                 if (node_find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
2358                                         if (nodeFindLink(snode->edittree, sock, tsock)==NULL) {
2359                                                 if (nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
2360                                                         if ( link->fromsock!= tsock && (!tnode || (tnode!=node && link->fromnode!=tnode)) ) {
2361                                                                 link->fromnode= tnode;
2362                                                                 link->fromsock= tsock;
2363                                                                 if (link->prev==NULL && link->next==NULL) {
2364                                                                         BLI_addtail(&snode->edittree->links, link);
2365                                                                 }
2366                                                                 
2367                                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2368                                                                 ntreeUpdateTree(snode->edittree);
2369                                                         }
2370                                                 }
2371                                         }
2372                                 }
2373                                 else {
2374                                         if (link->tonode || link->tosock) {
2375                                                 BLI_remlink(&snode->edittree->links, link);
2376                                                 link->prev = link->next = NULL;
2377                                                 link->fromnode= NULL;
2378                                                 link->fromsock= NULL;
2379                                                 snode->edittree->update |= NTREE_UPDATE_LINKS;
2380                                                 ntreeUpdateTree(snode->edittree);
2381                                         }
2382                                 }
2383                         }
2384                         
2385                         ED_region_tag_redraw(ar);
2386                         break;
2387                         
2388                 case LEFTMOUSE:
2389                 case RIGHTMOUSE:
2390                 case MIDDLEMOUSE:
2391                         if (link->tosock && link->fromsock) {
2392                                 /* send changed events for original tonode and new */
2393                                 snode_update(snode, link->tonode);
2394                                 
2395                                 /* we might need to remove a link */
2396                                 if (in_out==SOCK_OUT)
2397                                         node_remove_extra_links(snode, link->tosock, link);
2398                                 
2399                                 /* when linking to group outputs, update the socket type */
2400                                 /* XXX this should all be part of a generic update system */
2401                                 if (!link->tonode) {
2402                                         if(link->tosock->type != link->fromsock->type)
2403                                                 nodeSocketSetType(link->tosock, link->fromsock->type);
2404                                 }
2405                         }
2406                         else if (outside_group_rect(snode) && (link->tonode || link->fromnode)) {
2407                                 /* automatically add new group socket */
2408                                 if (link->tonode && link->tosock) {
2409                                         link->fromsock = node_group_expose_socket(snode->edittree, link->tosock, SOCK_IN);
2410                                         link->fromnode = NULL;
2411                                         if (link->prev==NULL && link->next==NULL) {
2412                                                 BLI_addtail(&snode->edittree->links, link);
2413                                         }
2414                                         snode->edittree->update |= NTREE_UPDATE_GROUP_IN | NTREE_UPDATE_LINKS;
2415                                 }
2416                                 else if (link->fromnode && link->fromsock) {
2417                                         link->tosock = node_group_expose_socket(snode->edittree, link->fromsock, SOCK_OUT);
2418                                         link->tonode = NULL;
2419                                         if (link->prev==NULL && link->next==NULL) {
2420                                                 BLI_addtail(&snode->edittree->links, link);
2421                                         }
2422                                         snode->edittree->update |= NTREE_UPDATE_GROUP_OUT | NTREE_UPDATE_LINKS;
2423                                 }
2424                         }
2425                         else
2426                                 nodeRemLink(snode->edittree, link);
2427                         
2428                         ntreeUpdateTree(snode->edittree);
2429                         snode_notify(C, snode);
2430                         snode_dag_update(C, snode);
2431                         
2432                         BLI_remlink(&snode->linkdrag, nldrag);
2433                         MEM_freeN(nldrag);
2434                         
2435                         return OPERATOR_FINISHED;
2436         }
2437         
2438         return OPERATOR_RUNNING_MODAL;
2439 }
2440
2441 /* return 1 when socket clicked */
2442 static int node_link_init(SpaceNode *snode, bNodeLinkDrag *nldrag)
2443 {
2444         bNodeLink *link;
2445         int in_out = 0;
2446
2447         /* output indicated? */
2448         if (node_find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
2449                 if (nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2450                         in_out = SOCK_OUT;
2451                 else {
2452                         /* find if we break a link */
2453                         for (link= snode->edittree->links.first; link; link= link->next) {
2454                                 if (link->fromsock==nldrag->sock)
2455                                         break;
2456                         }
2457                         if (link) {
2458                                 nldrag->node= link->tonode;
2459                                 nldrag->sock= link->tosock;
2460                                 nodeRemLink(snode->edittree, link);
2461                                 in_out = SOCK_IN;
2462                         }
2463                 }
2464         }
2465         /* or an input? */
2466         else if (node_find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
2467                 if (nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
2468                         in_out = SOCK_IN;
2469                 else {
2470                         /* find if we break a link */
2471                         for (link= snode->edittree->links.first; link; link= link->next) {
2472                                 if (link->tosock==nldrag->sock)
2473                                         break;
2474                         }
2475                         if (link) {
2476                                 /* send changed event to original tonode */
2477                                 if (link->tonode)
2478                                         snode_update(snode, link->tonode);
2479                                 
2480                                 nldrag->node= link->fromnode;
2481                                 nldrag->sock= link->fromsock;
2482                                 nodeRemLink(snode->edittree, link);
2483                                 in_out = SOCK_OUT;
2484                         }
2485                 }
2486         }
2487         
2488         return in_out;
2489 }
2490
2491 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
2492 {
2493         SpaceNode *snode= CTX_wm_space_node(C);
2494         ARegion *ar= CTX_wm_region(C);
2495         bNodeLinkDrag *nldrag= MEM_callocN(sizeof(bNodeLinkDrag), "drag link op customdata");
2496         
2497         
2498         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
2499                                                          &snode->mx, &snode->my);
2500
2501         ED_preview_kill_jobs(C);
2502
2503         nldrag->in_out= node_link_init(snode, nldrag);
2504         
2505         if (nldrag->in_out) {
2506                 op->customdata= nldrag;
2507                 
2508                 /* we make a temporal link */
2509                 if (nldrag->in_out==SOCK_OUT) {
2510                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2511                         nldrag->link->fromnode= nldrag->node;
2512                         nldrag->link->fromsock= nldrag->sock;
2513                         nldrag->link->tonode= NULL;
2514                         nldrag->link->tosock= NULL;
2515                 }
2516                 else {
2517                         nldrag->link= MEM_callocN(sizeof(bNodeLink), "link");
2518                         nldrag->link->fromnode= NULL;
2519                         nldrag->link->fromsock= NULL;
2520                         nldrag->link->tonode= nldrag->node;
2521                         nldrag->link->tosock= nldrag->sock;
2522                 }
2523                 BLI_addtail(&snode->linkdrag, nldrag);
2524                 
2525                 /* add modal handler */
2526                 WM_event_add_modal_handler(C, op);
2527                 
2528                 return OPERATOR_RUNNING_MODAL;
2529         }
2530         else {
2531                 MEM_freeN(nldrag);
2532                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2533         }
2534 }
2535
2536 static int node_link_cancel(bContext *C, wmOperator *op)
2537 {
2538         SpaceNode *snode= CTX_wm_space_node(C);
2539         bNodeLinkDrag *nldrag= op->customdata;
2540
2541         nodeRemLink(snode->edittree, nldrag->link);
2542         BLI_remlink(&snode->linkdrag, nldrag);
2543         MEM_freeN(nldrag);
2544
2545         return OPERATOR_CANCELLED;
2546 }
2547
2548 void NODE_OT_link(wmOperatorType *ot)
2549 {
2550         /* identifiers */
2551         ot->name = "Link Nodes";
2552         ot->idname = "NODE_OT_link";
2553         ot->description = "Use the mouse to create a link between two nodes";
2554         
2555         /* api callbacks */
2556         ot->invoke = node_link_invoke;
2557         ot->modal = node_link_modal;
2558 //      ot->exec = node_link_exec;
2559         ot->poll = ED_operator_node_active;
2560         ot->cancel = node_link_cancel;
2561         
2562         /* flags */
2563         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2564 }
2565
2566 /* ********************** Make Link operator ***************** */
2567
2568 /* makes a link between selected output and input sockets */
2569 static int node_make_link_exec(bContext *C, wmOperator *op)
2570 {
2571         SpaceNode *snode= CTX_wm_space_node(C);
2572         int replace = RNA_boolean_get(op->ptr, "replace");
2573
2574         ED_preview_kill_jobs(C);
2575
2576         snode_autoconnect(snode, 1, replace);
2577
2578         /* deselect sockets after linking */
2579         node_deselect_all_input_sockets(snode, 0);
2580         node_deselect_all_output_sockets(snode, 0);
2581
2582         ntreeUpdateTree(snode->edittree);
2583         snode_notify(C, snode);
2584         snode_dag_update(C, snode);
2585         
2586         return OPERATOR_FINISHED;
2587 }
2588
2589 void NODE_OT_link_make(wmOperatorType *ot)
2590 {
2591         /* identifiers */
2592         ot->name = "Make Links";
2593         ot->description = "Makes a link between selected output in input sockets";
2594         ot->idname = "NODE_OT_link_make";
2595         
2596         /* callbacks */
2597         ot->exec = node_make_link_exec;
2598         ot->poll = ED_operator_node_active; // XXX we need a special poll which checks that there are selected input/output sockets
2599         
2600         /* flags */
2601         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2602         
2603         RNA_def_boolean(ot->srna, "replace", 0, "Replace", "Replace socket connections with the new links");
2604 }
2605
2606 /* ********************** Cut Link operator ***************** */
2607
2608 #define LINK_RESOL 12
2609 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2610 {
2611         float coord_array[LINK_RESOL+1][2];
2612         int i, b;
2613         
2614         if (node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2615
2616                 for (i=0; i<tot-1; i++)
2617                         for (b=0; b<LINK_RESOL; b++)
2618                                 if (isect_line_line_v2(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2619                                         return 1;
2620         }
2621         return 0;
2622 }
2623
2624 static int cut_links_exec(bContext *C, wmOperator *op)
2625 {
2626         SpaceNode *snode= CTX_wm_space_node(C);
2627         ARegion *ar= CTX_wm_region(C);
2628         float mcoords[256][2];
2629         int i= 0;
2630         
2631         RNA_BEGIN (op->ptr, itemptr, "path")
2632         {
2633                 float loc[2];
2634                 
2635                 RNA_float_get_array(&itemptr, "loc", loc);
2636                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2637                                                                  &mcoords[i][0], &mcoords[i][1]);
2638                 i++;
2639                 if (i>= 256) break;
2640         }
2641         RNA_END;
2642         
2643         if (i>1) {
2644                 bNodeLink *link, *next;
2645
2646                 ED_preview_kill_jobs(C);
2647                 
2648                 for (link= snode->edittree->links.first; link; link= next) {
2649                         next= link->next;
2650                         
2651                         if (cut_links_intersect(link, mcoords, i)) {
2652                                 snode_update(snode, link->tonode);
2653                                 nodeRemLink(snode->edittree, link);
2654                         }
2655                 }
2656                 
2657                 ntreeUpdateTree(snode->edittree);
2658                 snode_notify(C, snode);
2659                 snode_dag_update(C, snode);
2660                 
2661                 return OPERATOR_FINISHED;
2662         }
2663         
2664         return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2665 }
2666
2667 void NODE_OT_links_cut(wmOperatorType *ot)
2668 {
2669         PropertyRNA *prop;
2670         
2671         ot->name = "Cut links";
2672         ot->idname = "NODE_OT_links_cut";
2673         ot->description = "Use the mouse to cut (remove) some links";
2674         
2675         ot->invoke = WM_gesture_lines_invoke;
2676         ot->modal = WM_gesture_lines_modal;
2677         ot->exec = cut_links_exec;
2678         ot->cancel = WM_gesture_lines_cancel;
2679         
2680         ot->poll = ED_operator_node_active;
2681         
2682         /* flags */
2683         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2684         
2685         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2686         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2687         /* internal */
2688         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2689 }
2690
2691 /* ********************** Detach links operator ***************** */
2692
2693 static int detach_links_exec(bContext *C, wmOperator *UNUSED(op))
2694 {
2695         SpaceNode *snode= CTX_wm_space_node(C);
2696         bNodeTree *ntree= snode->edittree;
2697         bNode *node;
2698         
2699         ED_preview_kill_jobs(C);
2700         
2701         for (node= ntree->nodes.first; node; node= node->next) {
2702                 if (node->flag & SELECT) {
2703                         nodeInternalRelink(ntree, node);
2704                 }
2705         }
2706         
2707         ntreeUpdateTree(ntree);
2708         
2709         snode_notify(C, snode);
2710         snode_dag_update(C, snode);
2711
2712         return OPERATOR_FINISHED;
2713 }
2714
2715 void NODE_OT_links_detach(wmOperatorType *ot)
2716 {
2717         ot->name = "Detach Links";
2718         ot->idname = "NODE_OT_links_detach";
2719         ot->description = "Remove all links to selected nodes, and try to connect neighbor nodes together";
2720         
2721         ot->exec = detach_links_exec;
2722         ot->poll = ED_operator_node_active;
2723         
2724         /* flags */
2725         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
2726 }
2727
2728 /* *********************  automatic node insert on dragging ******************* */
2729
2730 /* assumes sockets in list */
2731 static bNodeSocket *socket_best_match(ListBase *sockets)
2732 {
2733         bNodeSocket *sock;
2734         int type, maxtype=0;
2735         
2736         /* find type range */
2737         for (sock=sockets->first; sock; sock=sock->next)
2738                 maxtype = MAX2(sock->type, maxtype);
2739         
2740         /* try all types, starting from 'highest' (i.e. colors, vectors, values) */
2741         for (type=maxtype; type >= 0; --type) {
2742                 for (sock= sockets->first; sock; sock= sock->next) {
2743                         if (!nodeSocketIsHidden(sock) && type==sock->type) {
2744                                 return sock;
2745                         }
2746                 }
2747         }
2748         
2749         /* no visible sockets, unhide first of highest type */
2750         for (type=maxtype; type >= 0; --type) {
2751                 for (sock= sockets->first; sock; sock= sock->next) {
2752                         if (type==sock->type) {
2753                                 sock->flag &= ~SOCK_HIDDEN;
2754                                 return sock;
2755                         }
2756                 }
2757         }
2758         
2759         return NULL;
2760 }
2761
2762 /* prevent duplicate testing code below */
2763 static SpaceNode *ed_node_link_conditions(ScrArea *sa, bNode **select)
2764 {
2765         SpaceNode *snode= sa?sa->spacedata.first:NULL;
2766         bNode *node;
2767         bNodeLink *link;
2768         
2769         /* no unlucky accidents */
2770         if (sa==NULL || sa->spacetype!=SPACE_NODE) return NULL;
2771         
2772         *select= NULL;
2773         
2774         for (node= snode->edittree->nodes.first; node; node= node->next) {
2775                 if (node->flag & SELECT) {
2776                         if (*select)
2777                                 break;
2778                         else
2779                                 *select= node;
2780                 }
2781         }
2782         /* only one selected */
2783         if (node || *select==NULL) return NULL;
2784         
2785         /* correct node */
2786         if ((*select)->inputs.first==NULL || (*select)->outputs.first==NULL) return NULL;
2787         
2788         /* test node for links */
2789         for (link= snode->edittree->links.first; link; link=link->next) {
2790                 if (link->tonode == *select || link->fromnode == *select)
2791                         return NULL;
2792         }
2793         
2794         return snode;
2795 }
2796
2797 /* assumes link with NODE_LINKFLAG_HILITE set */
2798 void ED_node_link_insert(ScrArea *sa)
2799 {
2800         bNode *node, *select;
2801         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2802         bNodeLink *link;
2803         bNodeSocket *sockto;
2804         
2805         if (snode==NULL) return;
2806         
2807         /* get the link */
2808         for (link= snode->edittree->links.first; link; link=link->next)
2809                 if (link->flag & NODE_LINKFLAG_HILITE)
2810                         break;
2811         
2812         if (link) {
2813                 node= link->tonode;
2814                 sockto= link->tosock;
2815                 
2816                 link->tonode= select;
2817                 link->tosock= socket_best_match(&select->inputs);
2818                 link->flag &= ~NODE_LINKFLAG_HILITE;
2819                 
2820                 nodeAddLink(snode->edittree, select, socket_best_match(&select->outputs), node, sockto);
2821                 ntreeUpdateTree(snode->edittree);       /* needed for pointers */
2822                 snode_update(snode, select);
2823                 ED_node_changed_update(snode->id, select);
2824         }
2825 }
2826
2827
2828 /* test == 0, clear all intersect flags */
2829 void ED_node_link_intersect_test(ScrArea *sa, int test)
2830 {
2831         bNode *select;
2832         SpaceNode *snode= ed_node_link_conditions(sa, &select);
2833         bNodeLink *link, *selink=NULL;
2834         float mcoords[6][2];
2835         
2836         if (snode==NULL) return;
2837         
2838         /* clear flags */
2839         for (link= snode->edittree->links.first; link; link=link->next)
2840                 link->flag &= ~NODE_LINKFLAG_HILITE;
2841         
2842         if (test==0) return;
2843         
2844         /* okay, there's 1 node, without links, now intersect */
2845         mcoords[0][0]= select->totr.xmin;
2846         mcoords[0][1]= select->totr.ymin;
2847         mcoords[1][0]= select->totr.xmax;
2848         mcoords[1][1]= select->totr.ymin;
2849         mcoords[2][0]= select->totr.xmax;
2850         mcoords[2][1]= select->totr.ymax;
2851         mcoords[3][0]= select->totr.xmin;
2852         mcoords[3][1]= select->totr.ymax;
2853         mcoords[4][0]= select->totr.xmin;
2854         mcoords[4][1]= select->totr.ymin;
2855         mcoords[5][0]= select->totr.xmax;
2856         mcoords[5][1]= select->totr.ymax;
2857         
2858         /* we only tag a single link for intersect now */
2859         /* idea; use header dist when more? */
2860         for (link= snode->edittree->links.first; link; link=link->next) {
2861                 
2862                 if (cut_links_intersect(link, mcoords, 5)) { /* intersect code wants edges */
2863                         if (selink)
2864                                 break;
2865                         selink= link;
2866                 }
2867         }
2868                 
2869         if (link==NULL && selink)
2870                 selink->flag |= NODE_LINKFLAG_HILITE;
2871 }
2872
2873
2874 /* ******************************** */
2875 // XXX some code needing updating to operators...
2876
2877
2878 /* goes over all scenes, reads render layers */
2879 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
2880 {
2881         Main *bmain= CTX_data_main(C);
2882         SpaceNode *snode= CTX_wm_space_node(C);
2883         Scene *curscene= CTX_data_scene(C), *scene;
2884         bNode *node;
2885
2886         ED_preview_kill_jobs(C);
2887
2888         /* first tag scenes unread */
2889         for (scene= bmain->scene.first; scene; scene= scene->id.next)
2890                 scene->id.flag |= LIB_DOIT;
2891
2892         for (node= snode->edittree->nodes.first; node; node= node->next) {
2893                 if (node->type==CMP_NODE_R_LAYERS) {
2894                         ID *id= node->id;
2895                         if (id->flag & LIB_DOIT) {
2896                                 RE_ReadRenderResult(curscene, (Scene *)id);
2897                                 ntreeCompositTagRender((Scene *)id);
2898                                 id->flag &= ~LIB_DOIT;
2899                         }
2900                 }
2901         }
2902         
2903         snode_notify(C, snode);
2904         snode_dag_update(C, snode);
2905
2906         return OPERATOR_FINISHED;
2907 }
2908
2909 void NODE_OT_read_renderlayers(wmOperatorType *ot)
2910 {
2911         
2912         ot->name = "Read Render Layers";
2913         ot->idname = "NODE_OT_read_renderlayers";
2914         ot->description = "Read all render layers of all used scenes";
2915         
2916         ot->exec = node_read_renderlayers_exec;
2917         
2918         ot->poll = composite_node_active;
2919         
2920         /* flags */
2921         ot->flag = 0;
2922 }
2923
2924 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
2925 {
2926         Main *bmain= CTX_data_main(C);
2927         SpaceNode *snode= CTX_wm_space_node(C);
2928         Scene *curscene= CTX_data_scene(C);
2929         Render *re= RE_NewRender(curscene->id.name);
2930
2931         WM_cursor_wait(1);
2932         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
2933         WM_cursor_wait(0);
2934
2935         /* note we are careful to send the right notifier, as otherwise the
2936          * compositor would reexecute and overwrite the full sample result */
2937         WM_event_add_notifier(C, NC_SCENE|ND_COMPO_RESULT, NULL);
2938
2939         return OPERATOR_FINISHED;
2940 }
2941
2942
2943 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
2944 {
2945         
2946         ot->name = "Read Full Sample Layers";
2947         ot->idname = "NODE_OT_read_fullsamplelayers";
2948         ot->description = "Read all render layers of current scene, in full sample";
2949         
2950         ot->exec = node_read_fullsamplelayers_exec;
2951         
2952         ot->poll = composite_node_active;
2953         
2954         /* flags */
2955         ot->flag = 0;
2956 }
2957
2958 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
2959 {
2960         Scene *sce= CTX_data_scene(C);
2961         bNode *node;
2962         
2963         for (node= sce->nodetree->nodes.first; node; node= node->next) {
2964                 if (node->id==(ID *)sce && node->need_exec) {
2965                         break;
2966                 }
2967         }
2968         if (node) {
2969                 SceneRenderLayer *srl= BLI_findlink(&sce->r.layers, node->custom1);
2970                 
2971                 if (srl) {
2972                         PointerRNA op_ptr;
2973                         
2974                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
2975                         RNA_string_set(&op_ptr, "layer", srl->name);
2976                         RNA_string_set(&op_ptr, "scene", sce->id.name+2);
2977                         
2978                         /* to keep keypositions */
2979                         sce->r.scemode |= R_NO_FRAME_UPDATE;
2980                         
2981                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
2982
2983                         WM_operator_properties_free(&op_ptr);
2984                         
2985                         return OPERATOR_FINISHED;
2986                 }
2987                    
2988         }
2989         return OPERATOR_CANCELLED;
2990 }
2991
2992 void NODE_OT_render_changed(wmOperatorType *ot)
2993 {
2994         
2995         ot->name = "Render Changed Layer";
2996         ot->idname = "NODE_OT_render_changed";
2997         ot->description = "Render current scene, when input node's layer has been changed";
2998         
2999         ot->exec = node_render_changed_exec;
3000         
3001         ot->poll = composite_node_active;
3002         
3003         /* flags */
3004         ot->flag = 0;
3005 }
3006
3007
3008 /* ****************** Make Group operator ******************* */
3009
3010 static int node_group_make_exec(bContext *C, wmOperator *op)
3011 {
3012         SpaceNode *snode = CTX_wm_space_node(C);
3013         bNode *gnode;
3014         
3015         if (snode->edittree!=snode->nodetree) {
3016                 BKE_report(op->reports, RPT_WARNING, "Can not add a new Group in a Group");
3017                 return OPERATOR_CANCELLED;
3018         }
3019         
3020         /* for time being... is too complex to handle */
3021         if (snode->treetype==NTREE_COMPOSIT) {
3022                 for (gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
3023                         if (gnode->flag & SELECT)
3024                                 if (gnode->type==CMP_NODE_R_LAYERS)
3025                                         break;
3026                 }
3027                 
3028                 if (gnode) {
3029                         BKE_report(op->reports, RPT_WARNING, "Can not add RenderLayer in a Group");
3030                         return OPERATOR_CANCELLED;
3031                 }
3032         }
3033
3034         ED_preview_kill_jobs(C);
3035         
3036         gnode= node_group_make_from_selected(snode->nodetree);
3037         if (gnode==NULL) {
3038                 BKE_report(op->reports, RPT_WARNING, "Can not make Group");
3039                 return OPERATOR_CANCELLED;
3040         }
3041         else {
3042                 nodeSetActive(snode->nodetree, gnode);
3043                 ntreeUpdateTree(snode->nodetree);
3044         }
3045         
3046         snode_notify(C, snode);
3047         snode_dag_update(C, snode);
3048         
3049         return OPERATOR_FINISHED;
3050 }
3051
3052 void NODE_OT_group_make(wmOperatorType *ot)
3053 {
3054         /* identifiers */
3055         ot->name = "Group";
3056         ot->description = "Make group from selected nodes";
3057         ot->idname = "NODE_OT_group_make";
3058         
3059         /* api callbacks */
3060         ot->exec = node_group_make_exec;
3061         ot->poll = ED_operator_node_active;
3062         
3063         /* flags */
3064         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
3065 }
3066
3067 /* ****************** Hide operator *********************** */
3068
3069 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
3070 {
3071         bNode *node;
3072         int tot_eq= 0, tot_neq= 0;
3073
3074         /* Toggles the flag on all selected nodes.
3075          * If the flag is set on all nodes it is unset.
3076          * If the flag is not set on all nodes, it is set.
3077          */
3078         for (node= snode->edittree->nodes.first; node; node= node->next) {
3079                 if (node->flag & SELECT) {
3080                         
3081                         if (toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
3082                                 continue;
3083                         if (toggle_flag== NODE_OPTIONS && (node->typeinfo->flag & NODE_OPTIONS)==0)
3084                                 continue;
3085                         
3086                         if (node->flag & toggle_flag)
3087                                 tot_eq++;
3088                         else
3089                                 tot_neq++;
3090                 }
3091         }
3092         for (node= snode->edittree->nodes.first; node; node= node->next) {
3093                 if (node->flag & SELECT) {
3094                         
3095                         if (toggle_flag== NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW)==0)
3096                                 continue;
3097                         if (toggle_flag== NODE_OPTIONS && (node->typeinfo->flag & NODE_OPTIONS)==0)
3098                                 continue;
3099                         
3100                         if ( (tot_eq && tot_neq) || tot_eq==0)
3101                                 node->flag |= toggle_flag;
3102                         else
3103                                 node->flag &= ~toggle_flag;
3104                 }
3105         }
3106 }
3107
3108 static int node_hide_toggle_exec(bContext *C, wmOperator *UNUSED(op))
3109 {
3110         SpaceNode *snode= CTX_wm_space_node(C);
3111         
3112         /* sanity checking (poll callback checks this already) */
3113         if ((snode == NULL) || (snode->edittree == NULL))
3114                 return OPERATOR_CANCELLED;
3115         
3116         node_flag_toggle_exec(snode, NODE_HIDDEN);
3117         
3118         snode_notify(C, snode);
3119         
3120         return OPERATOR_FINISHED;
3121 }
3122
3123 void NODE_OT_hide_toggle(wmOperatorType *ot)
3124 {
3125         /* identifiers */
3126         ot->name = "Hide";
3127         ot->description = "Toggle hiding of selected nodes";
3128         ot->idname = "NODE_OT_hide_toggle";
3129         
3130         /* callbacks */
3131         ot->exec = node_hide_toggle_exec;
3132         ot->poll = ED_operator_node_active;
3133
3134         /* flags */
3135         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
3136 }
3137
3138 static int node_preview_toggle_exec(bContext *C, wmOperator *UNUSED(op))
3139 {
3140         SpaceNode *snode= CTX_wm_space_node(C);
3141
3142         /* sanity checking (poll callback checks this already) */
3143         if ((snode == NULL) || (snode->edittree == NULL))
3144                 return OPERATOR_CANCELLED;
3145
3146         ED_preview_kill_jobs(C);
3147
3148         node_flag_toggle_exec(snode, NODE_PREVIEW);
3149
3150         snode_notify(C, snode);
3151
3152         return OPERATOR_FINISHED;
3153 }
3154
3155 void NODE_OT_preview_toggle(wmOperatorType *ot)
3156 {
3157         /* identifiers */
3158         ot->name = "Toggle Node Preview";
3159         ot->description = "Toggle preview display for selected nodes";
3160         ot->idname = "NODE_OT_preview_toggle";
3161
3162         /* callbacks */
3163         ot->exec = node_preview_toggle_exec;
3164         ot->poll = ED_operator_node_active;
3165
3166         /* flags */
3167         ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
3168 }
3169