Cleanup: strip trailing space in editors
[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 #include "MEM_guardedalloc.h"
33
34 #include "DNA_lamp_types.h"
35 #include "DNA_material_types.h"
36 #include "DNA_node_types.h"
37 #include "DNA_text_types.h"
38 #include "DNA_world_types.h"
39
40 #include "BLI_math.h"
41 #include "BLI_blenlib.h"
42
43 #include "BKE_context.h"
44 #include "BKE_depsgraph.h"
45 #include "BKE_global.h"
46 #include "BKE_image.h"
47 #include "BKE_library.h"
48 #include "BKE_main.h"
49 #include "BKE_node.h"
50 #include "BKE_report.h"
51 #include "BKE_scene.h"
52
53 #include "RE_engine.h"
54 #include "RE_pipeline.h"
55
56
57 #include "ED_node.h"  /* own include */
58 #include "ED_screen.h"
59 #include "ED_render.h"
60
61 #include "RNA_access.h"
62 #include "RNA_define.h"
63 #include "RNA_enum_types.h"
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 #include "UI_view2d.h"
69
70 #include "GPU_material.h"
71
72 #include "IMB_imbuf_types.h"
73
74 #include "node_intern.h"  /* own include */
75 #include "NOD_composite.h"
76 #include "NOD_shader.h"
77 #include "NOD_texture.h"
78
79
80 #define USE_ESC_COMPO
81
82 /* ***************** composite job manager ********************** */
83
84 enum {
85         COM_RECALC_COMPOSITE = 1,
86         COM_RECALC_VIEWER    = 2
87 };
88
89 typedef struct CompoJob {
90         Scene *scene;
91         bNodeTree *ntree;
92         bNodeTree *localtree;
93         const short *stop;
94         short *do_update;
95         float *progress;
96         int recalc_flags;
97 } CompoJob;
98
99 static void compo_tag_output_nodes(bNodeTree *nodetree, int recalc_flags)
100 {
101         bNode *node;
102
103         for (node = nodetree->nodes.first; node; node = node->next) {
104                 if (node->type == CMP_NODE_COMPOSITE) {
105                         if (recalc_flags & COM_RECALC_COMPOSITE)
106                                 node->flag |= NODE_DO_OUTPUT_RECALC;
107                 }
108                 else if (node->type == CMP_NODE_VIEWER || node->type == CMP_NODE_SPLITVIEWER) {
109                         if (recalc_flags & COM_RECALC_VIEWER)
110                                 node->flag |= NODE_DO_OUTPUT_RECALC;
111                 }
112                 else if (node->type == NODE_GROUP) {
113                         if (node->id)
114                                 compo_tag_output_nodes((bNodeTree *)node->id, recalc_flags);
115                 }
116         }
117 }
118
119 static int compo_get_recalc_flags(const bContext *C)
120 {
121         wmWindowManager *wm = CTX_wm_manager(C);
122         wmWindow *win;
123         int recalc_flags = 0;
124
125         for (win = wm->windows.first; win; win = win->next) {
126                 bScreen *sc = win->screen;
127                 ScrArea *sa;
128
129                 for (sa = sc->areabase.first; sa; sa = sa->next) {
130                         if (sa->spacetype == SPACE_IMAGE) {
131                                 SpaceImage *sima = sa->spacedata.first;
132                                 if (sima->image) {
133                                         if (sima->image->type == IMA_TYPE_R_RESULT)
134                                                 recalc_flags |= COM_RECALC_COMPOSITE;
135                                         else if (sima->image->type == IMA_TYPE_COMPOSITE)
136                                                 recalc_flags |= COM_RECALC_VIEWER;
137                                 }
138                         }
139                         else if (sa->spacetype == SPACE_NODE) {
140                                 SpaceNode *snode = sa->spacedata.first;
141                                 if (snode->flag & SNODE_BACKDRAW)
142                                         recalc_flags |= COM_RECALC_VIEWER;
143                         }
144                 }
145         }
146
147         return recalc_flags;
148 }
149
150 /* called by compo, only to check job 'stop' value */
151 static int compo_breakjob(void *cjv)
152 {
153         CompoJob *cj = cjv;
154
155         /* without G.is_break 'ESC' wont quit - which annoys users */
156         return (*(cj->stop)
157 #ifdef USE_ESC_COMPO
158                 ||
159                 G.is_break
160 #endif
161                 );
162 }
163
164 /* called by compo, wmJob sends notifier */
165 static void compo_statsdrawjob(void *cjv, const char *UNUSED(str))
166 {
167         CompoJob *cj = cjv;
168
169         *(cj->do_update) = true;
170 }
171
172 /* called by compo, wmJob sends notifier */
173 static void compo_redrawjob(void *cjv)
174 {
175         CompoJob *cj = cjv;
176
177         *(cj->do_update) = true;
178 }
179
180 static void compo_freejob(void *cjv)
181 {
182         CompoJob *cj = cjv;
183
184         if (cj->localtree) {
185                 ntreeLocalMerge(cj->localtree, cj->ntree);
186         }
187         MEM_freeN(cj);
188 }
189
190 /* only now we copy the nodetree, so adding many jobs while
191  * sliding buttons doesn't frustrate */
192 static void compo_initjob(void *cjv)
193 {
194         CompoJob *cj = cjv;
195
196         cj->localtree = ntreeLocalize(cj->ntree);
197
198         if (cj->recalc_flags)
199                 compo_tag_output_nodes(cj->localtree, cj->recalc_flags);
200 }
201
202 /* called before redraw notifiers, it moves finished previews over */
203 static void compo_updatejob(void *UNUSED(cjv))
204 {
205         WM_main_add_notifier(NC_SCENE | ND_COMPO_RESULT, NULL);
206 }
207
208 static void compo_progressjob(void *cjv, float progress)
209 {
210         CompoJob *cj = cjv;
211
212         *(cj->progress) = progress;
213 }
214
215 /* only this runs inside thread */
216 static void compo_startjob(void *cjv, short *stop, short *do_update, float *progress)
217 {
218         CompoJob *cj = cjv;
219         bNodeTree *ntree = cj->localtree;
220         Scene *scene = cj->scene;
221         SceneRenderView *srv;
222
223         if (scene->use_nodes == false)
224                 return;
225
226         cj->stop = stop;
227         cj->do_update = do_update;
228         cj->progress = progress;
229
230         ntree->test_break = compo_breakjob;
231         ntree->tbh = cj;
232         ntree->stats_draw = compo_statsdrawjob;
233         ntree->sdh = cj;
234         ntree->progress = compo_progressjob;
235         ntree->prh = cj;
236         ntree->update_draw = compo_redrawjob;
237         ntree->udh = cj;
238
239         // XXX BIF_store_spare();
240         /* 1 is do_previews */
241
242         if ((cj->scene->r.scemode & R_MULTIVIEW) == 0) {
243                 ntreeCompositExecTree(cj->scene, ntree, &cj->scene->r, false, true, &scene->view_settings, &scene->display_settings, "");
244         }
245         else {
246                 for (srv = scene->r.views.first; srv; srv = srv->next) {
247                         if (BKE_scene_multiview_is_render_view_active(&scene->r, srv) == false) continue;
248                         ntreeCompositExecTree(cj->scene, ntree, &cj->scene->r, false, true, &scene->view_settings, &scene->display_settings, srv->name);
249                 }
250         }
251
252         ntree->test_break = NULL;
253         ntree->stats_draw = NULL;
254         ntree->progress = NULL;
255
256 }
257
258 /**
259  * \param scene_owner is the owner of the job,
260  * we don't use it for anything else currently so could also be a void pointer,
261  * but for now keep it an 'Scene' for consistency.
262  *
263  * \note only call from spaces `refresh` callbacks, not direct! - use with care.
264  */
265 void ED_node_composite_job(const bContext *C, struct bNodeTree *nodetree, Scene *scene_owner)
266 {
267         wmJob *wm_job;
268         CompoJob *cj;
269         Scene *scene = CTX_data_scene(C);
270
271         /* to fix bug: [#32272] */
272         if (G.is_rendering) {
273                 return;
274         }
275
276 #ifdef USE_ESC_COMPO
277         G.is_break = false;
278 #endif
279
280         BKE_image_backup_render(scene, BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result"), false);
281
282         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene_owner, "Compositing",
283                              WM_JOB_EXCL_RENDER | WM_JOB_PROGRESS, WM_JOB_TYPE_COMPOSITE);
284         cj = MEM_callocN(sizeof(CompoJob), "compo job");
285
286         /* customdata for preview thread */
287         cj->scene = scene;
288         cj->ntree = nodetree;
289         cj->recalc_flags = compo_get_recalc_flags(C);
290
291         /* setup job */
292         WM_jobs_customdata_set(wm_job, cj, compo_freejob);
293         WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_COMPO_RESULT, NC_SCENE | ND_COMPO_RESULT);
294         WM_jobs_callbacks(wm_job, compo_startjob, compo_initjob, compo_updatejob, NULL);
295
296         WM_jobs_start(CTX_wm_manager(C), wm_job);
297 }
298
299 /* ***************************************** */
300
301 /* operator poll callback */
302 int composite_node_active(bContext *C)
303 {
304         if (ED_operator_node_active(C)) {
305                 SpaceNode *snode = CTX_wm_space_node(C);
306                 if (ED_node_is_compositor(snode))
307                         return 1;
308         }
309         return 0;
310 }
311
312 /* operator poll callback */
313 int composite_node_editable(bContext *C)
314 {
315         if (ED_operator_node_editable(C)) {
316                 SpaceNode *snode = CTX_wm_space_node(C);
317                 if (ED_node_is_compositor(snode))
318                         return 1;
319         }
320         return 0;
321 }
322
323 void snode_dag_update(bContext *C, SpaceNode *snode)
324 {
325         Main *bmain = CTX_data_main(C);
326
327         /* for groups, update all ID's using this */
328         if (snode->edittree != snode->nodetree) {
329                 FOREACH_NODETREE(bmain, tntree, id) {
330                         if (ntreeHasTree(tntree, snode->edittree))
331                                 DAG_id_tag_update(id, 0);
332                 } FOREACH_NODETREE_END
333         }
334
335         DAG_id_tag_update(snode->id, 0);
336 }
337
338 void snode_notify(bContext *C, SpaceNode *snode)
339 {
340         ID *id = snode->id;
341
342         WM_event_add_notifier(C, NC_NODE | NA_EDITED, NULL);
343
344         if (ED_node_is_shader(snode)) {
345                 if (GS(id->name) == ID_MA)
346                         WM_main_add_notifier(NC_MATERIAL | ND_SHADING, id);
347                 else if (GS(id->name) == ID_LA)
348                         WM_main_add_notifier(NC_LAMP | ND_LIGHTING, id);
349                 else if (GS(id->name) == ID_WO)
350                         WM_main_add_notifier(NC_WORLD | ND_WORLD, id);
351         }
352         else if (ED_node_is_compositor(snode))
353                 WM_event_add_notifier(C, NC_SCENE | ND_NODES, id);
354         else if (ED_node_is_texture(snode))
355                 WM_event_add_notifier(C, NC_TEXTURE | ND_NODES, id);
356 }
357
358 void ED_node_set_tree_type(SpaceNode *snode, bNodeTreeType *typeinfo)
359 {
360         if (typeinfo)
361                 BLI_strncpy(snode->tree_idname, typeinfo->idname, sizeof(snode->tree_idname));
362         else
363                 snode->tree_idname[0] = '\0';
364 }
365
366 bool ED_node_is_compositor(struct SpaceNode *snode)
367 {
368         return STREQ(snode->tree_idname, ntreeType_Composite->idname);
369 }
370
371 bool ED_node_is_shader(struct SpaceNode *snode)
372 {
373         return STREQ(snode->tree_idname, ntreeType_Shader->idname);
374 }
375
376 bool ED_node_is_texture(struct SpaceNode *snode)
377 {
378         return STREQ(snode->tree_idname, ntreeType_Texture->idname);
379 }
380
381 /* assumes nothing being done in ntree yet, sets the default in/out node */
382 /* called from shading buttons or header */
383 void ED_node_shader_default(const bContext *C, ID *id)
384 {
385         Scene *scene = CTX_data_scene(C);
386         bNode *in, *out;
387         bNodeSocket *fromsock, *tosock, *sock;
388         bNodeTree *ntree;
389         int output_type, shader_type;
390         float color[4] = { 0.0f, 0.0f, 0.0f, 1.0f }, strength = 1.0f;
391
392         ntree = ntreeAddTree(NULL, "Shader Nodetree", ntreeType_Shader->idname);
393
394         switch (GS(id->name)) {
395                 case ID_MA:
396                 {
397                         Material *ma = (Material *)id;
398                         ma->nodetree = ntree;
399
400                         if (BKE_scene_use_new_shading_nodes(scene)) {
401                                 output_type = SH_NODE_OUTPUT_MATERIAL;
402                                 shader_type = SH_NODE_BSDF_DIFFUSE;
403                         }
404                         else {
405                                 output_type = SH_NODE_OUTPUT;
406                                 shader_type = SH_NODE_MATERIAL;
407                         }
408
409                         copy_v3_v3(color, &ma->r);
410                         strength = 0.0f;
411                         break;
412                 }
413                 case ID_WO:
414                 {
415                         World *wo = (World *)id;
416                         wo->nodetree = ntree;
417
418                         output_type = SH_NODE_OUTPUT_WORLD;
419                         shader_type = SH_NODE_BACKGROUND;
420
421                         copy_v3_v3(color, &wo->horr);
422                         strength = 1.0f;
423                         break;
424                 }
425                 case ID_LA:
426                 {
427                         Lamp *la = (Lamp *)id;
428                         la->nodetree = ntree;
429
430                         output_type = SH_NODE_OUTPUT_LAMP;
431                         shader_type = SH_NODE_EMISSION;
432
433                         copy_v3_v3(color, &la->r);
434                         if (la->type == LA_LOCAL || la->type == LA_SPOT || la->type == LA_AREA)
435                                 strength = 100.0f;
436                         else
437                                 strength = 1.0f;
438                         break;
439                 }
440                 default:
441                         printf("ED_node_shader_default called on wrong ID type.\n");
442                         return;
443         }
444
445         out = nodeAddStaticNode(C, ntree, output_type);
446         out->locx = 300.0f; out->locy = 300.0f;
447
448         in = nodeAddStaticNode(C, ntree, shader_type);
449         in->locx = 10.0f; in->locy = 300.0f;
450         nodeSetActive(ntree, in);
451
452         /* only a link from color to color */
453         fromsock = in->outputs.first;
454         tosock = out->inputs.first;
455         nodeAddLink(ntree, in, fromsock, out, tosock);
456
457         /* default values */
458         if (BKE_scene_use_new_shading_nodes(scene)) {
459                 PointerRNA sockptr;
460                 sock = in->inputs.first;
461                 RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, sock, &sockptr);
462
463                 RNA_float_set_array(&sockptr, "default_value", color);
464
465                 if (strength != 0.0f) {
466                         sock = in->inputs.last;
467                         RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, sock, &sockptr);
468                         RNA_float_set(&sockptr, "default_value", strength);
469                 }
470         }
471
472         ntreeUpdateTree(CTX_data_main(C), ntree);
473 }
474
475 /* assumes nothing being done in ntree yet, sets the default in/out node */
476 /* called from shading buttons or header */
477 void ED_node_composit_default(const bContext *C, struct Scene *sce)
478 {
479         bNode *in, *out;
480         bNodeSocket *fromsock, *tosock;
481
482         /* but lets check it anyway */
483         if (sce->nodetree) {
484                 if (G.debug & G_DEBUG)
485                         printf("error in composite initialize\n");
486                 return;
487         }
488
489         sce->nodetree = ntreeAddTree(NULL, "Compositing Nodetree", ntreeType_Composite->idname);
490
491         sce->nodetree->chunksize = 256;
492         sce->nodetree->edit_quality = NTREE_QUALITY_HIGH;
493         sce->nodetree->render_quality = NTREE_QUALITY_HIGH;
494
495         out = nodeAddStaticNode(C, sce->nodetree, CMP_NODE_COMPOSITE);
496         out->locx = 300.0f; out->locy = 400.0f;
497
498         in = nodeAddStaticNode(C, sce->nodetree, CMP_NODE_R_LAYERS);
499         in->locx = 10.0f; in->locy = 400.0f;
500         nodeSetActive(sce->nodetree, in);
501
502         /* links from color to color */
503         fromsock = in->outputs.first;
504         tosock = out->inputs.first;
505         nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
506
507         ntreeUpdateTree(CTX_data_main(C), sce->nodetree);
508 }
509
510 /* assumes nothing being done in ntree yet, sets the default in/out node */
511 /* called from shading buttons or header */
512 void ED_node_texture_default(const bContext *C, Tex *tx)
513 {
514         bNode *in, *out;
515         bNodeSocket *fromsock, *tosock;
516
517         /* but lets check it anyway */
518         if (tx->nodetree) {
519                 if (G.debug & G_DEBUG)
520                         printf("error in texture initialize\n");
521                 return;
522         }
523
524         tx->nodetree = ntreeAddTree(NULL, "Texture Nodetree", ntreeType_Texture->idname);
525
526         out = nodeAddStaticNode(C, tx->nodetree, TEX_NODE_OUTPUT);
527         out->locx = 300.0f; out->locy = 300.0f;
528
529         in = nodeAddStaticNode(C, tx->nodetree, TEX_NODE_CHECKER);
530         in->locx = 10.0f; in->locy = 300.0f;
531         nodeSetActive(tx->nodetree, in);
532
533         fromsock = in->outputs.first;
534         tosock = out->inputs.first;
535         nodeAddLink(tx->nodetree, in, fromsock, out, tosock);
536
537         ntreeUpdateTree(CTX_data_main(C), tx->nodetree);
538 }
539
540 /* Here we set the active tree(s), even called for each redraw now, so keep it fast :) */
541 void snode_set_context(const bContext *C)
542 {
543         SpaceNode *snode = CTX_wm_space_node(C);
544         bNodeTreeType *treetype = ntreeTypeFind(snode->tree_idname);
545         bNodeTree *ntree = snode->nodetree;
546         ID *id = snode->id, *from = snode->from;
547
548         /* we use this to signal warnings, when node shaders are drawn in wrong render engine */
549         if (BKE_scene_use_new_shading_nodes(CTX_data_scene(C)))
550                 snode->flag |= SNODE_NEW_SHADERS;
551         else
552                 snode->flag &= ~SNODE_NEW_SHADERS;
553
554         /* check the tree type */
555         if (!treetype ||
556             (treetype->poll && !treetype->poll(C, treetype)))
557         {
558                 /* invalid tree type, skip
559                  * NB: not resetting the node path here, invalid bNodeTreeType
560                  * may still be registered at a later point.
561                  */
562                 return;
563         }
564
565         if (snode->nodetree && !STREQ(snode->nodetree->idname, snode->tree_idname)) {
566                 /* current tree does not match selected type, clear tree path */
567                 ntree = NULL;
568                 id = NULL;
569                 from = NULL;
570         }
571
572         if (!(snode->flag & SNODE_PIN) || ntree == NULL) {
573                 if (treetype->get_from_context) {
574                         /* reset and update from context */
575                         ntree = NULL;
576                         id = NULL;
577                         from = NULL;
578
579                         treetype->get_from_context(C, treetype, &ntree, &id, &from);
580                 }
581         }
582
583         if (snode->nodetree != ntree || snode->id != id || snode->from != from ||
584             (snode->treepath.last == NULL && ntree))
585         {
586                 ED_node_tree_start(snode, ntree, id, from);
587         }
588 }
589
590 void snode_update(SpaceNode *snode, bNode *node)
591 {
592         bNodeTreePath *path;
593
594         /* XXX this only updates nodes in the current node space tree path.
595          * The function supposedly should update any potential group node linking to changed tree,
596          * this really requires a working depsgraph ...
597          */
598
599         /* update all edited group nodes */
600         path = snode->treepath.last;
601         if (path) {
602                 bNodeTree *ngroup = path->nodetree;
603                 for (path = path->prev; path; path = path->prev) {
604                         nodeUpdateID(path->nodetree, (ID *)ngroup);
605                         ngroup = path->nodetree;
606                 }
607         }
608
609         if (node)
610                 nodeUpdate(snode->edittree, node);
611 }
612
613 void ED_node_set_active(Main *bmain, bNodeTree *ntree, bNode *node)
614 {
615         const bool was_active_texture = (node->flag & NODE_ACTIVE_TEXTURE) != 0;
616
617         nodeSetActive(ntree, node);
618
619         if (node->type != NODE_GROUP) {
620                 const bool was_output = (node->flag & NODE_DO_OUTPUT) != 0;
621                 bool do_update = false;
622
623                 /* generic node group output: set node as active output */
624                 if (node->type == NODE_GROUP_OUTPUT) {
625                         bNode *tnode;
626                         for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
627                                 if (tnode->type == NODE_GROUP_OUTPUT)
628                                         tnode->flag &= ~NODE_DO_OUTPUT;
629
630                         node->flag |= NODE_DO_OUTPUT;
631                         if (!was_output)
632                                 do_update = 1;
633                 }
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 && ELEM(GS(node->id->name), ID_MA, ID_LA, ID_WO))
639                                 nodeClearActiveID(ntree, ID_TE);
640
641                         if (ELEM(node->type, SH_NODE_OUTPUT, SH_NODE_OUTPUT_MATERIAL,
642                                  SH_NODE_OUTPUT_WORLD, SH_NODE_OUTPUT_LAMP, SH_NODE_OUTPUT_LINESTYLE))
643                         {
644                                 bNode *tnode;
645
646                                 for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
647                                         if (tnode->type == node->type)
648                                                 tnode->flag &= ~NODE_DO_OUTPUT;
649
650                                 node->flag |= NODE_DO_OUTPUT;
651                                 if (was_output == 0)
652                                         ED_node_tag_update_nodetree(bmain, ntree, node);
653                         }
654                         else if (do_update)
655                                 ED_node_tag_update_nodetree(bmain, ntree, node);
656
657                         /* if active texture changed, free glsl materials */
658                         if ((node->flag & NODE_ACTIVE_TEXTURE) && !was_active_texture) {
659                                 Material *ma;
660                                 World *wo;
661
662                                 for (ma = bmain->mat.first; ma; ma = ma->id.next)
663                                         if (ma->nodetree && ma->use_nodes && ntreeHasTree(ma->nodetree, ntree))
664                                                 GPU_material_free(&ma->gpumaterial);
665
666                                 for (wo = bmain->world.first; wo; wo = wo->id.next)
667                                         if (wo->nodetree && wo->use_nodes && ntreeHasTree(wo->nodetree, ntree))
668                                                 GPU_material_free(&wo->gpumaterial);
669
670                                 WM_main_add_notifier(NC_IMAGE, NULL);
671                         }
672
673                         WM_main_add_notifier(NC_MATERIAL | ND_NODES, node->id);
674                 }
675                 else if (ntree->type == NTREE_COMPOSIT) {
676                         /* make active viewer, currently only 1 supported... */
677                         if (ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
678                                 bNode *tnode;
679
680
681                                 for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
682                                         if (ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
683                                                 tnode->flag &= ~NODE_DO_OUTPUT;
684
685                                 node->flag |= NODE_DO_OUTPUT;
686                                 if (was_output == 0)
687                                         ED_node_tag_update_nodetree(bmain, ntree, node);
688
689                                 /* addnode() doesnt link this yet... */
690                                 node->id = (ID *)BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
691                         }
692                         else if (node->type == CMP_NODE_R_LAYERS) {
693                                 Scene *scene;
694
695                                 for (scene = bmain->scene.first; scene; scene = scene->id.next) {
696                                         if (scene->nodetree && scene->use_nodes && ntreeHasTree(scene->nodetree, ntree)) {
697                                                 if (node->id == NULL || node->id == (ID *)scene) {
698                                                         int num_layers = BLI_listbase_count(&scene->r.layers);
699                                                         scene->r.actlay = node->custom1;
700                                                         /* Clamp the value, because it might have come from a different
701                                                          * scene which could have more render layers than new one.
702                                                          */
703                                                         scene->r.actlay = min_ff(scene->r.actlay, num_layers - 1);
704                                                 }
705                                         }
706                                 }
707                         }
708                         else if (node->type == CMP_NODE_COMPOSITE) {
709                                 if (was_output == 0) {
710                                         bNode *tnode;
711
712                                         for (tnode = ntree->nodes.first; tnode; tnode = tnode->next)
713                                                 if (tnode->type == CMP_NODE_COMPOSITE)
714                                                         tnode->flag &= ~NODE_DO_OUTPUT;
715
716                                         node->flag |= NODE_DO_OUTPUT;
717                                         ED_node_tag_update_nodetree(bmain, ntree, node);
718                                 }
719                         }
720                         else if (do_update)
721                                 ED_node_tag_update_nodetree(bmain, ntree, node);
722                 }
723                 else if (ntree->type == NTREE_TEXTURE) {
724                         // XXX
725 #if 0
726                         if (node->id)
727                                 ;  // XXX BIF_preview_changed(-1);
728                         // allqueue(REDRAWBUTSSHADING, 1);
729                         // allqueue(REDRAWIPO, 0);
730 #endif
731                 }
732         }
733 }
734
735 void ED_node_post_apply_transform(bContext *UNUSED(C), bNodeTree *UNUSED(ntree))
736 {
737         /* XXX This does not work due to layout functions relying on node->block,
738          * which only exists during actual drawing. Can we rely on valid totr rects?
739          */
740         /* make sure nodes have correct bounding boxes after transform */
741         /* node_update_nodetree(C, ntree, 0.0f, 0.0f); */
742 }
743
744 /* ***************** generic operator functions for nodes ***************** */
745
746 #if 0 /* UNUSED */
747
748 static int edit_node_poll(bContext *C)
749 {
750         return ED_operator_node_active(C);
751 }
752
753 static void edit_node_properties(wmOperatorType *ot)
754 {
755         /* XXX could node be a context pointer? */
756         RNA_def_string(ot->srna, "node", NULL, MAX_NAME, "Node", "");
757         RNA_def_int(ot->srna, "socket", 0, 0, MAX_SOCKET, "Socket", "", 0, MAX_SOCKET);
758         RNA_def_enum(ot->srna, "in_out", rna_enum_node_socket_in_out_items, SOCK_IN, "Socket Side", "");
759 }
760
761 static int edit_node_invoke_properties(bContext *C, wmOperator *op)
762 {
763         if (!RNA_struct_property_is_set(op->ptr, "node")) {
764                 bNode *node = CTX_data_pointer_get_type(C, "node", &RNA_Node).data;
765                 if (!node)
766                         return 0;
767                 else
768                         RNA_string_set(op->ptr, "node", node->name);
769         }
770
771         if (!RNA_struct_property_is_set(op->ptr, "in_out"))
772                 RNA_enum_set(op->ptr, "in_out", SOCK_IN);
773
774         if (!RNA_struct_property_is_set(op->ptr, "socket"))
775                 RNA_int_set(op->ptr, "socket", 0);
776
777         return 1;
778 }
779
780 static void edit_node_properties_get(wmOperator *op, bNodeTree *ntree, bNode **rnode, bNodeSocket **rsock, int *rin_out)
781 {
782         bNode *node;
783         bNodeSocket *sock = NULL;
784         char nodename[MAX_NAME];
785         int sockindex;
786         int in_out;
787
788         RNA_string_get(op->ptr, "node", nodename);
789         node = nodeFindNodebyName(ntree, nodename);
790
791         in_out = RNA_enum_get(op->ptr, "in_out");
792
793         sockindex = RNA_int_get(op->ptr, "socket");
794         switch (in_out) {
795                 case SOCK_IN:   sock = BLI_findlink(&node->inputs, sockindex);  break;
796                 case SOCK_OUT:  sock = BLI_findlink(&node->outputs, sockindex); break;
797         }
798
799         if (rnode)
800                 *rnode = node;
801         if (rsock)
802                 *rsock = sock;
803         if (rin_out)
804                 *rin_out = in_out;
805 }
806 #endif
807
808 /* ************************** Node generic ************** */
809
810 /* is rct in visible part of node? */
811 static bNode *visible_node(SpaceNode *snode, const rctf *rct)
812 {
813         bNode *node;
814
815         for (node = snode->edittree->nodes.last; node; node = node->prev) {
816                 if (BLI_rctf_isect(&node->totr, rct, NULL))
817                         break;
818         }
819         return node;
820 }
821
822 /* ********************** size widget operator ******************** */
823
824 typedef struct NodeSizeWidget {
825         float mxstart, mystart;
826         float oldlocx, oldlocy;
827         float oldoffsetx, oldoffsety;
828         float oldwidth, oldheight;
829         float oldminiwidth;
830         int directions;
831 } NodeSizeWidget;
832
833 static void node_resize_init(bContext *C, wmOperator *op, const wmEvent *UNUSED(event), bNode *node, int dir)
834 {
835         SpaceNode *snode = CTX_wm_space_node(C);
836
837         NodeSizeWidget *nsw = MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
838
839         op->customdata = nsw;
840         nsw->mxstart = snode->cursor[0];
841         nsw->mystart = snode->cursor[1];
842
843         /* store old */
844         nsw->oldlocx = node->locx;
845         nsw->oldlocy = node->locy;
846         nsw->oldoffsetx = node->offsetx;
847         nsw->oldoffsety = node->offsety;
848         nsw->oldwidth = node->width;
849         nsw->oldheight = node->height;
850         nsw->oldminiwidth = node->miniwidth;
851         nsw->directions = dir;
852
853         WM_cursor_modal_set(CTX_wm_window(C), node_get_resize_cursor(dir));
854         /* add modal handler */
855         WM_event_add_modal_handler(C, op);
856 }
857
858 static void node_resize_exit(bContext *C, wmOperator *op, bool UNUSED(cancel))
859 {
860         WM_cursor_modal_restore(CTX_wm_window(C));
861
862         MEM_freeN(op->customdata);
863         op->customdata = NULL;
864 }
865
866 static int node_resize_modal(bContext *C, wmOperator *op, const wmEvent *event)
867 {
868         SpaceNode *snode = CTX_wm_space_node(C);
869         ARegion *ar = CTX_wm_region(C);
870         bNode *node = nodeGetActive(snode->edittree);
871         NodeSizeWidget *nsw = op->customdata;
872         float mx, my, dx, dy;
873
874         switch (event->type) {
875                 case MOUSEMOVE:
876
877                         UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &mx, &my);
878                         dx = (mx - nsw->mxstart) / UI_DPI_FAC;
879                         dy = (my - nsw->mystart) / UI_DPI_FAC;
880
881                         if (node) {
882                                 /* width can use node->width or node->miniwidth (hidden nodes) */
883                                 float *pwidth;
884                                 float oldwidth, widthmin, widthmax;
885                                 /* ignore hidden flag for frame nodes */
886                                 bool use_hidden = (node->type != NODE_FRAME);
887                                 if (use_hidden && node->flag & NODE_HIDDEN) {
888                                         pwidth = &node->miniwidth;
889                                         oldwidth = nsw->oldminiwidth;
890                                         widthmin = 0.0f;
891                                 }
892                                 else {
893                                         pwidth = &node->width;
894                                         oldwidth = nsw->oldwidth;
895                                         widthmin = node->typeinfo->minwidth;
896                                 }
897                                 widthmax = node->typeinfo->maxwidth;
898
899                                 {
900                                         if (nsw->directions & NODE_RESIZE_RIGHT) {
901                                                 *pwidth = oldwidth + dx;
902                                                 CLAMP(*pwidth, widthmin, widthmax);
903                                         }
904                                         if (nsw->directions & NODE_RESIZE_LEFT) {
905                                                 float locmax = nsw->oldlocx + oldwidth;
906
907                                                 node->locx = nsw->oldlocx + dx;
908                                                 CLAMP(node->locx, locmax - widthmax, locmax - widthmin);
909                                                 *pwidth = locmax - node->locx;
910                                         }
911                                 }
912
913                                 /* height works the other way round ... */
914                                 {
915                                         float heightmin = UI_DPI_FAC * node->typeinfo->minheight;
916                                         float heightmax = UI_DPI_FAC * node->typeinfo->maxheight;
917                                         if (nsw->directions & NODE_RESIZE_TOP) {
918                                                 float locmin = nsw->oldlocy - nsw->oldheight;
919
920                                                 node->locy = nsw->oldlocy + dy;
921                                                 CLAMP(node->locy, locmin + heightmin, locmin + heightmax);
922                                                 node->height = node->locy - locmin;
923                                         }
924                                         if (nsw->directions & NODE_RESIZE_BOTTOM) {
925                                                 node->height = nsw->oldheight - dy;
926                                                 CLAMP(node->height, heightmin, heightmax);
927                                         }
928                                 }
929
930                                 /* XXX make callback? */
931                                 if (node->type == NODE_FRAME) {
932                                         /* keep the offset symmetric around center point */
933                                         if (nsw->directions & NODE_RESIZE_LEFT) {
934                                                 node->locx = nsw->oldlocx + 0.5f * dx;
935                                                 node->offsetx = nsw->oldoffsetx + 0.5f * dx;
936                                         }
937                                         if (nsw->directions & NODE_RESIZE_RIGHT) {
938                                                 node->locx = nsw->oldlocx + 0.5f * dx;
939                                                 node->offsetx = nsw->oldoffsetx - 0.5f * dx;
940                                         }
941                                         if (nsw->directions & NODE_RESIZE_TOP) {
942                                                 node->locy = nsw->oldlocy + 0.5f * dy;
943                                                 node->offsety = nsw->oldoffsety + 0.5f * dy;
944                                         }
945                                         if (nsw->directions & NODE_RESIZE_BOTTOM) {
946                                                 node->locy = nsw->oldlocy + 0.5f * dy;
947                                                 node->offsety = nsw->oldoffsety - 0.5f * dy;
948                                         }
949                                 }
950                         }
951
952                         ED_region_tag_redraw(ar);
953
954                         break;
955
956                 case LEFTMOUSE:
957                 case MIDDLEMOUSE:
958                 case RIGHTMOUSE:
959
960                         node_resize_exit(C, op, false);
961                         ED_node_post_apply_transform(C, snode->edittree);
962
963                         return OPERATOR_FINISHED;
964         }
965
966         return OPERATOR_RUNNING_MODAL;
967 }
968
969 static int node_resize_invoke(bContext *C, wmOperator *op, const wmEvent *event)
970 {
971         SpaceNode *snode = CTX_wm_space_node(C);
972         ARegion *ar = CTX_wm_region(C);
973         bNode *node = nodeGetActive(snode->edittree);
974         int dir;
975
976         if (node) {
977                 /* convert mouse coordinates to v2d space */
978                 UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1],
979                                          &snode->cursor[0], &snode->cursor[1]);
980                 dir = node->typeinfo->resize_area_func(node, snode->cursor[0], snode->cursor[1]);
981                 if (dir != 0) {
982                         node_resize_init(C, op, event, node, dir);
983                         return OPERATOR_RUNNING_MODAL;
984                 }
985         }
986         return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;
987 }
988
989 static void node_resize_cancel(bContext *C, wmOperator *op)
990 {
991         node_resize_exit(C, op, true);
992 }
993
994 void NODE_OT_resize(wmOperatorType *ot)
995 {
996         /* identifiers */
997         ot->name = "Resize Node";
998         ot->idname = "NODE_OT_resize";
999         ot->description = "Resize a node";
1000
1001         /* api callbacks */
1002         ot->invoke = node_resize_invoke;
1003         ot->modal = node_resize_modal;
1004         ot->poll = ED_operator_node_active;
1005         ot->cancel = node_resize_cancel;
1006
1007         /* flags */
1008         ot->flag = OPTYPE_BLOCKING;
1009 }
1010
1011
1012 /* ********************** hidden sockets ******************** */
1013
1014 int node_has_hidden_sockets(bNode *node)
1015 {
1016         bNodeSocket *sock;
1017
1018         for (sock = node->inputs.first; sock; sock = sock->next)
1019                 if (sock->flag & SOCK_HIDDEN)
1020                         return 1;
1021         for (sock = node->outputs.first; sock; sock = sock->next)
1022                 if (sock->flag & SOCK_HIDDEN)
1023                         return 1;
1024         return 0;
1025 }
1026
1027 void node_set_hidden_sockets(SpaceNode *snode, bNode *node, int set)
1028 {
1029         bNodeSocket *sock;
1030
1031         if (set == 0) {
1032                 for (sock = node->inputs.first; sock; sock = sock->next)
1033                         sock->flag &= ~SOCK_HIDDEN;
1034                 for (sock = node->outputs.first; sock; sock = sock->next)
1035                         sock->flag &= ~SOCK_HIDDEN;
1036         }
1037         else {
1038                 /* hide unused sockets */
1039                 for (sock = node->inputs.first; sock; sock = sock->next) {
1040                         if (sock->link == NULL)
1041                                 sock->flag |= SOCK_HIDDEN;
1042                 }
1043                 for (sock = node->outputs.first; sock; sock = sock->next) {
1044                         if (nodeCountSocketLinks(snode->edittree, sock) == 0)
1045                                 sock->flag |= SOCK_HIDDEN;
1046                 }
1047         }
1048 }
1049
1050
1051 /* checks snode->mouse position, and returns found node/socket */
1052 /* type is SOCK_IN and/or SOCK_OUT */
1053 int node_find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, float cursor[2], int in_out)
1054 {
1055         bNode *node;
1056         bNodeSocket *sock;
1057         rctf rect;
1058
1059         *nodep = NULL;
1060         *sockp = NULL;
1061
1062         /* check if we click in a socket */
1063         for (node = snode->edittree->nodes.first; node; node = node->next) {
1064
1065                 BLI_rctf_init_pt_radius(&rect, cursor, NODE_SOCKSIZE + 4);
1066
1067                 if (!(node->flag & NODE_HIDDEN)) {
1068                         /* extra padding inside and out - allow dragging on the text areas too */
1069                         if (in_out == SOCK_IN) {
1070                                 rect.xmax += NODE_SOCKSIZE;
1071                                 rect.xmin -= NODE_SOCKSIZE * 4;
1072                         }
1073                         else if (in_out == SOCK_OUT) {
1074                                 rect.xmax += NODE_SOCKSIZE * 4;
1075                                 rect.xmin -= NODE_SOCKSIZE;
1076                         }
1077                 }
1078
1079                 if (in_out & SOCK_IN) {
1080                         for (sock = node->inputs.first; sock; sock = sock->next) {
1081                                 if (!nodeSocketIsHidden(sock)) {
1082                                         if (BLI_rctf_isect_pt(&rect, sock->locx, sock->locy)) {
1083                                                 if (node == visible_node(snode, &rect)) {
1084                                                         *nodep = node;
1085                                                         *sockp = sock;
1086                                                         return 1;
1087                                                 }
1088                                         }
1089                                 }
1090                         }
1091                 }
1092                 if (in_out & SOCK_OUT) {
1093                         for (sock = node->outputs.first; sock; sock = sock->next) {
1094                                 if (!nodeSocketIsHidden(sock)) {
1095                                         if (BLI_rctf_isect_pt(&rect, sock->locx, sock->locy)) {
1096                                                 if (node == visible_node(snode, &rect)) {
1097                                                         *nodep = node;
1098                                                         *sockp = sock;
1099                                                         return 1;
1100                                                 }
1101                                         }
1102                                 }
1103                         }
1104                 }
1105         }
1106
1107         return 0;
1108 }
1109
1110 /* ****************** Duplicate *********************** */
1111
1112 static void node_duplicate_reparent_recursive(bNode *node)
1113 {
1114         bNode *parent;
1115
1116         node->flag |= NODE_TEST;
1117
1118         /* find first selected parent */
1119         for (parent = node->parent; parent; parent = parent->parent) {
1120                 if (parent->flag & SELECT) {
1121                         if (!(parent->flag & NODE_TEST))
1122                                 node_duplicate_reparent_recursive(parent);
1123                         break;
1124                 }
1125         }
1126         /* reparent node copy to parent copy */
1127         if (parent) {
1128                 nodeDetachNode(node->new_node);
1129                 nodeAttachNode(node->new_node, parent->new_node);
1130         }
1131 }
1132
1133 static int node_duplicate_exec(bContext *C, wmOperator *op)
1134 {
1135         SpaceNode *snode = CTX_wm_space_node(C);
1136         bNodeTree *ntree = snode->edittree;
1137         bNode *node, *newnode, *lastnode;
1138         bNodeLink *link, *newlink, *lastlink;
1139         const bool keep_inputs = RNA_boolean_get(op->ptr, "keep_inputs");
1140         bool do_tag_update = false;
1141
1142         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1143
1144         lastnode = ntree->nodes.last;
1145         for (node = ntree->nodes.first; node; node = node->next) {
1146                 if (node->flag & SELECT) {
1147                         newnode = nodeCopyNode(ntree, node);
1148
1149                         if (newnode->id) {
1150                                 /* simple id user adjustment, node internal functions don't touch this
1151                                  * but operators and readfile.c do. */
1152                                 id_us_plus(newnode->id);
1153                                 /* to ensure redraws or rerenders happen */
1154                                 ED_node_tag_update_id(snode->id);
1155                         }
1156                 }
1157
1158                 /* make sure we don't copy new nodes again! */
1159                 if (node == lastnode)
1160                         break;
1161         }
1162
1163         /* copy links between selected nodes
1164          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
1165          */
1166         lastlink = ntree->links.last;
1167         for (link = ntree->links.first; link; link = link->next) {
1168                 /* This creates new links between copied nodes.
1169                  * If keep_inputs is set, also copies input links from unselected (when fromnode==NULL)!
1170                  */
1171                 if (link->tonode && (link->tonode->flag & NODE_SELECT) &&
1172                     (keep_inputs || (link->fromnode && (link->fromnode->flag & NODE_SELECT))))
1173                 {
1174                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
1175                         newlink->flag = link->flag;
1176                         newlink->tonode = link->tonode->new_node;
1177                         newlink->tosock = link->tosock->new_sock;
1178                         if (link->fromnode && (link->fromnode->flag & NODE_SELECT)) {
1179                                 newlink->fromnode = link->fromnode->new_node;
1180                                 newlink->fromsock = link->fromsock->new_sock;
1181                         }
1182                         else {
1183                                 /* input node not copied, this keeps the original input linked */
1184                                 newlink->fromnode = link->fromnode;
1185                                 newlink->fromsock = link->fromsock;
1186                         }
1187
1188                         BLI_addtail(&ntree->links, newlink);
1189                 }
1190
1191                 /* make sure we don't copy new links again! */
1192                 if (link == lastlink)
1193                         break;
1194         }
1195
1196         /* clear flags for recursive depth-first iteration */
1197         for (node = ntree->nodes.first; node; node = node->next)
1198                 node->flag &= ~NODE_TEST;
1199         /* reparent copied nodes */
1200         for (node = ntree->nodes.first; node; node = node->next) {
1201                 if ((node->flag & SELECT) && !(node->flag & NODE_TEST))
1202                         node_duplicate_reparent_recursive(node);
1203
1204                 /* only has to check old nodes */
1205                 if (node == lastnode)
1206                         break;
1207         }
1208
1209         /* deselect old nodes, select the copies instead */
1210         for (node = ntree->nodes.first; node; node = node->next) {
1211                 if (node->flag & SELECT) {
1212                         /* has been set during copy above */
1213                         newnode = node->new_node;
1214
1215                         nodeSetSelected(node, false);
1216                         node->flag &= ~NODE_ACTIVE;
1217                         nodeSetSelected(newnode, true);
1218
1219                         do_tag_update |= (do_tag_update || node_connected_to_output(ntree, newnode));
1220                 }
1221
1222                 /* make sure we don't copy new nodes again! */
1223                 if (node == lastnode)
1224                         break;
1225         }
1226
1227         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1228
1229         snode_notify(C, snode);
1230         if (do_tag_update) {
1231                 snode_dag_update(C, snode);
1232         }
1233
1234         return OPERATOR_FINISHED;
1235 }
1236
1237 void NODE_OT_duplicate(wmOperatorType *ot)
1238 {
1239         /* identifiers */
1240         ot->name = "Duplicate Nodes";
1241         ot->description = "Duplicate selected nodes";
1242         ot->idname = "NODE_OT_duplicate";
1243
1244         /* api callbacks */
1245         ot->exec = node_duplicate_exec;
1246         ot->poll = ED_operator_node_editable;
1247
1248         /* flags */
1249         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1250
1251         RNA_def_boolean(ot->srna, "keep_inputs", 0, "Keep Inputs", "Keep the input links to duplicated nodes");
1252 }
1253
1254 bool ED_node_select_check(ListBase *lb)
1255
1256
1257 {
1258         bNode *node;
1259
1260         for (node = lb->first; node; node = node->next) {
1261                 if (node->flag & NODE_SELECT) {
1262                         return true;
1263                 }
1264         }
1265
1266         return false;
1267 }
1268
1269 /* ******************************** */
1270 // XXX some code needing updating to operators...
1271
1272
1273 /* goes over all scenes, reads render layers */
1274 static int node_read_renderlayers_exec(bContext *C, wmOperator *UNUSED(op))
1275 {
1276         Main *bmain = CTX_data_main(C);
1277         SpaceNode *snode = CTX_wm_space_node(C);
1278         Scene *curscene = CTX_data_scene(C), *scene;
1279         bNode *node;
1280
1281         ED_preview_kill_jobs(CTX_wm_manager(C), bmain);
1282
1283         /* first tag scenes unread */
1284         for (scene = bmain->scene.first; scene; scene = scene->id.next)
1285                 scene->id.tag |= LIB_TAG_DOIT;
1286
1287         for (node = snode->edittree->nodes.first; node; node = node->next) {
1288                 if (node->type == CMP_NODE_R_LAYERS) {
1289                         ID *id = node->id;
1290                         if (id->tag & LIB_TAG_DOIT) {
1291                                 RE_ReadRenderResult(curscene, (Scene *)id);
1292                                 ntreeCompositTagRender((Scene *)id);
1293                                 id->tag &= ~LIB_TAG_DOIT;
1294                         }
1295                 }
1296         }
1297
1298         snode_notify(C, snode);
1299         snode_dag_update(C, snode);
1300
1301         return OPERATOR_FINISHED;
1302 }
1303
1304 void NODE_OT_read_renderlayers(wmOperatorType *ot)
1305 {
1306
1307         ot->name = "Read Render Layers";
1308         ot->idname = "NODE_OT_read_renderlayers";
1309         ot->description = "Read all render layers of all used scenes";
1310
1311         ot->exec = node_read_renderlayers_exec;
1312
1313         ot->poll = composite_node_active;
1314
1315         /* flags */
1316         ot->flag = 0;
1317 }
1318
1319 static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
1320 {
1321         Main *bmain = CTX_data_main(C);
1322         SpaceNode *snode = CTX_wm_space_node(C);
1323         Scene *curscene = CTX_data_scene(C);
1324         Render *re = RE_NewSceneRender(curscene);
1325
1326         WM_cursor_wait(1);
1327         RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
1328         WM_cursor_wait(0);
1329
1330         /* note we are careful to send the right notifier, as otherwise the
1331          * compositor would reexecute and overwrite the full sample result */
1332         WM_event_add_notifier(C, NC_SCENE | ND_COMPO_RESULT, NULL);
1333
1334         return OPERATOR_FINISHED;
1335 }
1336
1337
1338 void NODE_OT_read_fullsamplelayers(wmOperatorType *ot)
1339 {
1340
1341         ot->name = "Read Full Sample Layers";
1342         ot->idname = "NODE_OT_read_fullsamplelayers";
1343         ot->description = "Read all render layers of current scene, in full sample";
1344
1345         ot->exec = node_read_fullsamplelayers_exec;
1346
1347         ot->poll = composite_node_active;
1348
1349         /* flags */
1350         ot->flag = 0;
1351 }
1352
1353 int node_render_changed_exec(bContext *C, wmOperator *UNUSED(op))
1354 {
1355         Scene *sce = CTX_data_scene(C);
1356         bNode *node;
1357
1358         for (node = sce->nodetree->nodes.first; node; node = node->next) {
1359                 if (node->id == (ID *)sce && node->need_exec) {
1360                         break;
1361                 }
1362         }
1363         if (node) {
1364                 SceneRenderLayer *srl = BLI_findlink(&sce->r.layers, node->custom1);
1365
1366                 if (srl) {
1367                         PointerRNA op_ptr;
1368
1369                         WM_operator_properties_create(&op_ptr, "RENDER_OT_render");
1370                         RNA_string_set(&op_ptr, "layer", srl->name);
1371                         RNA_string_set(&op_ptr, "scene", sce->id.name + 2);
1372
1373                         /* to keep keypositions */
1374                         sce->r.scemode |= R_NO_FRAME_UPDATE;
1375
1376                         WM_operator_name_call(C, "RENDER_OT_render", WM_OP_INVOKE_DEFAULT, &op_ptr);
1377
1378                         WM_operator_properties_free(&op_ptr);
1379
1380                         return OPERATOR_FINISHED;
1381                 }
1382         }
1383         return OPERATOR_CANCELLED;
1384 }
1385
1386 void NODE_OT_render_changed(wmOperatorType *ot)
1387 {
1388         ot->name = "Render Changed Layer";
1389         ot->idname = "NODE_OT_render_changed";
1390         ot->description = "Render current scene, when input node's layer has been changed";
1391
1392         ot->exec = node_render_changed_exec;
1393
1394         ot->poll = composite_node_active;
1395
1396         /* flags */
1397         ot->flag = 0;
1398 }
1399
1400
1401 /* ****************** Hide operator *********************** */
1402
1403 static void node_flag_toggle_exec(SpaceNode *snode, int toggle_flag)
1404 {
1405         bNode *node;
1406         int tot_eq = 0, tot_neq = 0;
1407
1408         /* Toggles the flag on all selected nodes.
1409          * If the flag is set on all nodes it is unset.
1410          * If the flag is not set on all nodes, it is set.
1411          */
1412         for (node = snode->edittree->nodes.first; node; node = node->next) {
1413                 if (node->flag & SELECT) {
1414
1415                         if (toggle_flag == NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW) == 0)
1416                                 continue;
1417                         if (toggle_flag == NODE_OPTIONS && !(node->typeinfo->draw_buttons || node->typeinfo->draw_buttons_ex))
1418                                 continue;
1419
1420                         if (node->flag & toggle_flag)
1421                                 tot_eq++;
1422                         else
1423                                 tot_neq++;
1424                 }
1425         }
1426         for (node = snode->edittree->nodes.first; node; node = node->next) {
1427                 if (node->flag & SELECT) {
1428
1429                         if (toggle_flag == NODE_PREVIEW && (node->typeinfo->flag & NODE_PREVIEW) == 0)
1430                                 continue;
1431                         if (toggle_flag == NODE_OPTIONS && !(node->typeinfo->draw_buttons || node->typeinfo->draw_buttons_ex))
1432                                 continue;
1433
1434                         if ((tot_eq && tot_neq) || tot_eq == 0)
1435                                 node->flag |= toggle_flag;
1436                         else
1437                                 node->flag &= ~toggle_flag;
1438                 }
1439         }
1440 }
1441
1442 static int node_hide_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1443 {
1444         SpaceNode *snode = CTX_wm_space_node(C);
1445
1446         /* sanity checking (poll callback checks this already) */
1447         if ((snode == NULL) || (snode->edittree == NULL))
1448                 return OPERATOR_CANCELLED;
1449
1450         node_flag_toggle_exec(snode, NODE_HIDDEN);
1451
1452         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1453
1454         return OPERATOR_FINISHED;
1455 }
1456
1457 void NODE_OT_hide_toggle(wmOperatorType *ot)
1458 {
1459         /* identifiers */
1460         ot->name = "Hide";
1461         ot->description = "Toggle hiding of selected nodes";
1462         ot->idname = "NODE_OT_hide_toggle";
1463
1464         /* callbacks */
1465         ot->exec = node_hide_toggle_exec;
1466         ot->poll = ED_operator_node_active;
1467
1468         /* flags */
1469         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1470 }
1471
1472 static int node_preview_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1473 {
1474         SpaceNode *snode = CTX_wm_space_node(C);
1475
1476         /* sanity checking (poll callback checks this already) */
1477         if ((snode == NULL) || (snode->edittree == NULL))
1478                 return OPERATOR_CANCELLED;
1479
1480         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1481
1482         node_flag_toggle_exec(snode, NODE_PREVIEW);
1483
1484         snode_notify(C, snode);
1485
1486         return OPERATOR_FINISHED;
1487 }
1488
1489 void NODE_OT_preview_toggle(wmOperatorType *ot)
1490 {
1491         /* identifiers */
1492         ot->name = "Toggle Node Preview";
1493         ot->description = "Toggle preview display for selected nodes";
1494         ot->idname = "NODE_OT_preview_toggle";
1495
1496         /* callbacks */
1497         ot->exec = node_preview_toggle_exec;
1498         ot->poll = ED_operator_node_active;
1499
1500         /* flags */
1501         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1502 }
1503
1504 static int node_options_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1505 {
1506         SpaceNode *snode = CTX_wm_space_node(C);
1507
1508         /* sanity checking (poll callback checks this already) */
1509         if ((snode == NULL) || (snode->edittree == NULL))
1510                 return OPERATOR_CANCELLED;
1511
1512         node_flag_toggle_exec(snode, NODE_OPTIONS);
1513
1514         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1515
1516         return OPERATOR_FINISHED;
1517 }
1518
1519 void NODE_OT_options_toggle(wmOperatorType *ot)
1520 {
1521         /* identifiers */
1522         ot->name = "Toggle Node Options";
1523         ot->description = "Toggle option buttons display for selected nodes";
1524         ot->idname = "NODE_OT_options_toggle";
1525
1526         /* callbacks */
1527         ot->exec = node_options_toggle_exec;
1528         ot->poll = ED_operator_node_active;
1529
1530         /* flags */
1531         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1532 }
1533
1534 static int node_socket_toggle_exec(bContext *C, wmOperator *UNUSED(op))
1535 {
1536         SpaceNode *snode = CTX_wm_space_node(C);
1537         bNode *node;
1538         int hidden;
1539
1540         /* sanity checking (poll callback checks this already) */
1541         if ((snode == NULL) || (snode->edittree == NULL))
1542                 return OPERATOR_CANCELLED;
1543
1544         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1545
1546         /* Toggle for all selected nodes */
1547         hidden = 0;
1548         for (node = snode->edittree->nodes.first; node; node = node->next) {
1549                 if (node->flag & SELECT) {
1550                         if (node_has_hidden_sockets(node)) {
1551                                 hidden = 1;
1552                                 break;
1553                         }
1554                 }
1555         }
1556
1557         for (node = snode->edittree->nodes.first; node; node = node->next) {
1558                 if (node->flag & SELECT) {
1559                         node_set_hidden_sockets(snode, node, !hidden);
1560                 }
1561         }
1562
1563         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1564
1565         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1566
1567         return OPERATOR_FINISHED;
1568 }
1569
1570 void NODE_OT_hide_socket_toggle(wmOperatorType *ot)
1571 {
1572         /* identifiers */
1573         ot->name = "Toggle Hidden Node Sockets";
1574         ot->description = "Toggle unused node socket display";
1575         ot->idname = "NODE_OT_hide_socket_toggle";
1576
1577         /* callbacks */
1578         ot->exec = node_socket_toggle_exec;
1579         ot->poll = ED_operator_node_active;
1580
1581         /* flags */
1582         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1583 }
1584
1585 /* ****************** Mute operator *********************** */
1586
1587 static int node_mute_exec(bContext *C, wmOperator *UNUSED(op))
1588 {
1589         SpaceNode *snode = CTX_wm_space_node(C);
1590         bNode *node;
1591         bool do_tag_update = false;
1592
1593         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1594
1595         for (node = snode->edittree->nodes.first; node; node = node->next) {
1596                 /* Only allow muting of nodes having a mute func! */
1597                 if ((node->flag & SELECT) && node->typeinfo->update_internal_links) {
1598                         node->flag ^= NODE_MUTED;
1599                         snode_update(snode, node);
1600                         do_tag_update |= (do_tag_update || node_connected_to_output(snode->edittree, node));
1601                 }
1602         }
1603
1604         snode_notify(C, snode);
1605         if (do_tag_update) {
1606                 snode_dag_update(C, snode);
1607         }
1608
1609         return OPERATOR_FINISHED;
1610 }
1611
1612 void NODE_OT_mute_toggle(wmOperatorType *ot)
1613 {
1614         /* identifiers */
1615         ot->name = "Toggle Node Mute";
1616         ot->description = "Toggle muting of the nodes";
1617         ot->idname = "NODE_OT_mute_toggle";
1618
1619         /* callbacks */
1620         ot->exec = node_mute_exec;
1621         ot->poll = ED_operator_node_editable;
1622
1623         /* flags */
1624         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1625 }
1626
1627 /* ****************** Delete operator ******************* */
1628
1629 static int node_delete_exec(bContext *C, wmOperator *UNUSED(op))
1630 {
1631         SpaceNode *snode = CTX_wm_space_node(C);
1632         bNode *node, *next;
1633         bool do_tag_update = false;
1634
1635         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1636
1637         for (node = snode->edittree->nodes.first; node; node = next) {
1638                 next = node->next;
1639                 if (node->flag & SELECT) {
1640                         /* check id user here, nodeFreeNode is called for free dbase too */
1641                         do_tag_update |= (do_tag_update || node_connected_to_output(snode->edittree, node));
1642                         if (node->id)
1643                                 id_us_min(node->id);
1644                         nodeFreeNode(snode->edittree, node);
1645                 }
1646         }
1647
1648         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1649
1650         snode_notify(C, snode);
1651         if (do_tag_update) {
1652                 snode_dag_update(C, snode);
1653         }
1654
1655         return OPERATOR_FINISHED;
1656 }
1657
1658 void NODE_OT_delete(wmOperatorType *ot)
1659 {
1660         /* identifiers */
1661         ot->name = "Delete";
1662         ot->description = "Delete selected nodes";
1663         ot->idname = "NODE_OT_delete";
1664
1665         /* api callbacks */
1666         ot->exec = node_delete_exec;
1667         ot->poll = ED_operator_node_editable;
1668
1669         /* flags */
1670         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1671 }
1672
1673 /* ****************** Switch View ******************* */
1674
1675 static int node_switch_view_poll(bContext *C)
1676 {
1677         SpaceNode *snode = CTX_wm_space_node(C);
1678
1679         if (snode && snode->edittree)
1680                 return true;
1681
1682         return false;
1683 }
1684
1685 static int node_switch_view_exec(bContext *C, wmOperator *UNUSED(op))
1686 {
1687         SpaceNode *snode = CTX_wm_space_node(C);
1688         bNode *node, *next;
1689
1690         for (node = snode->edittree->nodes.first; node; node = next) {
1691                 next = node->next;
1692                 if (node->flag & SELECT) {
1693                         /* call the update function from the Switch View node */
1694                         node->update = NODE_UPDATE_OPERATOR;
1695                 }
1696         }
1697
1698         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1699
1700         snode_notify(C, snode);
1701         snode_dag_update(C, snode);
1702
1703         return OPERATOR_FINISHED;
1704 }
1705
1706 void NODE_OT_switch_view_update(wmOperatorType *ot)
1707 {
1708         /* identifiers */
1709         ot->name = "Update Views";
1710         ot->description = "Update views of selected node";
1711         ot->idname = "NODE_OT_switch_view_update";
1712
1713         /* api callbacks */
1714         ot->exec = node_switch_view_exec;
1715         ot->poll = node_switch_view_poll;
1716
1717         /* flags */
1718         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1719 }
1720
1721 /* ****************** Delete with reconnect ******************* */
1722 static int node_delete_reconnect_exec(bContext *C, wmOperator *UNUSED(op))
1723 {
1724         SpaceNode *snode = CTX_wm_space_node(C);
1725         bNode *node, *next;
1726
1727         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1728
1729         for (node = snode->edittree->nodes.first; node; node = next) {
1730                 next = node->next;
1731                 if (node->flag & SELECT) {
1732                         nodeInternalRelink(snode->edittree, node);
1733
1734                         /* check id user here, nodeFreeNode is called for free dbase too */
1735                         if (node->id)
1736                                 id_us_min(node->id);
1737                         nodeFreeNode(snode->edittree, node);
1738                 }
1739         }
1740
1741         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
1742
1743         snode_notify(C, snode);
1744         snode_dag_update(C, snode);
1745
1746         return OPERATOR_FINISHED;
1747 }
1748
1749 void NODE_OT_delete_reconnect(wmOperatorType *ot)
1750 {
1751         /* identifiers */
1752         ot->name = "Delete with Reconnect";
1753         ot->description = "Delete nodes; will reconnect nodes as if deletion was muted";
1754         ot->idname = "NODE_OT_delete_reconnect";
1755
1756         /* api callbacks */
1757         ot->exec = node_delete_reconnect_exec;
1758         ot->poll = ED_operator_node_editable;
1759
1760         /* flags */
1761         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1762 }
1763
1764
1765 /* ****************** File Output Add Socket  ******************* */
1766
1767 static int node_output_file_add_socket_exec(bContext *C, wmOperator *op)
1768 {
1769         Scene *scene = CTX_data_scene(C);
1770         SpaceNode *snode = CTX_wm_space_node(C);
1771         PointerRNA ptr = CTX_data_pointer_get(C, "node");
1772         bNodeTree *ntree = NULL;
1773         bNode *node = NULL;
1774         char file_path[MAX_NAME];
1775
1776         if (ptr.data) {
1777                 node = ptr.data;
1778                 ntree = ptr.id.data;
1779         }
1780         else if (snode && snode->edittree) {
1781                 ntree = snode->edittree;
1782                 node = nodeGetActive(snode->edittree);
1783         }
1784
1785         if (!node || node->type != CMP_NODE_OUTPUT_FILE)
1786                 return OPERATOR_CANCELLED;
1787
1788         RNA_string_get(op->ptr, "file_path", file_path);
1789         ntreeCompositOutputFileAddSocket(ntree, node, file_path, &scene->r.im_format);
1790
1791         snode_notify(C, snode);
1792
1793         return OPERATOR_FINISHED;
1794 }
1795
1796 void NODE_OT_output_file_add_socket(wmOperatorType *ot)
1797 {
1798         /* identifiers */
1799         ot->name = "Add File Node Socket";
1800         ot->description = "Add a new input to a file output node";
1801         ot->idname = "NODE_OT_output_file_add_socket";
1802
1803         /* callbacks */
1804         ot->exec = node_output_file_add_socket_exec;
1805         ot->poll = composite_node_editable;
1806
1807         /* flags */
1808         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1809
1810         RNA_def_string(ot->srna, "file_path", "Image", MAX_NAME, "File Path", "Sub-path of the output file");
1811 }
1812
1813 /* ****************** Multi File Output Remove Socket  ******************* */
1814
1815 static int node_output_file_remove_active_socket_exec(bContext *C, wmOperator *UNUSED(op))
1816 {
1817         SpaceNode *snode = CTX_wm_space_node(C);
1818         PointerRNA ptr = CTX_data_pointer_get(C, "node");
1819         bNodeTree *ntree = NULL;
1820         bNode *node = NULL;
1821
1822         if (ptr.data) {
1823                 node = ptr.data;
1824                 ntree = ptr.id.data;
1825         }
1826         else if (snode && snode->edittree) {
1827                 ntree = snode->edittree;
1828                 node = nodeGetActive(snode->edittree);
1829         }
1830
1831         if (!node || node->type != CMP_NODE_OUTPUT_FILE)
1832                 return OPERATOR_CANCELLED;
1833
1834         if (!ntreeCompositOutputFileRemoveActiveSocket(ntree, node))
1835                 return OPERATOR_CANCELLED;
1836
1837         snode_notify(C, snode);
1838
1839         return OPERATOR_FINISHED;
1840 }
1841
1842 void NODE_OT_output_file_remove_active_socket(wmOperatorType *ot)
1843 {
1844         /* identifiers */
1845         ot->name = "Remove File Node Socket";
1846         ot->description = "Remove active input from a file output node";
1847         ot->idname = "NODE_OT_output_file_remove_active_socket";
1848
1849         /* callbacks */
1850         ot->exec = node_output_file_remove_active_socket_exec;
1851         ot->poll = composite_node_editable;
1852
1853         /* flags */
1854         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1855 }
1856
1857 /* ****************** Multi File Output Move Socket  ******************* */
1858
1859 static int node_output_file_move_active_socket_exec(bContext *C, wmOperator *op)
1860 {
1861         SpaceNode *snode = CTX_wm_space_node(C);
1862         PointerRNA ptr = CTX_data_pointer_get(C, "node");
1863         bNode *node = NULL;
1864         NodeImageMultiFile *nimf;
1865         bNodeSocket *sock;
1866         int direction;
1867
1868         if (ptr.data)
1869                 node = ptr.data;
1870         else if (snode && snode->edittree)
1871                 node = nodeGetActive(snode->edittree);
1872
1873         if (!node || node->type != CMP_NODE_OUTPUT_FILE)
1874                 return OPERATOR_CANCELLED;
1875
1876         nimf = node->storage;
1877
1878         sock = BLI_findlink(&node->inputs, nimf->active_input);
1879         if (!sock)
1880                 return OPERATOR_CANCELLED;
1881
1882         direction = RNA_enum_get(op->ptr, "direction");
1883
1884         if (direction == 1) {
1885                 bNodeSocket *before = sock->prev;
1886                 if (!before)
1887                         return OPERATOR_CANCELLED;
1888                 BLI_remlink(&node->inputs, sock);
1889                 BLI_insertlinkbefore(&node->inputs, before, sock);
1890                 nimf->active_input--;
1891         }
1892         else {
1893                 bNodeSocket *after = sock->next;
1894                 if (!after)
1895                         return OPERATOR_CANCELLED;
1896                 BLI_remlink(&node->inputs, sock);
1897                 BLI_insertlinkafter(&node->inputs, after, sock);
1898                 nimf->active_input++;
1899         }
1900
1901         snode_notify(C, snode);
1902
1903         return OPERATOR_FINISHED;
1904 }
1905
1906 void NODE_OT_output_file_move_active_socket(wmOperatorType *ot)
1907 {
1908         static const EnumPropertyItem direction_items[] = {
1909                 {1, "UP", 0, "Up", ""},
1910                 {2, "DOWN", 0, "Down", ""},
1911                 { 0, NULL, 0, NULL, NULL }
1912         };
1913
1914         /* identifiers */
1915         ot->name = "Move File Node Socket";
1916         ot->description = "Move the active input of a file output node up or down the list";
1917         ot->idname = "NODE_OT_output_file_move_active_socket";
1918
1919         /* callbacks */
1920         ot->exec = node_output_file_move_active_socket_exec;
1921         ot->poll = composite_node_editable;
1922
1923         /* flags */
1924         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1925
1926         RNA_def_enum(ot->srna, "direction", direction_items, 2, "Direction", "");
1927 }
1928
1929 /* ****************** Copy Node Color ******************* */
1930
1931 static int node_copy_color_exec(bContext *C, wmOperator *UNUSED(op))
1932 {
1933         SpaceNode *snode = CTX_wm_space_node(C);
1934         bNodeTree *ntree = snode->edittree;
1935         bNode *node, *tnode;
1936
1937         if (!ntree)
1938                 return OPERATOR_CANCELLED;
1939         node = nodeGetActive(ntree);
1940         if (!node)
1941                 return OPERATOR_CANCELLED;
1942
1943         for (tnode = ntree->nodes.first; tnode; tnode = tnode->next) {
1944                 if (tnode->flag & NODE_SELECT && tnode != node) {
1945                         if (node->flag & NODE_CUSTOM_COLOR) {
1946                                 tnode->flag |= NODE_CUSTOM_COLOR;
1947                                 copy_v3_v3(tnode->color, node->color);
1948                         }
1949                         else
1950                                 tnode->flag &= ~NODE_CUSTOM_COLOR;
1951                 }
1952         }
1953
1954         ED_node_sort(ntree);
1955         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
1956
1957         return OPERATOR_FINISHED;
1958 }
1959
1960 void NODE_OT_node_copy_color(wmOperatorType *ot)
1961 {
1962         /* identifiers */
1963         ot->name = "Copy Color";
1964         ot->description = "Copy color to all selected nodes";
1965         ot->idname = "NODE_OT_node_copy_color";
1966
1967         /* api callbacks */
1968         ot->exec = node_copy_color_exec;
1969         ot->poll = ED_operator_node_editable;
1970
1971         /* flags */
1972         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1973 }
1974
1975 /* ****************** Copy to clipboard ******************* */
1976
1977 static int node_clipboard_copy_exec(bContext *C, wmOperator *UNUSED(op))
1978 {
1979         SpaceNode *snode = CTX_wm_space_node(C);
1980         bNodeTree *ntree = snode->edittree;
1981         bNode *node;
1982         bNodeLink *link, *newlink;
1983
1984         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
1985
1986         /* clear current clipboard */
1987         BKE_node_clipboard_clear();
1988         BKE_node_clipboard_init(ntree);
1989
1990         for (node = ntree->nodes.first; node; node = node->next) {
1991                 if (node->flag & SELECT) {
1992                         bNode *new_node;
1993                         new_node = nodeCopyNode(NULL, node);
1994                         BKE_node_clipboard_add_node(new_node);
1995                 }
1996         }
1997
1998         for (node = ntree->nodes.first; node; node = node->next) {
1999                 if (node->flag & SELECT) {
2000                         bNode *new_node = node->new_node;
2001
2002                         /* ensure valid pointers */
2003                         if (new_node->parent) {
2004                                 /* parent pointer must be redirected to new node or detached if parent is not copied */
2005                                 if (new_node->parent->flag & NODE_SELECT) {
2006                                         new_node->parent = new_node->parent->new_node;
2007                                 }
2008                                 else {
2009                                         nodeDetachNode(new_node);
2010                                 }
2011                         }
2012                 }
2013         }
2014
2015         /* copy links between selected nodes
2016          * NB: this depends on correct node->new_node and sock->new_sock pointers from above copy!
2017          */
2018         for (link = ntree->links.first; link; link = link->next) {
2019                 /* This creates new links between copied nodes. */
2020                 if (link->tonode && (link->tonode->flag & NODE_SELECT) &&
2021                     link->fromnode && (link->fromnode->flag & NODE_SELECT))
2022                 {
2023                         newlink = MEM_callocN(sizeof(bNodeLink), "bNodeLink");
2024                         newlink->flag = link->flag;
2025                         newlink->tonode = link->tonode->new_node;
2026                         newlink->tosock = link->tosock->new_sock;
2027                         newlink->fromnode = link->fromnode->new_node;
2028                         newlink->fromsock = link->fromsock->new_sock;
2029
2030                         BKE_node_clipboard_add_link(newlink);
2031                 }
2032         }
2033
2034         return OPERATOR_FINISHED;
2035 }
2036
2037 void NODE_OT_clipboard_copy(wmOperatorType *ot)
2038 {
2039         /* identifiers */
2040         ot->name = "Copy to Clipboard";
2041         ot->description = "Copies selected nodes to the clipboard";
2042         ot->idname = "NODE_OT_clipboard_copy";
2043
2044         /* api callbacks */
2045         ot->exec = node_clipboard_copy_exec;
2046         ot->poll = ED_operator_node_active;
2047
2048         /* flags */
2049         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2050 }
2051
2052 /* ****************** Paste from clipboard ******************* */
2053
2054 static int node_clipboard_paste_exec(bContext *C, wmOperator *op)
2055 {
2056         SpaceNode *snode = CTX_wm_space_node(C);
2057         bNodeTree *ntree = snode->edittree;
2058         const ListBase *clipboard_nodes_lb;
2059         const ListBase *clipboard_links_lb;
2060         bNode *node;
2061         bNodeLink *link;
2062         int num_nodes;
2063         float center[2];
2064         bool is_clipboard_valid, all_nodes_valid;
2065
2066         /* validate pointers in the clipboard */
2067         is_clipboard_valid = BKE_node_clipboard_validate();
2068         clipboard_nodes_lb = BKE_node_clipboard_get_nodes();
2069         clipboard_links_lb = BKE_node_clipboard_get_links();
2070
2071         if (BLI_listbase_is_empty(clipboard_nodes_lb)) {
2072                 BKE_report(op->reports, RPT_ERROR, "Clipboard is empty");
2073                 return OPERATOR_CANCELLED;
2074         }
2075
2076         if (BKE_node_clipboard_get_type() != ntree->type) {
2077                 BKE_report(op->reports, RPT_ERROR, "Clipboard nodes are an incompatible type");
2078                 return OPERATOR_CANCELLED;
2079         }
2080
2081         /* only warn */
2082         if (is_clipboard_valid == false) {
2083                 BKE_report(op->reports, RPT_WARNING, "Some nodes references could not be restored, will be left empty");
2084         }
2085
2086         /* make sure all clipboard nodes would be valid in the target tree */
2087         all_nodes_valid = true;
2088         for (node = clipboard_nodes_lb->first; node; node = node->next) {
2089                 if (!node->typeinfo->poll_instance || !node->typeinfo->poll_instance(node, ntree)) {
2090                         all_nodes_valid = false;
2091                         BKE_reportf(op->reports, RPT_ERROR, "Cannot add node %s into node tree %s", node->name, ntree->id.name + 2);
2092                 }
2093         }
2094         if (!all_nodes_valid)
2095                 return OPERATOR_CANCELLED;
2096
2097         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
2098
2099         /* deselect old nodes */
2100         node_deselect_all(snode);
2101
2102         /* calculate "barycenter" for placing on mouse cursor */
2103         zero_v2(center);
2104         for (node = clipboard_nodes_lb->first, num_nodes = 0; node; node = node->next, num_nodes++) {
2105                 center[0] += BLI_rctf_cent_x(&node->totr);
2106                 center[1] += BLI_rctf_cent_y(&node->totr);
2107         }
2108         mul_v2_fl(center, 1.0 / num_nodes);
2109
2110         /* copy nodes from clipboard */
2111         for (node = clipboard_nodes_lb->first; node; node = node->next) {
2112                 bNode *new_node = nodeCopyNode(ntree, node);
2113
2114                 /* needed since nodeCopyNode() doesn't increase ID's */
2115                 id_us_plus(node->id);
2116
2117                 /* pasted nodes are selected */
2118                 nodeSetSelected(new_node, true);
2119         }
2120
2121         /* reparent copied nodes */
2122         for (node = clipboard_nodes_lb->first; node; node = node->next) {
2123                 bNode *new_node = node->new_node;
2124                 if (new_node->parent)
2125                         new_node->parent = new_node->parent->new_node;
2126         }
2127
2128         for (link = clipboard_links_lb->first; link; link = link->next) {
2129                 nodeAddLink(ntree, link->fromnode->new_node, link->fromsock->new_sock,
2130                             link->tonode->new_node, link->tosock->new_sock);
2131         }
2132
2133         ntreeUpdateTree(CTX_data_main(C), snode->edittree);
2134
2135         snode_notify(C, snode);
2136         snode_dag_update(C, snode);
2137
2138         return OPERATOR_FINISHED;
2139 }
2140
2141 void NODE_OT_clipboard_paste(wmOperatorType *ot)
2142 {
2143         /* identifiers */
2144         ot->name = "Paste from Clipboard";
2145         ot->description = "Pastes nodes from the clipboard to the active node tree";
2146         ot->idname = "NODE_OT_clipboard_paste";
2147
2148         /* api callbacks */
2149         ot->exec = node_clipboard_paste_exec;
2150         ot->poll = ED_operator_node_editable;
2151
2152         /* flags */
2153         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2154 }
2155
2156 /********************** Add interface socket operator *********************/
2157
2158 static bNodeSocket *ntree_get_active_interface_socket(ListBase *lb)
2159 {
2160         bNodeSocket *sock;
2161         for (sock = lb->first; sock; sock = sock->next)
2162                 if (sock->flag & SELECT)
2163                         return sock;
2164         return NULL;
2165 }
2166
2167 static int ntree_socket_add_exec(bContext *C, wmOperator *op)
2168 {
2169         SpaceNode *snode = CTX_wm_space_node(C);
2170         bNodeTree *ntree = snode->edittree;
2171         int in_out = RNA_enum_get(op->ptr, "in_out");
2172         PointerRNA ntree_ptr;
2173         bNodeSocket *sock, *tsock, *active_sock;
2174         const char *default_name;
2175
2176         RNA_id_pointer_create((ID *)ntree, &ntree_ptr);
2177
2178         if (in_out == SOCK_IN) {
2179                 active_sock = ntree_get_active_interface_socket(&ntree->inputs);
2180                 default_name = "Input";
2181         }
2182         else {
2183                 active_sock = ntree_get_active_interface_socket(&ntree->outputs);
2184                 default_name = "Output";
2185         }
2186
2187         if (active_sock) {
2188                 /* insert a copy of the active socket right after it */
2189                 sock = ntreeInsertSocketInterface(ntree, in_out, active_sock->idname, active_sock->next, active_sock->name);
2190                 /* XXX this only works for actual sockets, not interface templates! */
2191                 /*nodeSocketCopyValue(sock, &ntree_ptr, active_sock, &ntree_ptr);*/
2192         }
2193         else {
2194                 /* XXX TODO define default socket type for a tree! */
2195                 sock = ntreeAddSocketInterface(ntree, in_out, "NodeSocketFloat", default_name);
2196         }
2197
2198         /* deactivate sockets (has to check both lists) */
2199         for (tsock = ntree->inputs.first; tsock; tsock = tsock->next)
2200                 tsock->flag &= ~SELECT;
2201         for (tsock = ntree->outputs.first; tsock; tsock = tsock->next)
2202                 tsock->flag &= ~SELECT;
2203         /* make the new socket active */
2204         sock->flag |= SELECT;
2205
2206         ntreeUpdateTree(CTX_data_main(C), ntree);
2207
2208         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2209
2210         return OPERATOR_FINISHED;
2211 }
2212
2213 void NODE_OT_tree_socket_add(wmOperatorType *ot)
2214 {
2215         /* identifiers */
2216         ot->name = "Add Node Tree Interface Socket";
2217         ot->description = "Add an input or output socket to the current node tree";
2218         ot->idname = "NODE_OT_tree_socket_add";
2219
2220         /* api callbacks */
2221         ot->exec = ntree_socket_add_exec;
2222         ot->poll = ED_operator_node_editable;
2223
2224         /* flags */
2225         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2226
2227         RNA_def_enum(ot->srna, "in_out", rna_enum_node_socket_in_out_items, SOCK_IN, "Socket Type", "");
2228 }
2229
2230 /********************** Remove interface socket operator *********************/
2231
2232 static int ntree_socket_remove_exec(bContext *C, wmOperator *UNUSED(op))
2233 {
2234         SpaceNode *snode = CTX_wm_space_node(C);
2235         bNodeTree *ntree = snode->edittree;
2236         bNodeSocket *iosock, *active_sock;
2237
2238         iosock = ntree_get_active_interface_socket(&ntree->inputs);
2239         if (!iosock)
2240                 iosock = ntree_get_active_interface_socket(&ntree->outputs);
2241         if (!iosock)
2242                 return OPERATOR_CANCELLED;
2243
2244         /* preferably next socket becomes active, otherwise try previous socket */
2245         active_sock = (iosock->next ? iosock->next : iosock->prev);
2246         ntreeRemoveSocketInterface(ntree, iosock);
2247
2248         /* set active socket */
2249         if (active_sock)
2250                 active_sock->flag |= SELECT;
2251
2252         ntreeUpdateTree(CTX_data_main(C), ntree);
2253
2254         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2255
2256         return OPERATOR_FINISHED;
2257 }
2258
2259 void NODE_OT_tree_socket_remove(wmOperatorType *ot)
2260 {
2261         /* identifiers */
2262         ot->name = "Remove Node Tree Interface Socket";
2263         ot->description = "Remove an input or output socket to the current node tree";
2264         ot->idname = "NODE_OT_tree_socket_remove";
2265
2266         /* api callbacks */
2267         ot->exec = ntree_socket_remove_exec;
2268         ot->poll = ED_operator_node_editable;
2269
2270         /* flags */
2271         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2272 }
2273
2274 /********************** Move interface socket operator *********************/
2275
2276 static const EnumPropertyItem move_direction_items[] = {
2277         { 1, "UP", 0, "Up", "" },
2278         { 2, "DOWN", 0, "Down", "" },
2279         { 0, NULL, 0, NULL, NULL },
2280 };
2281
2282 static int ntree_socket_move_exec(bContext *C, wmOperator *op)
2283 {
2284         SpaceNode *snode = CTX_wm_space_node(C);
2285         bNodeTree *ntree = snode->edittree;
2286         int direction = RNA_enum_get(op->ptr, "direction");
2287         bNodeSocket *iosock;
2288         ListBase *lb;
2289
2290         lb = &ntree->inputs;
2291         iosock = ntree_get_active_interface_socket(lb);
2292         if (!iosock) {
2293                 lb = &ntree->outputs;
2294                 iosock = ntree_get_active_interface_socket(lb);
2295         }
2296         if (!iosock)
2297                 return OPERATOR_CANCELLED;
2298
2299         switch (direction) {
2300                 case 1:
2301                 {       /* up */
2302                         bNodeSocket *before = iosock->prev;
2303                         BLI_remlink(lb, iosock);
2304                         if (before)
2305                                 BLI_insertlinkbefore(lb, before, iosock);
2306                         else
2307                                 BLI_addhead(lb, iosock);
2308                         break;
2309                 }
2310                 case 2:
2311                 {       /* down */
2312                         bNodeSocket *after = iosock->next;
2313                         BLI_remlink(lb, iosock);
2314                         if (after)
2315                                 BLI_insertlinkafter(lb, after, iosock);
2316                         else
2317                                 BLI_addtail(lb, iosock);
2318                         break;
2319                 }
2320         }
2321
2322         ntreeUpdateTree(CTX_data_main(C), ntree);
2323
2324         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2325
2326         return OPERATOR_FINISHED;
2327 }
2328
2329 void NODE_OT_tree_socket_move(wmOperatorType *ot)
2330 {
2331         /* identifiers */
2332         ot->name = "Move Node Tree Socket";
2333         ot->description = "Move a socket up or down in the current node tree's sockets stack";
2334         ot->idname = "NODE_OT_tree_socket_move";
2335
2336         /* api callbacks */
2337         ot->exec = ntree_socket_move_exec;
2338         ot->poll = ED_operator_node_editable;
2339
2340         /* flags */
2341         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2342
2343         RNA_def_enum(ot->srna, "direction", move_direction_items, 1, "Direction", "");
2344 }
2345
2346 /* ********************** Shader Script Update ******************/
2347
2348 static int node_shader_script_update_poll(bContext *C)
2349 {
2350         Scene *scene = CTX_data_scene(C);
2351         RenderEngineType *type = RE_engines_find(scene->r.engine);
2352         SpaceNode *snode = CTX_wm_space_node(C);
2353         bNode *node;
2354         Text *text;
2355
2356         /* test if we have a render engine that supports shaders scripts */
2357         if (!(type && type->update_script_node))
2358                 return 0;
2359
2360         /* see if we have a shader script node in context */
2361         node = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript).data;
2362
2363         if (!node && snode && snode->edittree)
2364                 node = nodeGetActive(snode->edittree);
2365
2366         if (node && node->type == SH_NODE_SCRIPT) {
2367                 NodeShaderScript *nss = node->storage;
2368
2369                 if (node->id || nss->filepath[0]) {
2370                         return ED_operator_node_editable(C);
2371                 }
2372         }
2373
2374         /* see if we have a text datablock in context */
2375         text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
2376         if (text)
2377                 return 1;
2378
2379         /* we don't check if text datablock is actually in use, too slow for poll */
2380
2381         return 0;
2382 }
2383
2384 /* recursively check for script nodes in groups using this text and update */
2385 static bool node_shader_script_update_text_recursive(RenderEngine *engine, RenderEngineType *type, bNodeTree *ntree, Text *text)
2386 {
2387         bool found = false;
2388         bNode *node;
2389
2390         ntree->done = true;
2391
2392         /* update each script that is using this text datablock */
2393         for (node = ntree->nodes.first; node; node = node->next) {
2394                 if (node->type == NODE_GROUP) {
2395                         bNodeTree *ngroup = (bNodeTree *)node->id;
2396                         if (ngroup && !ngroup->done)
2397                                 found |= node_shader_script_update_text_recursive(engine, type, ngroup, text);
2398                 }
2399                 else if (node->type == SH_NODE_SCRIPT && node->id == &text->id) {
2400                         type->update_script_node(engine, ntree, node);
2401                         found = true;
2402                 }
2403         }
2404
2405         return found;
2406 }
2407
2408 static int node_shader_script_update_exec(bContext *C, wmOperator *op)
2409 {
2410         Main *bmain = CTX_data_main(C);
2411         Scene *scene = CTX_data_scene(C);
2412         SpaceNode *snode = CTX_wm_space_node(C);
2413         PointerRNA nodeptr = CTX_data_pointer_get_type(C, "node", &RNA_ShaderNodeScript);
2414         bNodeTree *ntree_base = NULL;
2415         bNode *node = NULL;
2416         RenderEngine *engine;
2417         RenderEngineType *type;
2418         bool found = false;
2419
2420         /* setup render engine */
2421         type = RE_engines_find(scene->r.engine);
2422         engine = RE_engine_create(type);
2423         engine->reports = op->reports;
2424
2425         /* get node */
2426         if (nodeptr.data) {
2427                 ntree_base = nodeptr.id.data;
2428                 node = nodeptr.data;
2429         }
2430         else if (snode && snode->edittree) {
2431                 ntree_base = snode->edittree;
2432                 node = nodeGetActive(snode->edittree);
2433         }
2434
2435         if (node) {
2436                 /* update single node */
2437                 type->update_script_node(engine, ntree_base, node);
2438
2439                 found = true;
2440         }
2441         else {
2442                 /* update all nodes using text datablock */
2443                 Text *text = CTX_data_pointer_get_type(C, "edit_text", &RNA_Text).data;
2444
2445                 if (text) {
2446                         /* clear flags for recursion check */
2447                         FOREACH_NODETREE(bmain, ntree, id) {
2448                                 if (ntree->type == NTREE_SHADER)
2449                                         ntree->done = false;
2450                         } FOREACH_NODETREE_END
2451
2452                         FOREACH_NODETREE(bmain, ntree, id) {
2453                                 if (ntree->type == NTREE_SHADER) {
2454                                         if (!ntree->done)
2455                                                 found |= node_shader_script_update_text_recursive(engine, type, ntree, text);
2456                                 }
2457                         } FOREACH_NODETREE_END
2458
2459                         if (!found)
2460                                 BKE_report(op->reports, RPT_INFO, "Text not used by any node, no update done");
2461                 }
2462         }
2463
2464         RE_engine_free(engine);
2465
2466         return (found) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
2467 }
2468
2469 void NODE_OT_shader_script_update(wmOperatorType *ot)
2470 {
2471         /* identifiers */
2472         ot->name = "Script Node Update";
2473         ot->description = "Update shader script node with new sockets and options from the script";
2474         ot->idname = "NODE_OT_shader_script_update";
2475
2476         /* api callbacks */
2477         ot->exec = node_shader_script_update_exec;
2478         ot->poll = node_shader_script_update_poll;
2479
2480         /* flags */
2481         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2482 }
2483
2484 /* ********************** Viewer border ******************/
2485
2486 static void viewer_border_corner_to_backdrop(SpaceNode *snode, ARegion *ar, int x, int y,
2487                                              int backdrop_width, int backdrop_height,
2488                                              float *fx, float *fy)
2489 {
2490         float bufx, bufy;
2491
2492         bufx = backdrop_width * snode->zoom;
2493         bufy = backdrop_height * snode->zoom;
2494
2495         *fx = (bufx > 0.0f ? ((float) x - 0.5f * ar->winx - snode->xof) / bufx + 0.5f : 0.0f);
2496         *fy = (bufy > 0.0f ? ((float) y - 0.5f * ar->winy - snode->yof) / bufy + 0.5f : 0.0f);
2497 }
2498
2499 static int viewer_border_exec(bContext *C, wmOperator *op)
2500 {
2501         Image *ima;
2502         void *lock;
2503         ImBuf *ibuf;
2504
2505         ED_preview_kill_jobs(CTX_wm_manager(C), CTX_data_main(C));
2506
2507         ima = BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
2508         ibuf = BKE_image_acquire_ibuf(ima, NULL, &lock);
2509
2510         if (ibuf) {
2511                 ARegion *ar = CTX_wm_region(C);
2512                 SpaceNode *snode = CTX_wm_space_node(C);
2513                 bNodeTree *btree = snode->nodetree;
2514                 rcti rect;
2515                 rctf rectf;
2516
2517                 /* get border from operator */
2518                 WM_operator_properties_border_to_rcti(op, &rect);
2519
2520                 /* convert border to unified space within backdrop image */
2521                 viewer_border_corner_to_backdrop(snode, ar, rect.xmin, rect.ymin, ibuf->x, ibuf->y,
2522                                                  &rectf.xmin, &rectf.ymin);
2523
2524                 viewer_border_corner_to_backdrop(snode, ar, rect.xmax, rect.ymax, ibuf->x, ibuf->y,
2525                                                  &rectf.xmax, &rectf.ymax);
2526
2527                 /* clamp coordinates */
2528                 rectf.xmin = max_ff(rectf.xmin, 0.0f);
2529                 rectf.ymin = max_ff(rectf.ymin, 0.0f);
2530                 rectf.xmax = min_ff(rectf.xmax, 1.0f);
2531                 rectf.ymax = min_ff(rectf.ymax, 1.0f);
2532
2533                 if (rectf.xmin < rectf.xmax && rectf.ymin < rectf.ymax) {
2534                         btree->viewer_border = rectf;
2535
2536                         if (rectf.xmin == 0.0f && rectf.ymin == 0.0f &&
2537                             rectf.xmax == 1.0f && rectf.ymax == 1.0f)
2538                         {
2539                                 btree->flag &= ~NTREE_VIEWER_BORDER;
2540                         }
2541                         else {
2542                                 btree->flag |= NTREE_VIEWER_BORDER;
2543                         }
2544
2545                         snode_notify(C, snode);
2546                         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2547                 }
2548                 else {
2549                         btree->flag &= ~NTREE_VIEWER_BORDER;
2550                 }
2551         }
2552
2553         BKE_image_release_ibuf(ima, ibuf, lock);
2554
2555         return OPERATOR_FINISHED;
2556 }
2557
2558 void NODE_OT_viewer_border(wmOperatorType *ot)
2559 {
2560         /* identifiers */
2561         ot->name = "Viewer Border";
2562         ot->description = "Set the boundaries for viewer operations";
2563         ot->idname = "NODE_OT_viewer_border";
2564
2565         /* api callbacks */
2566         ot->invoke = WM_gesture_border_invoke;
2567         ot->exec = viewer_border_exec;
2568         ot->modal = WM_gesture_border_modal;
2569         ot->cancel = WM_gesture_border_cancel;
2570         ot->poll = composite_node_active;
2571
2572         /* flags */
2573         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2574
2575         /* properties */
2576         WM_operator_properties_gesture_border_select(ot);
2577 }
2578
2579 static int clear_viewer_border_exec(bContext *C, wmOperator *UNUSED(op))
2580 {
2581         SpaceNode *snode = CTX_wm_space_node(C);
2582         bNodeTree *btree = snode->nodetree;
2583
2584         btree->flag &= ~NTREE_VIEWER_BORDER;
2585         snode_notify(C, snode);
2586         WM_event_add_notifier(C, NC_NODE | ND_DISPLAY, NULL);
2587
2588         return OPERATOR_FINISHED;
2589 }
2590
2591 void NODE_OT_clear_viewer_border(wmOperatorType *ot)
2592 {
2593         /* identifiers */
2594         ot->name = "Clear Viewer Border";
2595         ot->description = "Clear the boundaries for viewer operations";
2596         ot->idname = "NODE_OT_clear_viewer_border";
2597
2598         /* api callbacks */
2599         ot->exec = clear_viewer_border_exec;
2600         ot->poll = composite_node_active;
2601
2602         /* flags */
2603         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2604 }