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