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