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