2.5 Texture paint:
[blender.git] / source / blender / editors / space_node / node_edit.c
1 /**
2  * $Id:
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. 
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2005 Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): David Millan Escriva, Juho Vepsäläinen, Nathan Letwory
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <math.h>
33 #include <string.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_action_types.h"
38 #include "DNA_brush_types.h"
39 #include "DNA_color_types.h"
40 #include "DNA_image_types.h"
41 #include "DNA_ipo_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_material_types.h"
44 #include "DNA_texture_types.h"
45 #include "DNA_node_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_userdef_types.h"
50
51 #include "BKE_context.h"
52 #include "BKE_colortools.h"
53 #include "BKE_global.h"
54 #include "BKE_image.h"
55 #include "BKE_library.h"
56 #include "BKE_main.h"
57 #include "BKE_node.h"
58 #include "BKE_material.h"
59 #include "BKE_paint.h"
60 #include "BKE_texture.h"
61 #include "BKE_scene.h"
62 #include "BKE_utildefines.h"
63
64 #include "ED_previewrender.h"
65
66 #include "BIF_gl.h"
67
68 #include "BLI_arithb.h"
69 #include "BLI_blenlib.h"
70 #include "BLI_storage_types.h"
71
72 #include "RE_pipeline.h"
73
74 #include "IMB_imbuf_types.h"
75
76 #include "ED_space_api.h"
77 #include "ED_screen.h"
78 #include "ED_transform.h"
79 #include "ED_types.h"
80
81 #include "RNA_access.h"
82 #include "RNA_define.h"
83
84 #include "WM_api.h"
85 #include "WM_types.h"
86
87 #include "UI_view2d.h"
88  
89 #include "node_intern.h"
90
91 #define SOCK_IN         1
92 #define SOCK_OUT        2
93
94 /* ***************** composite job manager ********************** */
95
96 typedef struct CompoJob {
97         Scene *scene;
98         bNodeTree *ntree;
99         bNodeTree *localtree;
100         short *stop;
101         short *do_update;
102 } CompoJob;
103
104 /* called by compo, only to check job 'stop' value */
105 static int compo_breakjob(void *cjv)
106 {
107         CompoJob *cj= cjv;
108         
109         return *(cj->stop);
110 }
111
112 /* called by compo, wmJob sends notifier */
113 static void compo_redrawjob(void *cjv, char *str)
114 {
115         CompoJob *cj= cjv;
116         
117         *(cj->do_update)= 1;
118 }
119
120 static void compo_freejob(void *cjv)
121 {
122         CompoJob *cj= cjv;
123
124         if(cj->localtree) {
125                 ntreeLocalMerge(cj->localtree, cj->ntree);
126         }
127         MEM_freeN(cj);
128 }
129
130 /* only now we copy the nodetree, so adding many jobs while
131    sliding buttons doesn't frustrate */
132 static void compo_initjob(void *cjv)
133 {
134         CompoJob *cj= cjv;
135
136         cj->localtree= ntreeLocalize(cj->ntree);
137 }
138
139 /* called before redraw notifiers, it moves finished previews over */
140 static void compo_updatejob(void *cjv)
141 {
142         CompoJob *cj= cjv;
143         
144         ntreeLocalSync(cj->localtree, cj->ntree);
145 }
146
147
148 /* only this runs inside thread */
149 static void compo_startjob(void *cjv, short *stop, short *do_update)
150 {
151         CompoJob *cj= cjv;
152         bNodeTree *ntree= cj->localtree;
153         
154         if(cj->scene->use_nodes==0)
155                 return;
156         
157         cj->stop= stop;
158         cj->do_update= do_update;
159         
160         ntree->test_break= compo_breakjob;
161         ntree->tbh= cj;
162         ntree->stats_draw= compo_redrawjob;
163         ntree->sdh= cj;
164         
165         // XXX BIF_store_spare();
166         
167         ntreeCompositExecTree(ntree, &cj->scene->r, 1); /* 1 is do_previews */
168         
169         ntree->test_break= NULL;
170         ntree->stats_draw= NULL;
171
172 }
173
174 void snode_composite_job(const bContext *C, ScrArea *sa)
175 {
176         SpaceNode *snode= sa->spacedata.first;
177         wmJob *steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), sa);
178         CompoJob *cj= MEM_callocN(sizeof(CompoJob), "compo job");
179         
180         /* customdata for preview thread */
181         cj->scene= CTX_data_scene(C);
182         cj->ntree= snode->nodetree;
183         
184         /* setup job */
185         WM_jobs_customdata(steve, cj, compo_freejob);
186         WM_jobs_timer(steve, 0.1, NC_SCENE, NC_SCENE|ND_COMPO_RESULT);
187         WM_jobs_callbacks(steve, compo_startjob, compo_initjob, compo_updatejob);
188         
189         WM_jobs_start(CTX_wm_manager(C), steve);
190         
191 }
192
193 /* ***************************************** */
194
195 /* also checks for edited groups */
196 bNode *editnode_get_active(bNodeTree *ntree)
197 {
198         bNode *node;
199         
200         /* check for edited group */
201         for(node= ntree->nodes.first; node; node= node->next)
202                 if(node->flag & NODE_GROUP_EDIT)
203                         break;
204         if(node)
205                 return nodeGetActive((bNodeTree *)node->id);
206         else
207                 return nodeGetActive(ntree);
208 }
209
210 void snode_handle_recalc(bContext *C, SpaceNode *snode)
211 {
212         if(snode->treetype==NTREE_SHADER)
213                 WM_event_add_notifier(C, NC_MATERIAL|ND_NODES, snode->id);
214         else if(snode->treetype==NTREE_COMPOSIT)
215                 WM_event_add_notifier(C, NC_SCENE|ND_NODES, snode->id);
216         else if(snode->treetype==NTREE_TEXTURE) {
217                 // ntreeTexUpdatePreviews(snode->nodetree); /* XXX texture nodes should follow shader node methods (ton) */
218                 // XXX BIF_preview_changed(ID_TE);
219         }
220 }
221
222 #if 0
223 static int image_detect_file_sequence(int *start_p, int *frames_p, char *str)
224 {
225         SpaceFile *sfile;
226         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX], filename[FILE_MAX];
227         int a, frame, totframe, found, minframe;
228         unsigned short numlen;
229
230         sfile= scrarea_find_space_of_type(curarea, SPACE_FILE);
231         if(sfile==NULL || sfile->filelist==NULL)
232                 return 0;
233
234         /* find first frame */
235         found= 0;
236         minframe= 0;
237
238         for(a=0; a<sfile->totfile; a++) {
239                 if(sfile->filelist[a].flags & ACTIVE) {
240                         BLI_strncpy(name, sfile->filelist[a].relname, sizeof(name));
241                         frame= BLI_stringdec(name, head, tail, &numlen);
242
243                         if(!found || frame < minframe) {
244                                 BLI_strncpy(filename, name, sizeof(name));
245                                 minframe= frame;
246                                 found= 1;
247                         }
248                 }
249         }
250
251         /* not one frame found */
252         if(!found)
253                 return 0;
254
255         /* counter number of following frames */
256         found= 1;
257         totframe= 0;
258
259         for(frame=minframe; found; frame++) {
260                 found= 0;
261                 BLI_strncpy(name, filename, sizeof(name));
262                 BLI_stringenc(name, head, tail, numlen, frame);
263
264                 for(a=0; a<sfile->totfile; a++) {
265                         if(sfile->filelist[a].flags & ACTIVE) {
266                                 if(strcmp(sfile->filelist[a].relname, name) == 0) {
267                                         found= 1;
268                                         totframe++;
269                                         break;
270                                 }
271                         }
272                 }
273         }
274
275         if(totframe > 1) {
276                 BLI_strncpy(str, sfile->dir, sizeof(name));
277                 strcat(str, filename);
278
279                 *start_p= minframe;
280                 *frames_p= totframe;
281                 return 1;
282         }
283
284         return 0;
285 }
286
287 static void load_node_image(char *str)  /* called from fileselect */
288 {
289         SpaceNode *snode= curarea->spacedata.first;
290         bNode *node= nodeGetActive(snode->edittree);
291         Image *ima= NULL;
292         ImageUser *iuser= node->storage;
293         char filename[FILE_MAX];
294         int start=0, frames=0, sequence;
295
296         sequence= image_detect_file_sequence(&start, &frames, filename);
297         if(sequence)
298                 str= filename;
299         
300         ima= BKE_add_image_file(str);
301         if(ima) {
302                 if(node->id)
303                         node->id->us--;
304                 
305                 node->id= &ima->id;
306                 id_us_plus(node->id);
307
308                 BLI_strncpy(node->name, node->id->name+2, 21);
309
310                 if(sequence) {
311                         ima->source= IMA_SRC_SEQUENCE;
312                         iuser->frames= frames;
313                         iuser->offset= start-1;
314                 }
315                                    
316                 BKE_image_signal(ima, node->storage, IMA_SIGNAL_RELOAD);
317                 
318                 NodeTagChanged(snode->edittree, node);
319                 // XXX snode_handle_recalc(C, snode);
320         }
321 }
322
323 static void set_node_imagepath(char *str)       /* called from fileselect */
324 {
325         SpaceNode *snode= curarea->spacedata.first;
326         bNode *node= nodeGetActive(snode->edittree);
327         BLI_strncpy(((NodeImageFile *)node->storage)->name, str, sizeof( ((NodeImageFile *)node->storage)->name ));
328 }
329
330 #endif /* 0 */
331
332 bNode *snode_get_editgroup(SpaceNode *snode)
333 {
334         bNode *gnode;
335         
336         /* get the groupnode */
337         for(gnode= snode->nodetree->nodes.first; gnode; gnode= gnode->next)
338                 if(gnode->flag & NODE_GROUP_EDIT)
339                         break;
340         return gnode;
341 }
342
343 #if 0
344
345 /* node has to be of type 'render layers' */
346 /* is a bit clumsy copying renderdata here... scene nodes use render size of current render */
347 static void composite_node_render(SpaceNode *snode, bNode *node)
348 {
349         RenderData rd;
350         Scene *scene= NULL;
351         int scemode, actlay;
352         
353         /* the button press won't show up otherwise, button hilites disabled */
354         force_draw(0);
355         
356         if(node->id && node->id!=(ID *)G.scene) {
357                 scene= G.scene;
358                 set_scene_bg((Scene *)node->id);
359                 rd= G.scene->r;
360                 G.scene->r.xsch= scene->r.xsch;
361                 G.scene->r.ysch= scene->r.ysch;
362                 G.scene->r.size= scene->r.size;
363                 G.scene->r.mode &= ~(R_BORDER|R_DOCOMP);
364                 G.scene->r.mode |= scene->r.mode & R_BORDER;
365                 G.scene->r.border= scene->r.border;
366                 G.scene->r.cfra= scene->r.cfra;
367         }
368         
369         scemode= G.scene->r.scemode;
370         actlay= G.scene->r.actlay;
371
372         G.scene->r.scemode |= R_SINGLE_LAYER|R_COMP_RERENDER;
373         G.scene->r.actlay= node->custom1;
374         
375         BIF_do_render(0);
376         
377         G.scene->r.scemode= scemode;
378         G.scene->r.actlay= actlay;
379
380         node->custom2= 0;
381         
382         if(scene) {
383                 G.scene->r= rd;
384                 set_scene_bg(scene);
385         }
386 }
387
388 static void composit_node_event(SpaceNode *snode, short event)
389 {
390         
391         switch(event) {
392                 case B_REDR:
393                         // allqueue(REDRAWNODE, 1);
394                         break;
395                 case B_NODE_LOADIMAGE:
396                 {
397                         bNode *node= nodeGetActive(snode->edittree);
398                         char name[FILE_MAXDIR+FILE_MAXFILE];
399                         
400                         if(node->id)
401                                 strcpy(name, ((Image *)node->id)->name);
402                         else strcpy(name, U.textudir);
403                         if (G.qual & LR_CTRLKEY) {
404                                 activate_imageselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
405                         } else {
406                                 activate_fileselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
407                         }
408                         break;
409                 }
410                 case B_NODE_SETIMAGE:
411                 {
412                         bNode *node= nodeGetActive(snode->edittree);
413                         char name[FILE_MAXDIR+FILE_MAXFILE];
414                         
415                         strcpy(name, ((NodeImageFile *)node->storage)->name);
416                         if (G.qual & LR_CTRLKEY) {
417                                 activate_imageselect(FILE_SPECIAL, "SELECT OUTPUT DIR", name, set_node_imagepath);
418                         } else {
419                                 activate_fileselect(FILE_SPECIAL, "SELECT OUTPUT DIR", name, set_node_imagepath);
420                         }
421                         break;
422                 }
423                 case B_NODE_TREE_EXEC:
424                         // XXX                  snode_handle_recalc(snode);
425                         break;          
426                 default:
427                         /* B_NODE_EXEC */
428                 {
429                         bNode *node= BLI_findlink(&snode->edittree->nodes, event-B_NODE_EXEC);
430                         if(node) {
431                                 NodeTagChanged(snode->edittree, node);
432                                 /* don't use NodeTagIDChanged, it gives far too many recomposites for image, scene layers, ... */
433                                 
434                                 /* not the best implementation of the world... but we need it to work now :) */
435                                 if(node->type==CMP_NODE_R_LAYERS && node->custom2) {
436                                         /* add event for this window (after render curarea can be changed) */
437                                         addqueue(curarea->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
438                                         
439                                         composite_node_render(snode, node);
440                                         // XXX                  snode_handle_recalc(snode);
441                                         
442                                         /* add another event, a render can go fullscreen and open new window */
443                                         addqueue(curarea->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
444                                 }
445                                 else {
446                                         node= snode_get_editgroup(snode);
447                                         if(node)
448                                                 NodeTagIDChanged(snode->nodetree, node->id);
449                                         
450                                         // XXX                  snode_handle_recalc(snode);
451                                 }
452                         }
453                 }                       
454         }
455 }
456
457 static void texture_node_event(SpaceNode *snode, short event)
458 {
459         switch(event) {
460                 case B_REDR:
461                         // allqueue(REDRAWNODE, 1);
462                         break;
463                 case B_NODE_LOADIMAGE:
464                 {
465                         bNode *node= nodeGetActive(snode->edittree);
466                         char name[FILE_MAXDIR+FILE_MAXFILE];
467                         
468                         if(node->id)
469                                 strcpy(name, ((Image *)node->id)->name);
470                         else strcpy(name, U.textudir);
471                         if (G.qual & LR_CTRLKEY) {
472                                 activate_imageselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
473                         } else {
474                                 activate_fileselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
475                         }
476                         break;
477                 }
478                 default:
479                         /* B_NODE_EXEC */
480                         ntreeTexCheckCyclics( snode->nodetree );
481                         // XXX                  snode_handle_recalc(snode);
482                         // allqueue(REDRAWNODE, 1);
483                         break;
484         }
485 }
486
487 #endif /* 0  */
488 /* assumes nothing being done in ntree yet, sets the default in/out node */
489 /* called from shading buttons or header */
490 void node_shader_default(Material *ma)
491 {
492         bNode *in, *out;
493         bNodeSocket *fromsock, *tosock;
494         
495         /* but lets check it anyway */
496         if(ma->nodetree) {
497                 printf("error in shader initialize\n");
498                 return;
499         }
500         
501         ma->nodetree= ntreeAddTree(NTREE_SHADER);
502         
503         out= nodeAddNodeType(ma->nodetree, SH_NODE_OUTPUT, NULL, NULL);
504         out->locx= 300.0f; out->locy= 300.0f;
505         
506         in= nodeAddNodeType(ma->nodetree, SH_NODE_MATERIAL, NULL, NULL);
507         in->locx= 10.0f; in->locy= 300.0f;
508         nodeSetActive(ma->nodetree, in);
509         
510         /* only a link from color to color */
511         fromsock= in->outputs.first;
512         tosock= out->inputs.first;
513         nodeAddLink(ma->nodetree, in, fromsock, out, tosock);
514         
515         ntreeSolveOrder(ma->nodetree);  /* needed for pointers */
516 }
517
518 /* assumes nothing being done in ntree yet, sets the default in/out node */
519 /* called from shading buttons or header */
520 void node_composit_default(Scene *sce)
521 {
522         bNode *in, *out;
523         bNodeSocket *fromsock, *tosock;
524         
525         /* but lets check it anyway */
526         if(sce->nodetree) {
527                 printf("error in composit initialize\n");
528                 return;
529         }
530         
531         sce->nodetree= ntreeAddTree(NTREE_COMPOSIT);
532         
533         out= nodeAddNodeType(sce->nodetree, CMP_NODE_COMPOSITE, NULL, NULL);
534         out->locx= 300.0f; out->locy= 400.0f;
535         out->id= &sce->id;
536         
537         in= nodeAddNodeType(sce->nodetree, CMP_NODE_R_LAYERS, NULL, NULL);
538         in->locx= 10.0f; in->locy= 400.0f;
539         in->id= &sce->id;
540         nodeSetActive(sce->nodetree, in);
541         
542         /* links from color to color */
543         fromsock= in->outputs.first;
544         tosock= out->inputs.first;
545         nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
546         
547         ntreeSolveOrder(sce->nodetree); /* needed for pointers */
548         
549         // XXX ntreeCompositForceHidden(sce->nodetree);
550 }
551
552 /* assumes nothing being done in ntree yet, sets the default in/out node */
553 /* called from shading buttons or header */
554 void node_texture_default(Tex *tx)
555 {
556         bNode *in, *out;
557         bNodeSocket *fromsock, *tosock;
558         
559         /* but lets check it anyway */
560         if(tx->nodetree) {
561                 printf("error in texture initialize\n");
562                 return;
563         }
564         
565         tx->nodetree= ntreeAddTree(NTREE_TEXTURE);
566         
567         out= nodeAddNodeType(tx->nodetree, TEX_NODE_OUTPUT, NULL, NULL);
568         out->locx= 300.0f; out->locy= 300.0f;
569         
570         in= nodeAddNodeType(tx->nodetree, TEX_NODE_CHECKER, NULL, NULL);
571         in->locx= 10.0f; in->locy= 300.0f;
572         nodeSetActive(tx->nodetree, in);
573         
574         fromsock= in->outputs.first;
575         tosock= out->inputs.first;
576         nodeAddLink(tx->nodetree, in, fromsock, out, tosock);
577         
578         ntreeSolveOrder(tx->nodetree);  /* needed for pointers */
579         ntreeTexUpdatePreviews(tx->nodetree); /* XXX texture nodes should follow shader node methods (ton) */
580 }
581
582 /* Here we set the active tree(s), even called for each redraw now, so keep it fast :) */
583 void snode_set_context(SpaceNode *snode, Scene *scene)
584 {
585         Object *ob= OBACT;
586         bNode *node= NULL;
587         
588         snode->nodetree= NULL;
589         snode->id= snode->from= NULL;
590         
591         if(snode->treetype==NTREE_SHADER) {
592                 /* need active object, or we allow pinning... */
593                 if(ob) {
594                         Material *ma= give_current_material(ob, ob->actcol);
595                         if(ma) {
596                                 snode->from= material_from(ob, ob->actcol);
597                                 snode->id= &ma->id;
598                                 snode->nodetree= ma->nodetree;
599                         }
600                 }
601         }
602         else if(snode->treetype==NTREE_COMPOSIT) {
603                 snode->from= NULL;
604                 snode->id= &scene->id;
605                 
606                 /* bit clumsy but reliable way to see if we draw first time */
607                 if(snode->nodetree==NULL)
608                         ntreeCompositForceHidden(scene->nodetree, scene);
609                 
610                 snode->nodetree= scene->nodetree;
611         }
612         else if(snode->treetype==NTREE_TEXTURE) {
613                 Tex *tx= NULL;
614
615                 if(snode->texfrom==SNODE_TEX_OBJECT) {
616                         if(ob) {
617                                 tx= give_current_texture(ob, ob->actcol);
618                                 snode->from= (ID *)ob;
619                         }
620                 }
621                 else if(snode->texfrom==SNODE_TEX_WORLD) {
622                         tx= give_current_world_texture(scene);
623                         snode->from= (ID *)scene->world;
624                 }
625                 else {
626                         MTex *mtex= NULL;
627                         Brush *brush= NULL;
628                         
629                         if(ob && ob->mode & OB_MODE_SCULPT) {
630                                 brush= paint_brush(&scene->toolsettings->sculpt->paint);
631                         }
632                         else
633                                 brush= paint_brush(&scene->toolsettings->imapaint.paint);
634
635                         if(brush) {
636                                 if(brush && brush->texact != -1)
637                                         mtex= brush->mtex[brush->texact];
638                         }
639                         
640                         if(mtex) {
641                                 snode->from= (ID *)scene;
642                                 tx= mtex->tex;
643                         }
644                 }
645                 
646                 if(tx) {
647                         snode->id= &tx->id;
648                         snode->nodetree= tx->nodetree;
649                 }
650         }
651         
652         /* find editable group */
653         if(snode->nodetree)
654                 for(node= snode->nodetree->nodes.first; node; node= node->next)
655                         if(node->flag & NODE_GROUP_EDIT)
656                                 break;
657         
658         if(node && node->id)
659                 snode->edittree= (bNodeTree *)node->id;
660         else
661                 snode->edittree= snode->nodetree;
662 }
663
664 #if 0
665 /* on activate image viewer, check if we show it */
666 static void node_active_image(Image *ima)
667 {
668         ScrArea *sa;
669         SpaceImage *sima= NULL;
670         
671         /* find an imagewindow showing render result */
672         for(sa=G.curscreen->areabase.first; sa; sa= sa->next) {
673                 if(sa->spacetype==SPACE_IMAGE) {
674                         sima= sa->spacedata.first;
675                         if(sima->image && sima->image->source!=IMA_SRC_VIEWER)
676                                 break;
677                 }
678         }
679         if(sa && sima) {
680                 sima->image= ima;
681                 scrarea_queue_winredraw(sa);
682                 scrarea_queue_headredraw(sa);
683         }
684 }
685 #endif /* 0 */
686
687 void node_set_active(SpaceNode *snode, bNode *node)
688 {
689         
690         nodeSetActive(snode->edittree, node);
691         
692         #if 0
693         // XXX
694         if(node->type!=NODE_GROUP) {
695                 
696                 /* tree specific activate calls */
697                 if(snode->treetype==NTREE_SHADER) {
698                         
699                         /* when we select a material, active texture is cleared, for buttons */
700                         if(node->id && GS(node->id->name)==ID_MA)
701                                 nodeClearActiveID(snode->edittree, ID_TE);
702                         if(node->id)
703                                 ; // XXX BIF_preview_changed(-1);       /* temp hack to force texture preview to update */
704                         
705                         // allqueue(REDRAWBUTSSHADING, 1);
706                         // allqueue(REDRAWIPO, 0);
707                 }
708                 else if(snode->treetype==NTREE_COMPOSIT) {
709                         /* make active viewer, currently only 1 supported... */
710                         if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) {
711                                 bNode *tnode;
712                                 int was_output= node->flag & NODE_DO_OUTPUT;
713
714                                 for(tnode= snode->edittree->nodes.first; tnode; tnode= tnode->next)
715                                         if( ELEM(tnode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
716                                                 tnode->flag &= ~NODE_DO_OUTPUT;
717                                 
718                                 node->flag |= NODE_DO_OUTPUT;
719                                 if(was_output==0) {
720                                         bNode *gnode;
721                                         
722                                         NodeTagChanged(snode->edittree, node);
723                                         
724                                         /* if inside group, tag entire group */
725                                         gnode= snode_get_editgroup(snode);
726                                         if(gnode)
727                                                 NodeTagIDChanged(snode->nodetree, gnode->id);
728                                         
729                                         // XXX                  snode_handle_recalc(snode);
730                                 }
731                                 
732                                 /* addnode() doesnt link this yet... */
733                                 node->id= (ID *)BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
734                         }
735                         else if(node->type==CMP_NODE_IMAGE) {
736                                 if(node->id)
737                                         node_active_image((Image *)node->id);
738                         }
739                         else if(node->type==CMP_NODE_R_LAYERS) {
740                                 if(node->id==NULL || node->id==(ID *)G.scene) {
741                                         G.scene->r.actlay= node->custom1;
742                                         // allqueue(REDRAWBUTSSCENE, 0);
743                                 }
744                         }
745                 }
746                 else if(snode->treetype==NTREE_TEXTURE) {
747                         if(node->id)
748                                 ; // XXX BIF_preview_changed(-1);
749                         // allqueue(REDRAWBUTSSHADING, 1);
750                         // allqueue(REDRAWIPO, 0);
751                 }
752         }
753         #endif /* 0 */
754 }
755
756 void snode_make_group_editable(SpaceNode *snode, bNode *gnode)
757 {
758         bNode *node;
759         
760         /* make sure nothing has group editing on */
761         for(node= snode->nodetree->nodes.first; node; node= node->next)
762                 node->flag &= ~NODE_GROUP_EDIT;
763         
764         if(gnode==NULL) {
765                 /* with NULL argument we do a toggle */
766                 if(snode->edittree==snode->nodetree)
767                         gnode= nodeGetActive(snode->nodetree);
768         }
769         
770         if(gnode && gnode->type==NODE_GROUP && gnode->id) {
771                 if(gnode->id->lib) {
772                         // XXX if(okee("Make Group Local"))
773                         //      ntreeMakeLocal((bNodeTree *)gnode->id);
774                         // else
775                                 return;
776                 }
777                 gnode->flag |= NODE_GROUP_EDIT;
778                 snode->edittree= (bNodeTree *)gnode->id;
779                 
780                 /* deselect all other nodes, so we can also do grabbing of entire subtree */
781                 for(node= snode->nodetree->nodes.first; node; node= node->next)
782                         node->flag &= ~SELECT;
783                 gnode->flag |= SELECT;
784                 
785         }
786         else 
787                 snode->edittree= snode->nodetree;
788         
789         ntreeSolveOrder(snode->nodetree);
790         
791         /* finally send out events for new active node */
792         if(snode->treetype==NTREE_SHADER) {
793                 // allqueue(REDRAWBUTSSHADING, 0);
794                 
795                 // XXX BIF_preview_changed(-1); /* temp hack to force texture preview to update */
796         }
797         
798         // allqueue(REDRAWNODE, 0);
799 }
800
801 #if 0
802
803 void node_ungroup(SpaceNode *snode)
804 {
805         bNode *gnode;
806
807         /* are we inside of a group? */
808         gnode= snode_get_editgroup(snode);
809         if(gnode)
810                 snode_make_group_editable(snode, NULL);
811         
812         gnode= nodeGetActive(snode->edittree);
813         if(gnode==NULL) return;
814         
815         if(gnode->type!=NODE_GROUP)
816                 error("Not a group");
817         else {
818                 if(nodeGroupUnGroup(snode->edittree, gnode)) {
819                         
820                         // allqueue(REDRAWNODE, 0);
821                 }
822                 else
823                         error("Can't ungroup");
824         }
825 }
826
827 #endif /* 0 */
828 /* when links in groups change, inputs/outputs change, nodes added/deleted... */
829 static void snode_verify_groups(SpaceNode *snode)
830 {
831         bNode *gnode;
832         
833         gnode= snode_get_editgroup(snode);
834         
835         /* does all materials */
836         if(gnode)
837                 nodeVerifyGroup((bNodeTree *)gnode->id);
838         
839 }
840
841 #if 0
842
843 static void node_addgroup(SpaceNode *snode)
844 {
845         bNodeTree *ngroup;
846         int tot= 0, offs, val;
847         char *strp;
848         
849         if(snode->edittree!=snode->nodetree) {
850                 error("Can not add a Group in a Group");
851                 return;
852         }
853         
854         /* construct menu with choices */
855         for(ngroup= G.main->nodetree.first; ngroup; ngroup= ngroup->id.next) {
856                 if(ngroup->type==snode->treetype)
857                         tot++;
858         }
859         if(tot==0) {
860                 error("No groups available in database");
861                 return;
862         }
863         strp= MEM_mallocN(32*tot+32, "menu");
864         strcpy(strp, "Add Group %t");
865         offs= strlen(strp);
866         
867         for(tot=0, ngroup= G.main->nodetree.first; ngroup; ngroup= ngroup->id.next, tot++) {
868                 if(ngroup->type==snode->treetype)
869                         offs+= sprintf(strp+offs, "|%s %%x%d", ngroup->id.name+2, tot);
870         }       
871         
872         val= pupmenu(strp);
873         if(val>=0) {
874                 ngroup= BLI_findlink(&G.main->nodetree, val);
875                 if(ngroup) {
876                         bNode *node= nodeAddNodeType(snode->edittree, NODE_GROUP, ngroup, NULL);
877                         
878                         /* generics */
879                         if(node) {
880                                 float locx, locy;
881                                 short mval[2];
882
883                                 node_deselectall(snode, 0);
884                                 
885                                 getmouseco_areawin(mval);
886                                 areamouseco_to_ipoco(G.v2d, mval, &locx, &locy);
887                                 
888                                 node->locx= locx;
889                                 node->locy= locy + 60.0f;               // arbitrary.. so its visible
890                                 node->flag |= SELECT;
891                                 
892                                 id_us_plus(node->id);
893                                 
894                                 node_set_active(snode, node);
895                         }
896                 }                       
897         }
898         MEM_freeN(strp);
899 }
900
901 #endif /* 0 */
902
903 /* ************************** Node generic ************** */
904
905 /* allows to walk the list in order of visibility */
906 bNode *next_node(bNodeTree *ntree)
907 {
908         static bNode *current=NULL, *last= NULL;
909         
910         if(ntree) {
911                 /* set current to the first selected node */
912                 for(current= ntree->nodes.last; current; current= current->prev)
913                         if(current->flag & NODE_SELECT)
914                                 break;
915                 
916                 /* set last to the first unselected node */
917                 for(last= ntree->nodes.last; last; last= last->prev)
918                         if((last->flag & NODE_SELECT)==0)
919                                 break;
920                 
921                 if(current==NULL)
922                         current= last;
923                 
924                 return NULL;
925         }
926         /* no nodes, or we are ready */
927         if(current==NULL)
928                 return NULL;
929         
930         /* now we walk the list backwards, but we always return current */
931         if(current->flag & NODE_SELECT) {
932                 bNode *node= current;
933                 
934                 /* find previous selected */
935                 current= current->prev;
936                 while(current && (current->flag & NODE_SELECT)==0)
937                         current= current->prev;
938                 
939                 /* find first unselected */
940                 if(current==NULL)
941                         current= last;
942                 
943                 return node;
944         }
945         else {
946                 bNode *node= current;
947                 
948                 /* find previous unselected */
949                 current= current->prev;
950                 while(current && (current->flag & NODE_SELECT))
951                         current= current->prev;
952                 
953                 return node;
954         }
955         
956         return NULL;
957 }
958
959 /* is rct in visible part of node? */
960 static bNode *visible_node(SpaceNode *snode, rctf *rct)
961 {
962         bNode *tnode;
963         
964         for(next_node(snode->edittree); (tnode=next_node(NULL));) {
965                 if(BLI_isect_rctf(&tnode->totr, rct, NULL))
966                         break;
967         }
968         return tnode;
969 }
970
971 void snode_home(ScrArea *sa, ARegion *ar, SpaceNode* snode)
972 {
973         bNode *node;
974         rctf *cur, *tot;
975         float oldwidth, oldheight, width, height;
976         int first= 1;
977         
978         cur= &ar->v2d.cur;
979         tot= &ar->v2d.tot;
980         
981         oldwidth= cur->xmax - cur->xmin;
982         oldheight= cur->ymax - cur->ymin;
983         
984         cur->xmin= cur->ymin= 0.0f;
985         cur->xmax=ar->winx;
986         cur->xmax= ar->winy;
987         
988         if(snode->edittree) {
989                 for(node= snode->edittree->nodes.first; node; node= node->next) {
990                         if(first) {
991                                 first= 0;
992                                 ar->v2d.cur= node->totr;
993                         }
994                         else {
995                                 BLI_union_rctf(cur, &node->totr);
996                         }
997                 }
998         }
999         
1000         snode->xof= 0;
1001         snode->yof= 0;
1002         width= cur->xmax - cur->xmin;
1003         height= cur->ymax- cur->ymin;
1004         if(width > height) {
1005                 float newheight;
1006                 newheight= oldheight * width/oldwidth;
1007                 cur->ymin= cur->ymin - newheight/4;
1008                 cur->ymax= cur->ymin + newheight;
1009         }
1010         else {
1011                 float newwidth;
1012                 newwidth= oldwidth * height/oldheight;
1013                 cur->xmin= cur->xmin - newwidth/4;
1014                 cur->xmax= cur->xmin + newwidth;
1015         }
1016         
1017         ar->v2d.tot= ar->v2d.cur;
1018         UI_view2d_curRect_validate(&ar->v2d);
1019 }
1020
1021 #if 0
1022 static void snode_bg_viewmove(SpaceNode *snode)
1023 {
1024         ScrArea *sa;
1025         Image *ima;
1026         ImBuf *ibuf;
1027         Window *win;
1028         short mval[2], mvalo[2];
1029         short rectx, recty, xmin, xmax, ymin, ymax, pad;
1030         int oldcursor;
1031         
1032         ima= BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
1033         ibuf= BKE_image_get_ibuf(ima, NULL);
1034         
1035         sa = snode->area;
1036         
1037         if(ibuf) {
1038                 rectx = ibuf->x;
1039                 recty = ibuf->y;
1040         } else {
1041                 rectx = recty = 1;
1042         }
1043         
1044         pad = 10;
1045         xmin = -(sa->winx/2) - rectx/2 + pad;
1046         xmax = sa->winx/2 + rectx/2 - pad;
1047         ymin = -(sa->winy/2) - recty/2 + pad;
1048         ymax = sa->winy/2 + recty/2 - pad;
1049         
1050         getmouseco_sc(mvalo);
1051         
1052         /* store the old cursor to temporarily change it */
1053         oldcursor=get_cursor();
1054         win=winlay_get_active_window();
1055         
1056         SetBlenderCursor(BC_NSEW_SCROLLCURSOR);
1057         
1058         while(get_mbut()&(L_MOUSE|M_MOUSE)) {
1059                 
1060                 getmouseco_sc(mval);
1061                 
1062                 if(mvalo[0]!=mval[0] || mvalo[1]!=mval[1]) {
1063                         
1064                         snode->xof -= (mvalo[0]-mval[0]);
1065                         snode->yof -= (mvalo[1]-mval[1]);
1066                         
1067                         /* prevent dragging image outside of the window and losing it! */
1068                         CLAMP(snode->xof, xmin, xmax);
1069                         CLAMP(snode->yof, ymin, ymax);
1070                         
1071                         mvalo[0]= mval[0];
1072                         mvalo[1]= mval[1];
1073                         
1074                         scrarea_do_windraw(curarea);
1075                         screen_swapbuffers();
1076                 }
1077                 else BIF_wait_for_statechange();
1078         }
1079         
1080         window_set_cursor(win, oldcursor);
1081 }
1082 #endif
1083
1084 /* ********************** size widget operator ******************** */
1085
1086 typedef struct NodeSizeWidget {
1087         float mxstart;
1088         float oldwidth;
1089 } NodeSizeWidget;
1090
1091 static int node_resize_modal(bContext *C, wmOperator *op, wmEvent *event)
1092 {
1093         SpaceNode *snode= CTX_wm_space_node(C);
1094         ARegion *ar= CTX_wm_region(C);
1095         bNode *node= editnode_get_active(snode->edittree);
1096         NodeSizeWidget *nsw= op->customdata;
1097         float mx, my;
1098         
1099         switch (event->type) {
1100                 case MOUSEMOVE:
1101                         
1102                         UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1103                                                                          &mx, &my);
1104                         
1105                         if(node->flag & NODE_HIDDEN) {
1106                                 node->miniwidth= nsw->oldwidth + mx - nsw->mxstart;
1107                                 CLAMP(node->miniwidth, 0.0f, 100.0f);
1108                         }
1109                         else {
1110                                 node->width= nsw->oldwidth + mx - nsw->mxstart;
1111                                 CLAMP(node->width, node->typeinfo->minwidth, node->typeinfo->maxwidth);
1112                         }
1113                         // XXX
1114                         if(snode->nodetree->type == NTREE_TEXTURE)
1115                                 ntreeTexUpdatePreviews(snode->nodetree); /* XXX texture nodes should follow shader node methods (ton) */
1116                                 
1117                         ED_region_tag_redraw(ar);
1118
1119                         break;
1120                         
1121                 case LEFTMOUSE:
1122                 case MIDDLEMOUSE:
1123                 case RIGHTMOUSE:
1124                         
1125                         MEM_freeN(nsw);
1126                         op->customdata= NULL;
1127                         
1128                         return OPERATOR_FINISHED;
1129         }
1130         
1131         return OPERATOR_RUNNING_MODAL;
1132 }
1133
1134 static int node_resize_invoke(bContext *C, wmOperator *op, wmEvent *event)
1135 {
1136         SpaceNode *snode= CTX_wm_space_node(C);
1137         ARegion *ar= CTX_wm_region(C);
1138         bNode *node= editnode_get_active(snode->edittree);
1139         
1140         if(node) {
1141                 rctf totr;
1142                 
1143                 UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1144                                                                  &snode->mx, &snode->my);
1145                 totr= node->totr;
1146                 totr.xmin= totr.xmax-10.0f;
1147                 totr.ymax= totr.ymin+10.0f;
1148                 
1149                 if(BLI_in_rctf(&totr, snode->mx, snode->my)) {
1150                         NodeSizeWidget *nsw= MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
1151                         
1152                         op->customdata= nsw;
1153                         nsw->mxstart= snode->mx;
1154                         
1155                         /* store old */
1156                         if(node->flag & NODE_HIDDEN)
1157                                 nsw->oldwidth= node->miniwidth;
1158                         else
1159                                 nsw->oldwidth= node->width;
1160                         
1161                         /* add modal handler */
1162                         WM_event_add_modal_handler(C, &CTX_wm_window(C)->handlers, op);
1163
1164                         return OPERATOR_RUNNING_MODAL;
1165                 }
1166         }
1167         return OPERATOR_PASS_THROUGH;
1168 }
1169
1170 void NODE_OT_resize(wmOperatorType *ot)
1171 {
1172         /* identifiers */
1173         ot->name= "Resize Node";
1174         ot->idname= "NODE_OT_resize";
1175         
1176         /* api callbacks */
1177         ot->invoke= node_resize_invoke;
1178         ot->modal= node_resize_modal;
1179         ot->poll= ED_operator_node_active;
1180         
1181         /* flags */
1182         ot->flag= OPTYPE_BLOCKING;
1183 }
1184
1185
1186 #if 0
1187
1188 /* ******************** rename ******************* */
1189
1190 void node_rename(SpaceNode *snode)
1191 {
1192         bNode *node, *rename_node;
1193         short found_node= 0;
1194
1195         /* check if a node is selected */
1196         for(node= snode->edittree->nodes.first; node; node= node->next) {
1197                 if(node->flag & SELECT) {
1198                         found_node= 1;
1199                         break;
1200                 }
1201         }
1202
1203         if(found_node) {
1204                 rename_node= nodeGetActive(snode->edittree);
1205                 node_rename_but((char *)rename_node->username);
1206         
1207                 // allqueue(REDRAWNODE, 1);
1208         }
1209 }
1210
1211 /* ********************** select ******************** */
1212
1213 /* used in buttons to check context, also checks for edited groups */
1214 bNode *editnode_get_active_idnode(bNodeTree *ntree, short id_code)
1215 {
1216         return nodeGetActiveID(ntree, id_code);
1217 }
1218
1219 /* used in buttons to check context, also checks for edited groups */
1220 Material *editnode_get_active_material(Material *ma)
1221 {
1222         if(ma && ma->use_nodes && ma->nodetree) {
1223                 bNode *node= editnode_get_active_idnode(ma->nodetree, ID_MA);
1224                 if(node)
1225                         return (Material *)node->id;
1226                 else
1227                         return NULL;
1228         }
1229         return ma;
1230 }
1231 #endif /* 0 */
1232
1233
1234 /* no undo here! */
1235 void node_deselectall(SpaceNode *snode, int swap)
1236 {
1237         bNode *node;
1238         
1239         if(swap) {
1240                 for(node= snode->edittree->nodes.first; node; node= node->next)
1241                         if(node->flag & SELECT)
1242                                 break;
1243                 if(node==NULL) {
1244                         for(node= snode->edittree->nodes.first; node; node= node->next)
1245                                 node->flag |= SELECT;
1246                         return;
1247                 }
1248                 /* else pass on to deselect */
1249         }
1250         
1251         for(node= snode->edittree->nodes.first; node; node= node->next)
1252                 node->flag &= ~SELECT;
1253 }
1254
1255
1256 int node_has_hidden_sockets(bNode *node)
1257 {
1258         bNodeSocket *sock;
1259         
1260         for(sock= node->inputs.first; sock; sock= sock->next)
1261                 if(sock->flag & SOCK_HIDDEN)
1262                         return 1;
1263         for(sock= node->outputs.first; sock; sock= sock->next)
1264                 if(sock->flag & SOCK_HIDDEN)
1265                         return 1;
1266         return 0;
1267 }
1268
1269
1270 static void node_hide_unhide_sockets(SpaceNode *snode, bNode *node)
1271 {
1272         bNodeSocket *sock;
1273         
1274         /* unhide all */
1275         if( node_has_hidden_sockets(node) ) {
1276                 for(sock= node->inputs.first; sock; sock= sock->next)
1277                         sock->flag &= ~SOCK_HIDDEN;
1278                 for(sock= node->outputs.first; sock; sock= sock->next)
1279                         sock->flag &= ~SOCK_HIDDEN;
1280         }
1281         else {
1282                 bNode *gnode= snode_get_editgroup(snode);
1283                 
1284                 /* hiding inside group should not break links in other group users */
1285                 if(gnode) {
1286                         nodeGroupSocketUseFlags((bNodeTree *)gnode->id);
1287                         for(sock= node->inputs.first; sock; sock= sock->next)
1288                                 if(!(sock->flag & SOCK_IN_USE))
1289                                         if(sock->link==NULL)
1290                                                 sock->flag |= SOCK_HIDDEN;
1291                         for(sock= node->outputs.first; sock; sock= sock->next)
1292                                 if(!(sock->flag & SOCK_IN_USE))
1293                                         if(nodeCountSocketLinks(snode->edittree, sock)==0)
1294                                                 sock->flag |= SOCK_HIDDEN;
1295                 }
1296                 else {
1297                         /* hide unused sockets */
1298                         for(sock= node->inputs.first; sock; sock= sock->next) {
1299                                 if(sock->link==NULL)
1300                                         sock->flag |= SOCK_HIDDEN;
1301                         }
1302                         for(sock= node->outputs.first; sock; sock= sock->next) {
1303                                 if(nodeCountSocketLinks(snode->edittree, sock)==0)
1304                                         sock->flag |= SOCK_HIDDEN;
1305                         }
1306                 }
1307         }
1308
1309         // allqueue(REDRAWNODE, 1);
1310         snode_verify_groups(snode);
1311
1312 }
1313
1314 /*static*/ int do_header_node(SpaceNode *snode, bNode *node, float mx, float my)
1315 {
1316         rctf totr= node->totr;
1317         
1318         totr.ymin= totr.ymax-20.0f;
1319         
1320         totr.xmax= totr.xmin+15.0f;
1321         if(BLI_in_rctf(&totr, mx, my)) {
1322                 node->flag |= NODE_HIDDEN;
1323                 // allqueue(REDRAWNODE, 0);
1324                 return 1;
1325         }       
1326         
1327         totr.xmax= node->totr.xmax;
1328         totr.xmin= totr.xmax-18.0f;
1329         if(node->typeinfo->flag & NODE_PREVIEW) {
1330                 if(BLI_in_rctf(&totr, mx, my)) {
1331                         node->flag ^= NODE_PREVIEW;
1332                         // allqueue(REDRAWNODE, 0);
1333                         return 1;
1334                 }
1335                 totr.xmin-=18.0f;
1336         }
1337         if(node->type == NODE_GROUP) {
1338                 if(BLI_in_rctf(&totr, mx, my)) {
1339                         snode_make_group_editable(snode, node);
1340                         return 1;
1341                 }
1342                 totr.xmin-=18.0f;
1343         }
1344         if(node->typeinfo->flag & NODE_OPTIONS) {
1345                 if(BLI_in_rctf(&totr, mx, my)) {
1346                         node->flag ^= NODE_OPTIONS;
1347                         // allqueue(REDRAWNODE, 0);
1348                         return 1;
1349                 }
1350                 totr.xmin-=18.0f;
1351         }
1352         /* hide unused sockets */
1353         if(BLI_in_rctf(&totr, mx, my)) {
1354                 node_hide_unhide_sockets(snode, node);
1355         }
1356         
1357         
1358         totr= node->totr;
1359         totr.xmin= totr.xmax-10.0f;
1360         totr.ymax= totr.ymin+10.0f;
1361         if(BLI_in_rctf(&totr, mx, my)) {
1362 //              scale_node(snode, node);
1363                 return 1;
1364         }
1365         return 0;
1366 }
1367
1368 /*static*/ int do_header_hidden_node(SpaceNode *snode, bNode *node, float mx, float my)
1369 {
1370         rctf totr= node->totr;
1371         
1372         totr.xmax= totr.xmin+15.0f;
1373         if(BLI_in_rctf(&totr, mx, my)) {
1374                 node->flag &= ~NODE_HIDDEN;
1375                 // allqueue(REDRAWNODE, 0);
1376                 return 1;
1377         }       
1378         
1379         totr.xmax= node->totr.xmax;
1380         totr.xmin= node->totr.xmax-15.0f;
1381         if(BLI_in_rctf(&totr, mx, my)) {
1382 //              scale_node(snode, node);
1383                 return 1;
1384         }
1385         return 0;
1386 }
1387
1388 static void node_link_viewer(SpaceNode *snode, bNode *tonode)
1389 {
1390         bNode *node;
1391
1392         /* context check */
1393         if(tonode==NULL || tonode->outputs.first==NULL)
1394                 return;
1395         if( ELEM(tonode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1396                 return;
1397         
1398         /* get viewer */
1399         for(node= snode->edittree->nodes.first; node; node= node->next)
1400                 if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1401                         if(node->flag & NODE_DO_OUTPUT)
1402                                 break;
1403                 
1404         if(node) {
1405                 bNodeLink *link;
1406                 
1407                 /* get link to viewer */
1408                 for(link= snode->edittree->links.first; link; link= link->next)
1409                         if(link->tonode==node)
1410                                 break;
1411
1412                 if(link) {
1413                         link->fromnode= tonode;
1414                         link->fromsock= tonode->outputs.first;
1415                         NodeTagChanged(snode->edittree, node);
1416                         
1417 // XXX                  snode_handle_recalc(snode);
1418                 }
1419         }
1420 }
1421
1422
1423 void node_active_link_viewer(SpaceNode *snode)
1424 {
1425         bNode *node= editnode_get_active(snode->edittree);
1426         if(node)
1427                 node_link_viewer(snode, node);
1428 }
1429
1430 /* return 0, nothing done */
1431 /*static*/ int node_mouse_groupheader(SpaceNode *snode)
1432 {
1433         bNode *gnode;
1434         float mx=0, my=0;
1435 // XXX  short mval[2];
1436         
1437         gnode= snode_get_editgroup(snode);
1438         if(gnode==NULL) return 0;
1439         
1440 // XXX  getmouseco_areawin(mval);
1441 // XXX  areamouseco_to_ipoco(G.v2d, mval, &mx, &my);
1442         
1443         /* click in header or outside? */
1444         if(BLI_in_rctf(&gnode->totr, mx, my)==0) {
1445                 rctf rect= gnode->totr;
1446                 
1447                 rect.ymax += NODE_DY;
1448                 if(BLI_in_rctf(&rect, mx, my)==0)
1449                         snode_make_group_editable(snode, NULL); /* toggles, so exits editmode */
1450 //              else
1451 // XXX                  transform_nodes(snode->nodetree, 'g', "Move group");
1452                 
1453                 return 1;
1454         }
1455         return 0;
1456 }
1457
1458 /* checks snode->mouse position, and returns found node/socket */
1459 /* type is SOCK_IN and/or SOCK_OUT */
1460 static int find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1461 {
1462         bNode *node;
1463         bNodeSocket *sock;
1464         rctf rect;
1465         
1466         /* check if we click in a socket */
1467         for(node= snode->edittree->nodes.first; node; node= node->next) {
1468                 
1469                 rect.xmin = snode->mx - NODE_SOCKSIZE+3;
1470                 rect.ymin = snode->my - NODE_SOCKSIZE+3;
1471                 rect.xmax = rect.xmin + 2*NODE_SOCKSIZE+6;
1472                 rect.ymax = rect.ymin + 2*NODE_SOCKSIZE+6;
1473                 
1474                 if (!(node->flag & NODE_HIDDEN)) {
1475                         /* extra padding inside and out - allow dragging on the text areas too */
1476                         if (in_out == SOCK_IN) {
1477                                 rect.xmax += NODE_SOCKSIZE;
1478                                 rect.xmin -= NODE_SOCKSIZE*4;
1479                         } else if (in_out == SOCK_OUT) {
1480                                 rect.xmax += NODE_SOCKSIZE*4;
1481                                 rect.xmin -= NODE_SOCKSIZE;
1482                         }
1483                 }
1484                 
1485                 if(in_out & SOCK_IN) {
1486                         for(sock= node->inputs.first; sock; sock= sock->next) {
1487                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1488                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1489                                                 if(node == visible_node(snode, &rect)) {
1490                                                         *nodep= node;
1491                                                         *sockp= sock;
1492                                                         return 1;
1493                                                 }
1494                                         }
1495                                 }
1496                         }
1497                 }
1498                 if(in_out & SOCK_OUT) {
1499                         for(sock= node->outputs.first; sock; sock= sock->next) {
1500                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1501                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1502                                                 if(node == visible_node(snode, &rect)) {
1503                                                         *nodep= node;
1504                                                         *sockp= sock;
1505                                                         return 1;
1506                                                 }
1507                                         }
1508                                 }
1509                         }
1510                 }
1511         }
1512         return 0;
1513 }
1514
1515 static int node_socket_hilights(SpaceNode *snode, int in_out)
1516 {
1517         bNode *node;
1518         bNodeSocket *sock, *tsock, *socksel= NULL;
1519         short redraw= 0;
1520         
1521         if(snode->edittree==NULL) return 0;
1522         
1523         /* deselect socks */
1524         for(node= snode->edittree->nodes.first; node; node= node->next) {
1525                 for(sock= node->inputs.first; sock; sock= sock->next) {
1526                         if(sock->flag & SELECT) {
1527                                 sock->flag &= ~SELECT;
1528                                 redraw++;
1529                                 socksel= sock;
1530                         }
1531                 }
1532                 for(sock= node->outputs.first; sock; sock= sock->next) {
1533                         if(sock->flag & SELECT) {
1534                                 sock->flag &= ~SELECT;
1535                                 redraw++;
1536                                 socksel= sock;
1537                         }
1538                 }
1539         }
1540         
1541         // XXX mousepos should be set here!
1542         
1543         if(find_indicated_socket(snode, &node, &tsock, in_out)) {
1544                 tsock->flag |= SELECT;
1545                 if(redraw==1 && tsock==socksel) redraw= 0;
1546                 else redraw= 1;
1547         }
1548         
1549         return redraw;
1550 }
1551
1552 /* ****************** Add *********************** */
1553
1554 void snode_autoconnect(SpaceNode *snode, bNode *node_to, int flag)
1555 {
1556         bNodeSocket *sock, *sockfrom[8];
1557         bNode *node, *nodefrom[8];
1558         int totsock= 0, socktype=0;
1559
1560         if(node_to==NULL || node_to->inputs.first==NULL)
1561                 return;
1562         
1563         /* no inputs for node allowed (code it) */
1564
1565         /* connect first 1 socket type now */
1566         for(sock= node_to->inputs.first; sock; sock= sock->next)
1567                 if(socktype<sock->type)
1568                         socktype= sock->type;
1569
1570         
1571         /* find potential sockets, max 8 should work */
1572         for(node= snode->edittree->nodes.first; node; node= node->next) {
1573                 if((node->flag & flag) && node!=node_to) {
1574                         for(sock= node->outputs.first; sock; sock= sock->next) {
1575                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1576                                         sockfrom[totsock]= sock;
1577                                         nodefrom[totsock]= node;
1578                                         totsock++;
1579                                         if(totsock>7)
1580                                                 break;
1581                                 }
1582                         }
1583                 }
1584                 if(totsock>7)
1585                         break;
1586         }
1587
1588         /* now just get matching socket types and create links */
1589         for(sock= node_to->inputs.first; sock; sock= sock->next) {
1590                 int a;
1591                 
1592                 for(a=0; a<totsock; a++) {
1593                         if(sockfrom[a]) {
1594                                 if(sock->type==sockfrom[a]->type && sock->type==socktype) {
1595                                         nodeAddLink(snode->edittree, nodefrom[a], sockfrom[a], node_to, sock);
1596                                         sockfrom[a]= NULL;
1597                                         break;
1598                                 }
1599                         }
1600                 }
1601         }
1602         
1603         ntreeSolveOrder(snode->edittree);
1604 }
1605
1606
1607 /* can be called from menus too, but they should do own undopush and redraws */
1608 bNode *node_add_node(SpaceNode *snode, Scene *scene, int type, float locx, float locy)
1609 {
1610         bNode *node= NULL, *gnode;
1611         
1612         node_deselectall(snode, 0);
1613         
1614         if(type>=NODE_DYNAMIC_MENU) {
1615                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
1616         }
1617         else if(type>=NODE_GROUP_MENU) {
1618                 if(snode->edittree!=snode->nodetree) {
1619                         // XXX error("Can not add a Group in a Group");
1620                         return NULL;
1621                 }
1622                 else {
1623                         bNodeTree *ngroup= BLI_findlink(&G.main->nodetree, type-NODE_GROUP_MENU);
1624                         if(ngroup)
1625                                 node= nodeAddNodeType(snode->edittree, NODE_GROUP, ngroup, NULL);
1626                 }
1627         }
1628         else
1629                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
1630         
1631         /* generics */
1632         if(node) {
1633                 node->locx= locx;
1634                 node->locy= locy + 60.0f;               // arbitrary.. so its visible
1635                 node->flag |= SELECT;
1636                 
1637                 gnode= snode_get_editgroup(snode);
1638                 if(gnode) {
1639                         node->locx -= gnode->locx;
1640                         node->locy -= gnode->locy;
1641                 }
1642
1643                 snode_verify_groups(snode);
1644                 node_set_active(snode, node);
1645                 
1646                 if(snode->nodetree->type==NTREE_COMPOSIT) {
1647                         if(ELEM(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE))
1648                                 node->id = &scene->id;
1649                         
1650                         ntreeCompositForceHidden(snode->edittree, scene);
1651                 }
1652                         
1653                 if(node->id)
1654                         id_us_plus(node->id);
1655                         
1656                 NodeTagChanged(snode->edittree, node);
1657         }
1658         
1659         if(snode->nodetree->type==NTREE_TEXTURE) {
1660                 ntreeTexCheckCyclics(snode->edittree);
1661                 ntreeTexUpdatePreviews(snode->edittree); /* XXX texture nodes should follow shader node methods (ton) */
1662         }
1663         
1664         return node;
1665 }
1666
1667 #if 0
1668
1669 void node_mute(SpaceNode *snode)
1670 {
1671         bNode *node;
1672
1673         /* no disabling inside of groups */
1674         if(snode_get_editgroup(snode))
1675                 return;
1676         
1677         for(node= snode->edittree->nodes.first; node; node= node->next) {
1678                 if(node->flag & SELECT) {
1679                         if(node->inputs.first && node->outputs.first) {
1680                                 if(node->flag & NODE_MUTED)
1681                                         node->flag &= ~NODE_MUTED;
1682                                 else
1683                                         node->flag |= NODE_MUTED;
1684                         }
1685                 }
1686         }
1687         
1688
1689 }
1690
1691 #endif
1692
1693 int node_duplicate_exec(bContext *C, wmOperator *op)
1694 {
1695         SpaceNode *snode= CTX_wm_space_node(C);
1696         
1697         ntreeCopyTree(snode->edittree, 1);      /* 1 == internally selected nodes */
1698         
1699         ntreeSolveOrder(snode->edittree);
1700         snode_verify_groups(snode);
1701         snode_handle_recalc(C, snode);
1702
1703         return OPERATOR_FINISHED;
1704 }
1705
1706 static int node_duplicate_invoke(bContext *C, wmOperator *op, wmEvent *event)
1707 {
1708         node_duplicate_exec(C, op);
1709         
1710         RNA_int_set(op->ptr, "mode", TFM_TRANSLATION);
1711         WM_operator_name_call(C, "TFM_OT_transform", WM_OP_INVOKE_REGION_WIN, op->ptr);
1712         
1713         return OPERATOR_FINISHED;
1714 }
1715
1716 void NODE_OT_duplicate(wmOperatorType *ot)
1717 {
1718         
1719         /* identifiers */
1720         ot->name= "Duplicate Nodes";
1721         ot->description = "Duplicate the nodes.";
1722         ot->idname= "NODE_OT_duplicate";
1723         
1724         /* api callbacks */
1725         ot->invoke= node_duplicate_invoke;
1726         ot->exec= node_duplicate_exec;
1727         
1728         ot->poll= ED_operator_node_active;
1729         
1730         /* flags */
1731         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1732         
1733         /* to give to transform */
1734         RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX);
1735 }
1736
1737 #if 0
1738
1739 static void node_insert_convertor(SpaceNode *snode, bNodeLink *link)
1740 {
1741         bNode *newnode= NULL;
1742         
1743         if(link->fromsock->type==SOCK_RGBA && link->tosock->type==SOCK_VALUE) {
1744                 if(snode->edittree->type==NTREE_SHADER)
1745                         newnode= node_add_node(snode, SH_NODE_RGBTOBW, 0.0f, 0.0f);
1746                 else if(snode->edittree->type==NTREE_COMPOSIT)
1747                         newnode= node_add_node(snode, CMP_NODE_RGBTOBW, 0.0f, 0.0f);
1748                 else
1749                         newnode= NULL;
1750         }
1751         else if(link->fromsock->type==SOCK_VALUE && link->tosock->type==SOCK_RGBA) {
1752                 if(snode->edittree->type==NTREE_SHADER)
1753                         newnode= node_add_node(snode, SH_NODE_VALTORGB, 0.0f, 0.0f);
1754                 else if(snode->edittree->type==NTREE_COMPOSIT)
1755                         newnode= node_add_node(snode, CMP_NODE_VALTORGB, 0.0f, 0.0f);
1756                 else
1757                         newnode= NULL;
1758         }
1759         
1760         if(newnode) {
1761                 /* dangerous assumption to use first in/out socks, but thats fine for now */
1762                 newnode->flag |= NODE_HIDDEN;
1763                 newnode->locx= 0.5f*(link->fromsock->locx + link->tosock->locx);
1764                 newnode->locy= 0.5f*(link->fromsock->locy + link->tosock->locy) + HIDDEN_RAD;
1765                 
1766                 nodeAddLink(snode->edittree, newnode, newnode->outputs.first, link->tonode, link->tosock);
1767                 link->tonode= newnode;
1768                 link->tosock= newnode->inputs.first;
1769         }
1770 }
1771
1772
1773 #endif /* 0 */
1774
1775 /* *************************** add link op ******************** */
1776
1777 /* temp data to pass on to modal */
1778 typedef struct NodeLinkDrag
1779 {
1780         bNode *node;
1781         bNodeSocket *sock;
1782         bNodeLink *link;
1783         int in_out;
1784 } NodeLinkDrag;
1785
1786 /*static*/ void reset_sel_socket(SpaceNode *snode, int in_out)
1787 {
1788         bNode *node;
1789         bNodeSocket *sock;
1790         
1791         for(node= snode->edittree->nodes.first; node; node= node->next) {
1792                 if(in_out & SOCK_IN) {
1793                         for(sock= node->inputs.first; sock; sock= sock->next)
1794                                 if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
1795                 }
1796                 if(in_out & SOCK_OUT) {
1797                         for(sock= node->outputs.first; sock; sock= sock->next)
1798                                 if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
1799                 }
1800         }
1801 }
1802
1803
1804 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
1805 {
1806         bNodeLink *tlink;
1807         bNodeSocket *sock;
1808         
1809         if(tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
1810                 
1811                 for(tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
1812                         if(link!=tlink && tlink->tosock==link->tosock)
1813                                 break;
1814                 }
1815                 if(tlink) {
1816                         /* is there a free input socket with same type? */
1817                         for(sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
1818                                 if(sock->type==tlink->fromsock->type)
1819                                         if(nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
1820                                                 break;
1821                         }
1822                         if(sock) {
1823                                 tlink->tosock= sock;
1824                                 sock->flag &= ~SOCK_HIDDEN;
1825                         }
1826                         else {
1827                                 nodeRemLink(snode->edittree, tlink);
1828                         }
1829                 }
1830         }
1831 }
1832
1833 /* loop that adds a nodelink, called by function below  */
1834 /* in_out = starting socket */
1835 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
1836 {
1837         SpaceNode *snode= CTX_wm_space_node(C);
1838         ARegion *ar= CTX_wm_region(C);
1839         NodeLinkDrag *nldrag= op->customdata;
1840         bNode *tnode, *node;
1841         bNodeSocket *tsock= NULL, *sock;
1842         bNodeLink *link;
1843         int in_out;
1844
1845         in_out= nldrag->in_out;
1846         node= nldrag->node;
1847         sock= nldrag->sock;
1848         link= nldrag->link;
1849         
1850         UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1851                                                          &snode->mx, &snode->my);
1852
1853         switch (event->type) {
1854                 case MOUSEMOVE:
1855                         
1856                         if(in_out==SOCK_OUT) {
1857                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_IN)) {
1858                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
1859                                                 if(tnode!=node  && link->tonode!=tnode && link->tosock!= tsock) {
1860                                                         link->tonode= tnode;
1861                                                         link->tosock= tsock;
1862                                                         ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
1863                                                 }
1864                                         }
1865                                 }
1866                                 else {
1867                                         link->tonode= NULL;
1868                                         link->tosock= NULL;
1869                                 }
1870                         }
1871                         else {
1872                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
1873                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
1874                                                 if(nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
1875                                                         if(tnode!=node && link->fromnode!=tnode && link->fromsock!= tsock) {
1876                                                                 link->fromnode= tnode;
1877                                                                 link->fromsock= tsock;
1878                                                                 ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
1879                                                         }
1880                                                 }
1881                                         }
1882                                 }
1883                                 else {
1884                                         link->fromnode= NULL;
1885                                         link->fromsock= NULL;
1886                                 }
1887                         }
1888                         /* hilight target sockets only */
1889                         node_socket_hilights(snode, in_out==SOCK_OUT?SOCK_IN:SOCK_OUT);
1890                         ED_region_tag_redraw(ar);
1891                         break;
1892                         
1893                 case LEFTMOUSE:
1894                 case RIGHTMOUSE:
1895                 case MIDDLEMOUSE:
1896         
1897                         /* remove link? */
1898                         if(link->tonode==NULL || link->fromnode==NULL) {
1899                                 nodeRemLink(snode->edittree, link);
1900                         }
1901                         else {
1902                                 /* send changed events for original tonode and new */
1903                                 if(link->tonode) 
1904                                         NodeTagChanged(snode->edittree, link->tonode);
1905                                 
1906                                 /* we might need to remove a link */
1907                                 if(in_out==SOCK_OUT) node_remove_extra_links(snode, link->tosock, link);
1908                         }
1909                         
1910                         ntreeSolveOrder(snode->edittree);
1911                         snode_verify_groups(snode);
1912                         snode_handle_recalc(C, snode);
1913                         
1914                         MEM_freeN(op->customdata);
1915                         op->customdata= NULL;
1916                         
1917                         return OPERATOR_FINISHED;
1918         }
1919         
1920         return OPERATOR_RUNNING_MODAL;
1921 }
1922
1923 /* return 1 when socket clicked */
1924 static int node_link_init(SpaceNode *snode, NodeLinkDrag *nldrag)
1925 {
1926         bNodeLink *link;
1927         
1928         /* output indicated? */
1929         if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
1930                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
1931                         return SOCK_OUT;
1932                 else {
1933                         /* find if we break a link */
1934                         for(link= snode->edittree->links.first; link; link= link->next) {
1935                                 if(link->fromsock==nldrag->sock)
1936                                         break;
1937                         }
1938                         if(link) {
1939                                 nldrag->node= link->tonode;
1940                                 nldrag->sock= link->tosock;
1941                                 nodeRemLink(snode->edittree, link);
1942                                 return SOCK_IN;
1943                         }
1944                 }
1945         }
1946         /* or an input? */
1947         else if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
1948                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
1949                         return SOCK_IN;
1950                 else {
1951                         /* find if we break a link */
1952                         for(link= snode->edittree->links.first; link; link= link->next) {
1953                                 if(link->tosock==nldrag->sock)
1954                                         break;
1955                         }
1956                         if(link) {
1957                                 /* send changed event to original tonode */
1958                                 if(link->tonode) 
1959                                         NodeTagChanged(snode->edittree, link->tonode);
1960                                 
1961                                 nldrag->node= link->fromnode;
1962                                 nldrag->sock= link->fromsock;
1963                                 nodeRemLink(snode->edittree, link);
1964                                 return SOCK_OUT;
1965                         }
1966                 }
1967         }
1968         
1969         return 0;
1970 }
1971
1972 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
1973 {
1974         SpaceNode *snode= CTX_wm_space_node(C);
1975         ARegion *ar= CTX_wm_region(C);
1976         NodeLinkDrag *nldrag= MEM_callocN(sizeof(NodeLinkDrag), "drag link op customdata");
1977         
1978         UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1979                                                          &snode->mx, &snode->my);
1980
1981         nldrag->in_out= node_link_init(snode, nldrag);
1982                 
1983         if(nldrag->in_out) {
1984                 op->customdata= nldrag;
1985                 
1986                 /* we make a temporal link */
1987                 if(nldrag->in_out==SOCK_OUT)
1988                         nldrag->link= nodeAddLink(snode->edittree, nldrag->node, nldrag->sock, NULL, NULL);
1989                 else
1990                         nldrag->link= nodeAddLink(snode->edittree, NULL, NULL, nldrag->node, nldrag->sock);
1991                 
1992                 /* add modal handler */
1993                 WM_event_add_modal_handler(C, &CTX_wm_window(C)->handlers, op);
1994                 
1995                 return OPERATOR_RUNNING_MODAL;
1996         }
1997         else {
1998                 MEM_freeN(nldrag);
1999                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
2000         }
2001 }
2002
2003 void NODE_OT_link(wmOperatorType *ot)
2004 {
2005         /* identifiers */
2006         ot->name= "Link Nodes";
2007         ot->idname= "NODE_OT_link";
2008         
2009         /* api callbacks */
2010         ot->invoke= node_link_invoke;
2011         ot->modal= node_link_modal;
2012 //      ot->exec= node_link_exec;
2013         ot->poll= ED_operator_node_active;
2014         
2015         /* flags */
2016         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2017 }
2018
2019
2020 void node_delete(SpaceNode *snode)
2021 {
2022         bNode *node, *next;
2023         bNodeSocket *sock;
2024         
2025         for(node= snode->edittree->nodes.first; node; node= next) {
2026                 next= node->next;
2027                 if(node->flag & SELECT) {
2028                         /* set selin and selout NULL if the sockets belong to a node to be deleted */
2029                         for(sock= node->inputs.first; sock; sock= sock->next)
2030                                 if(snode->edittree->selin == sock) snode->edittree->selin= NULL;
2031
2032                         for(sock= node->outputs.first; sock; sock= sock->next)
2033                                 if(snode->edittree->selout == sock) snode->edittree->selout= NULL;
2034
2035                         /* check id user here, nodeFreeNode is called for free dbase too */
2036                         if(node->id)
2037                                 node->id->us--;
2038                         nodeFreeNode(snode->edittree, node);
2039                 }
2040         }
2041         
2042         snode_verify_groups(snode);
2043         // NODE_FIX_ME
2044         // snode_handle_recalc(snode);
2045         // allqueue(REDRAWNODE, 1);
2046 }
2047
2048
2049 void node_hide(SpaceNode *snode)
2050 {
2051         bNode *node;
2052         int nothidden=0, ishidden=0;
2053         
2054         for(node= snode->edittree->nodes.first; node; node= node->next) {
2055                 if(node->flag & SELECT) {
2056                         if(node->flag & NODE_HIDDEN)
2057                                 ishidden++;
2058                         else
2059                                 nothidden++;
2060                 }
2061         }
2062         for(node= snode->edittree->nodes.first; node; node= node->next) {
2063                 if(node->flag & SELECT) {
2064                         if( (ishidden && nothidden) || ishidden==0)
2065                                 node->flag |= NODE_HIDDEN;
2066                         else 
2067                                 node->flag &= ~NODE_HIDDEN;
2068                 }
2069         }
2070 }
2071
2072 #if 0
2073
2074 void node_insert_key(SpaceNode *snode)
2075 {
2076         bNode *node= editnode_get_active(snode->edittree);
2077         
2078         if(node == NULL)
2079                 return;
2080         
2081         if(node->type==CMP_NODE_TIME) {
2082                 if(node->custom1<node->custom2) {
2083
2084                         CurveMapping *cumap= node->storage;
2085                         float fval, curval;
2086                 
2087                         curval= (float)(CFRA - node->custom1)/(float)(node->custom2-node->custom1);
2088                         fval= curvemapping_evaluateF(cumap, 0, curval);
2089                         
2090                         if(fbutton(&fval, 0.0f, 1.0f, 10, 10, "Insert Value")) {
2091                                 curvemap_insert(cumap->cm, curval, fval);
2092
2093                         }
2094                 }
2095         }
2096 }
2097
2098 void node_select_linked(SpaceNode *snode, int out)
2099 {
2100         bNodeLink *link;
2101         bNode *node;
2102         
2103         /* NODE_TEST is the free flag */
2104         for(node= snode->edittree->nodes.first; node; node= node->next)
2105                 node->flag &= ~NODE_TEST;
2106
2107         for(link= snode->edittree->links.first; link; link= link->next) {
2108                 if(out) {
2109                         if(link->fromnode->flag & NODE_SELECT)
2110                                 link->tonode->flag |= NODE_TEST;
2111                 }
2112                 else {
2113                         if(link->tonode->flag & NODE_SELECT)
2114                                 link->fromnode->flag |= NODE_TEST;
2115                 }
2116         }
2117         
2118         for(node= snode->edittree->nodes.first; node; node= node->next)
2119                 if(node->flag & NODE_TEST)
2120                         node->flag |= NODE_SELECT;
2121         
2122 }
2123
2124 /* makes a link between selected output and input sockets */
2125 void node_make_link(SpaceNode *snode)
2126 {
2127         bNode *fromnode, *tonode;
2128         bNodeLink *link;
2129         bNodeSocket *outsock= snode->edittree->selout;
2130         bNodeSocket *insock= snode->edittree->selin;
2131
2132         if(!insock || !outsock) return;
2133         if(nodeFindLink(snode->edittree, outsock, insock)) return;
2134
2135         if(nodeFindNode(snode->edittree, outsock, &fromnode, NULL) &&
2136                 nodeFindNode(snode->edittree, insock, &tonode, NULL)) {
2137                 link= nodeAddLink(snode->edittree, fromnode, outsock, tonode, insock);
2138                 NodeTagChanged(snode->edittree, tonode);
2139                 node_remove_extra_links(snode, insock, link);
2140         }
2141         else return;
2142
2143         ntreeSolveOrder(snode->edittree);
2144         snode_verify_groups(snode);
2145         // XXX                  snode_handle_recalc(snode);
2146
2147 }
2148 #endif
2149
2150 /* ********************** Cut Link operator ***************** */
2151
2152 #define LINK_RESOL 12
2153 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2154 {
2155         float coord_array[LINK_RESOL+1][2];
2156         int i, b;
2157         
2158         if(node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2159
2160                 for(i=0; i<tot-1; i++)
2161                         for(b=0; b<LINK_RESOL-1; b++)
2162                                 if(IsectLL2Df(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2163                                         return 1;
2164         }
2165         return 0;
2166 }
2167
2168 static int cut_links_exec(bContext *C, wmOperator *op)
2169 {
2170         SpaceNode *snode= CTX_wm_space_node(C);
2171         ARegion *ar= CTX_wm_region(C);
2172         float mcoords[256][2];
2173         int i= 0;
2174         
2175         RNA_BEGIN(op->ptr, itemptr, "path") {
2176                 float loc[2];
2177                 
2178                 RNA_float_get_array(&itemptr, "loc", loc);
2179                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2180                                                                  &mcoords[i][0], &mcoords[i][1]);
2181                 i++;
2182                 if(i>= 256) break;
2183         }
2184         RNA_END;
2185         
2186         if(i>1) {
2187                 bNodeLink *link, *next;
2188                 
2189                 for(link= snode->edittree->links.first; link; link= next) {
2190                         next= link->next;
2191                         
2192                         if(cut_links_intersect(link, mcoords, i)) {
2193                                 NodeTagChanged(snode->edittree, link->tonode);
2194                                 nodeRemLink(snode->edittree, link);
2195                         }
2196                 }
2197
2198                 ntreeSolveOrder(snode->edittree);
2199                 snode_verify_groups(snode);
2200                 snode_handle_recalc(C, snode);
2201                 
2202                 return OPERATOR_FINISHED;
2203         }
2204         
2205         return OPERATOR_PASS_THROUGH;;
2206 }
2207
2208 void NODE_OT_links_cut(wmOperatorType *ot)
2209 {
2210         PropertyRNA *prop;
2211         
2212         ot->name= "Cut links";
2213         ot->idname= "NODE_OT_links_cut";
2214         
2215         ot->invoke= WM_gesture_lines_invoke;
2216         ot->modal= WM_gesture_lines_modal;
2217         ot->exec= cut_links_exec;
2218         
2219         ot->poll= ED_operator_node_active;
2220         
2221         /* flags */
2222         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2223         
2224         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2225         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2226         /* internal */
2227         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2228 }
2229
2230 /* ******************************** */
2231
2232 /* goes over all scenes, reads render layerss */
2233 void node_read_renderlayers(SpaceNode *snode)
2234 {
2235         Scene *curscene= NULL; // XXX
2236         Scene *scene;
2237         bNode *node;
2238
2239         /* first tag scenes unread */
2240         for(scene= G.main->scene.first; scene; scene= scene->id.next) 
2241                 scene->id.flag |= LIB_DOIT;
2242
2243         for(node= snode->edittree->nodes.first; node; node= node->next) {
2244                 if(node->type==CMP_NODE_R_LAYERS) {
2245                         ID *id= node->id;
2246                         if(id->flag & LIB_DOIT) {
2247                                 RE_ReadRenderResult(curscene, (Scene *)id);
2248                                 ntreeCompositTagRender((Scene *)id);
2249                                 id->flag &= ~LIB_DOIT;
2250                         }
2251                 }
2252         }
2253         
2254         // XXX                  snode_handle_recalc(snode);
2255 }
2256
2257 void node_read_fullsamplelayers(SpaceNode *snode)
2258 {
2259         Scene *curscene= NULL; // XXX
2260         Render *re= RE_NewRender(curscene->id.name);
2261
2262         WM_cursor_wait(1);
2263
2264         //BIF_init_render_callbacks(re, 1);
2265         RE_MergeFullSample(re, curscene, snode->nodetree);
2266         //BIF_end_render_callbacks();
2267         
2268         // allqueue(REDRAWNODE, 1);
2269         // allqueue(REDRAWIMAGE, 1);
2270         
2271         WM_cursor_wait(0);
2272 }
2273
2274 void imagepaint_composite_tags(bNodeTree *ntree, Image *image, ImageUser *iuser)
2275 {
2276         bNode *node;
2277         
2278         if(ntree==NULL)
2279                 return;
2280         
2281         /* search for renderresults */
2282         if(image->type==IMA_TYPE_R_RESULT) {
2283                 for(node= ntree->nodes.first; node; node= node->next) {
2284                         if(node->type==CMP_NODE_R_LAYERS && node->id==NULL) {
2285                                 /* imageuser comes from ImageWin, so indexes are offset 1 */
2286                                 if(node->custom1==iuser->layer-1)
2287                                         NodeTagChanged(ntree, node);
2288                         }
2289                 }
2290         }
2291         else {
2292                 for(node= ntree->nodes.first; node; node= node->next) {
2293                         if(node->id== &image->id)
2294                                 NodeTagChanged(ntree, node);
2295                 }
2296         }
2297 }
2298
2299 /* ********************** */
2300
2301 void node_make_group(SpaceNode *snode)
2302 {
2303         bNode *gnode;
2304         
2305         if(snode->edittree!=snode->nodetree) {
2306 // XXX          error("Can not add a new Group in a Group");
2307                 return;
2308         }
2309         
2310         /* for time being... is too complex to handle */
2311         if(snode->treetype==NTREE_COMPOSIT) {
2312                 for(gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
2313                         if(gnode->flag & SELECT)
2314                                 if(gnode->type==CMP_NODE_R_LAYERS)
2315                                         break;
2316                 }
2317                 if(gnode) {
2318 // XXX                  error("Can not add RenderLayer in a Group");
2319                         return;
2320                 }
2321         }
2322         
2323         gnode= nodeMakeGroupFromSelected(snode->nodetree);
2324         if(gnode==NULL) {
2325 // XXX          error("Can not make Group");
2326         }
2327         else {
2328                 nodeSetActive(snode->nodetree, gnode);
2329                 ntreeSolveOrder(snode->nodetree);
2330         }
2331 }
2332
2333 #if 0
2334
2335 /* ******************** main event loop ****************** */
2336
2337 void winqreadnodespace(ScrArea *sa, void *spacedata, BWinEvent *evt)
2338 {
2339         SpaceNode *snode= spacedata;
2340         bNode *actnode;
2341         bNodeSocket *actsock;
2342         unsigned short event= evt->event;
2343         short val= evt->val, doredraw=0, fromlib= 0;
2344         
2345         if(sa->win==0) return;
2346         
2347         if(snode->nodetree==NULL) {
2348                 /* no other events should be handled, but floating panels still should get handled */
2349                 uiDoBlocks(&curarea->uiblocks, event, 1);
2350                 return;
2351         }
2352         
2353         if(val) {
2354                 if( node_uiDoBlocks(sa, event)!=UI_NOTHING ) event= 0;
2355                 
2356                 fromlib= (snode->id && snode->id->lib);
2357                 
2358                 switch(event) {
2359                 case LEFTMOUSE:
2360                         if(gpencil_do_paint(sa, L_MOUSE)) {
2361                                 return;
2362                         }
2363                         else if(fromlib) {
2364                                 if(node_mouse_groupheader(snode)==0)
2365                                         //node_mouse_select(snode, event);
2366                         }
2367                         else {
2368                                 
2369                                 if(G.qual & LR_CTRLKEY)
2370                                         if(gesture())
2371                                                 break;
2372                                         
2373 //                              if(node_add_link(snode)==0)
2374                                         if(node_mouse_groupheader(snode)==0)
2375 //                                              if(node_mouse_select(snode, event)==0)
2376                                                         node_border_link_delete(snode);
2377                         }
2378                         break;
2379                         
2380                 case RIGHTMOUSE: 
2381                         if(gpencil_do_paint(sa, R_MOUSE)) {
2382                                 return;
2383                         }
2384                         else if(find_indicated_socket(snode, &actnode, &actsock, SOCK_IN)) {
2385                                 if(actsock->flag & SOCK_SEL) {
2386                                         snode->edittree->selin= NULL;
2387                                         actsock->flag&= ~SOCK_SEL;
2388                                 }
2389                                 else {
2390                                         snode->edittree->selin= actsock;
2391                                         reset_sel_socket(snode, SOCK_IN);
2392                                         actsock->flag|= SOCK_SEL;
2393                                 }
2394                         }
2395                         else if(find_indicated_socket(snode, &actnode, &actsock, SOCK_OUT)) {
2396                                 if(actsock->flag & SOCK_SEL) {
2397                                         snode->edittree->selout= NULL;
2398                                         actsock->flag&= ~SOCK_SEL;
2399                                 }
2400                                 else {
2401                                         snode->edittree->selout= actsock;
2402                                         reset_sel_socket(snode, SOCK_OUT);
2403                                         actsock->flag|= SOCK_SEL;
2404                                 }
2405                         }
2406 //                      else if(!node_mouse_select(snode, event)) 
2407 //                              toolbox_n();
2408
2409                         break;
2410                 case MIDDLEMOUSE:
2411                         if((snode->flag & SNODE_BACKDRAW) && (snode->treetype==NTREE_COMPOSIT)
2412                            && (G.qual==LR_SHIFTKEY)) {
2413                                 snode_bg_viewmove(snode);
2414                         } else {
2415                                 view2dmove(event);
2416                         }
2417                 case WHEELUPMOUSE:
2418                 case WHEELDOWNMOUSE:
2419                         view2dmove(event);      /* in drawipo.c */
2420                         break;
2421                         
2422                 case MOUSEY:
2423                         doredraw= node_socket_hilights(snode, SOCK_IN|SOCK_OUT);
2424                         break;
2425                 
2426                 case UI_BUT_EVENT:
2427                         /* future: handlerize this! */
2428                         if(snode->treetype==NTREE_SHADER)
2429                                 shader_node_event(snode, val);
2430                         else if(snode->treetype==NTREE_COMPOSIT)
2431                                 composit_node_event(snode, val);
2432                         else if(snode->treetype==NTREE_TEXTURE)
2433                                 texture_node_event(snode, val);
2434                         break;
2435                         
2436                 case PADPLUSKEY:
2437                         snode_zoom_in(sa);
2438                         doredraw= 1;
2439                         break;
2440                 case PADMINUS:
2441                         snode_zoom_out(sa);
2442                         doredraw= 1;
2443                         break;
2444                 case HOMEKEY:
2445                         snode_home(sa, snode);
2446                         doredraw= 1;
2447                         break;
2448                 case TABKEY:
2449                         if(fromlib) fromlib= -1;
2450                         else snode_make_group_editable(snode, NULL);
2451                         break;
2452                         
2453                 case AKEY:
2454                         if(G.qual==LR_SHIFTKEY) {
2455                                 if(fromlib) fromlib= -1;
2456                                 else toolbox_n_add();
2457                         }
2458                         else if(G.qual==0) {
2459                                 node_deselectall(snode, 1);
2460                         }
2461                         break;
2462                 case BKEY:
2463                         if(G.qual==0)
2464                                 node_border_select(snode);
2465                         break;
2466                 case CKEY:      /* sort again, showing cyclics */
2467                         ntreeSolveOrder(snode->edittree);
2468                         doredraw= 1;
2469                         break;
2470                 case DKEY:
2471                         if(G.qual==LR_SHIFTKEY) {
2472                                 if(fromlib) fromlib= -1;
2473                                 else node_adduplicate(snode);
2474                         }
2475                         break;
2476                 case EKEY:
2477                         // XXX                  snode_handle_recalc(snode);
2478                         break;
2479                 case FKEY:
2480                         node_make_link(snode);
2481                         break;
2482                 case GKEY:
2483                         if(fromlib) fromlib= -1;
2484                         else {
2485                                 if(G.qual==LR_CTRLKEY) {
2486                                         if(okee("Make Group"))
2487                                                 node_make_group(snode);
2488                                 }
2489                                 else if(G.qual==LR_ALTKEY) {
2490                                         if(okee("Ungroup"))
2491                                                 node_ungroup(snode);
2492                                 }
2493                                 else if(G.qual==LR_SHIFTKEY) {
2494                                         node_addgroup(snode);
2495                                 }
2496 //                              else
2497 // XXX                                  transform_nodes(snode->edittree, 'g', "Move Node");
2498                         }
2499                         break;
2500                 case HKEY:
2501                         node_hide(snode);
2502                         break;
2503                 case IKEY:
2504                         node_insert_key(snode);
2505                         break;
2506                 case LKEY:
2507                         node_select_linked(snode, G.qual==LR_SHIFTKEY);
2508                         break;
2509                 case MKEY:
2510                         node_mute(snode);
2511                         break;
2512                 case RKEY:
2513                         if(G.qual==LR_CTRLKEY) {
2514                                 node_rename(snode);
2515                         } 
2516                         else if(G.qual==LR_SHIFTKEY) {
2517                                 if(okee("Read saved Full Sample Layers"))
2518                                         node_read_fullsamplelayers(snode);
2519                         }
2520                         else {
2521                                 if(okee("Read saved Render Layers"))
2522                                         node_read_renderlayers(snode);
2523                         }
2524                         break;
2525                 case DELKEY:
2526                 case XKEY:
2527                         if(G.qual==LR_ALTKEY) {
2528                                 gpencil_delete_menu();
2529                         }
2530                         else {
2531                                 if(fromlib) fromlib= -1;
2532                                 else node_delete(snode);
2533                         }
2534                         break;
2535                 }
2536         }
2537
2538         if(fromlib==-1)
2539                 error_libdata();
2540         if(doredraw)
2541                 scrarea_queue_winredraw(sa);
2542         if(doredraw==2)
2543                 scrarea_queue_headredraw(sa);
2544 }
2545 #endif
2546
2547 static int node_delete_selection_exec(bContext *C, wmOperator *op)
2548 {
2549         SpaceNode *snode= CTX_wm_space_node(C);
2550         ARegion *ar= CTX_wm_region(C);
2551         
2552         node_delete(snode);
2553         ED_region_tag_redraw(ar);
2554         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL); /* Do we need to pass the scene? */
2555
2556         return OPERATOR_FINISHED;
2557 }
2558
2559 /* operators */
2560
2561 void NODE_OT_delete(wmOperatorType *ot)
2562 {
2563         
2564         /* identifiers */
2565         ot->name= "Delete";
2566         ot->idname= "NODE_OT_delete";
2567         
2568         /* api callbacks */
2569         ot->exec= node_delete_selection_exec;
2570         ot->poll= ED_operator_node_active;
2571         
2572         /* flags */
2573         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2574 }
2575