More texnode preview fixes. Previews now have correct aspect ratio and are drawn...
[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                 WM_event_add_notifier(C, NC_TEXTURE|ND_NODES, snode->id);
218 }
219
220 #if 0
221 static int image_detect_file_sequence(int *start_p, int *frames_p, char *str)
222 {
223         SpaceFile *sfile;
224         char name[FILE_MAX], head[FILE_MAX], tail[FILE_MAX], filename[FILE_MAX];
225         int a, frame, totframe, found, minframe;
226         unsigned short numlen;
227
228         sfile= scrarea_find_space_of_type(curarea, SPACE_FILE);
229         if(sfile==NULL || sfile->filelist==NULL)
230                 return 0;
231
232         /* find first frame */
233         found= 0;
234         minframe= 0;
235
236         for(a=0; a<sfile->totfile; a++) {
237                 if(sfile->filelist[a].flags & ACTIVE) {
238                         BLI_strncpy(name, sfile->filelist[a].relname, sizeof(name));
239                         frame= BLI_stringdec(name, head, tail, &numlen);
240
241                         if(!found || frame < minframe) {
242                                 BLI_strncpy(filename, name, sizeof(name));
243                                 minframe= frame;
244                                 found= 1;
245                         }
246                 }
247         }
248
249         /* not one frame found */
250         if(!found)
251                 return 0;
252
253         /* counter number of following frames */
254         found= 1;
255         totframe= 0;
256
257         for(frame=minframe; found; frame++) {
258                 found= 0;
259                 BLI_strncpy(name, filename, sizeof(name));
260                 BLI_stringenc(name, head, tail, numlen, frame);
261
262                 for(a=0; a<sfile->totfile; a++) {
263                         if(sfile->filelist[a].flags & ACTIVE) {
264                                 if(strcmp(sfile->filelist[a].relname, name) == 0) {
265                                         found= 1;
266                                         totframe++;
267                                         break;
268                                 }
269                         }
270                 }
271         }
272
273         if(totframe > 1) {
274                 BLI_strncpy(str, sfile->dir, sizeof(name));
275                 strcat(str, filename);
276
277                 *start_p= minframe;
278                 *frames_p= totframe;
279                 return 1;
280         }
281
282         return 0;
283 }
284
285 static void load_node_image(char *str)  /* called from fileselect */
286 {
287         SpaceNode *snode= curarea->spacedata.first;
288         bNode *node= nodeGetActive(snode->edittree);
289         Image *ima= NULL;
290         ImageUser *iuser= node->storage;
291         char filename[FILE_MAX];
292         int start=0, frames=0, sequence;
293
294         sequence= image_detect_file_sequence(&start, &frames, filename);
295         if(sequence)
296                 str= filename;
297         
298         ima= BKE_add_image_file(str);
299         if(ima) {
300                 if(node->id)
301                         node->id->us--;
302                 
303                 node->id= &ima->id;
304                 id_us_plus(node->id);
305
306                 BLI_strncpy(node->name, node->id->name+2, 21);
307
308                 if(sequence) {
309                         ima->source= IMA_SRC_SEQUENCE;
310                         iuser->frames= frames;
311                         iuser->offset= start-1;
312                 }
313                                    
314                 BKE_image_signal(ima, node->storage, IMA_SIGNAL_RELOAD);
315                 
316                 NodeTagChanged(snode->edittree, node);
317                 // XXX snode_handle_recalc(C, snode);
318         }
319 }
320
321 static void set_node_imagepath(char *str)       /* called from fileselect */
322 {
323         SpaceNode *snode= curarea->spacedata.first;
324         bNode *node= nodeGetActive(snode->edittree);
325         BLI_strncpy(((NodeImageFile *)node->storage)->name, str, sizeof( ((NodeImageFile *)node->storage)->name ));
326 }
327
328 #endif /* 0 */
329
330 bNode *snode_get_editgroup(SpaceNode *snode)
331 {
332         bNode *gnode;
333         
334         /* get the groupnode */
335         for(gnode= snode->nodetree->nodes.first; gnode; gnode= gnode->next)
336                 if(gnode->flag & NODE_GROUP_EDIT)
337                         break;
338         return gnode;
339 }
340
341 #if 0
342
343 /* node has to be of type 'render layers' */
344 /* is a bit clumsy copying renderdata here... scene nodes use render size of current render */
345 static void composite_node_render(SpaceNode *snode, bNode *node)
346 {
347         RenderData rd;
348         Scene *scene= NULL;
349         int scemode, actlay;
350         
351         /* the button press won't show up otherwise, button hilites disabled */
352         force_draw(0);
353         
354         if(node->id && node->id!=(ID *)G.scene) {
355                 scene= G.scene;
356                 set_scene_bg((Scene *)node->id);
357                 rd= G.scene->r;
358                 G.scene->r.xsch= scene->r.xsch;
359                 G.scene->r.ysch= scene->r.ysch;
360                 G.scene->r.size= scene->r.size;
361                 G.scene->r.mode &= ~(R_BORDER|R_DOCOMP);
362                 G.scene->r.mode |= scene->r.mode & R_BORDER;
363                 G.scene->r.border= scene->r.border;
364                 G.scene->r.cfra= scene->r.cfra;
365         }
366         
367         scemode= G.scene->r.scemode;
368         actlay= G.scene->r.actlay;
369
370         G.scene->r.scemode |= R_SINGLE_LAYER|R_COMP_RERENDER;
371         G.scene->r.actlay= node->custom1;
372         
373         BIF_do_render(0);
374         
375         G.scene->r.scemode= scemode;
376         G.scene->r.actlay= actlay;
377
378         node->custom2= 0;
379         
380         if(scene) {
381                 G.scene->r= rd;
382                 set_scene_bg(scene);
383         }
384 }
385
386 static void composit_node_event(SpaceNode *snode, short event)
387 {
388         
389         switch(event) {
390                 case B_REDR:
391                         // allqueue(REDRAWNODE, 1);
392                         break;
393                 case B_NODE_LOADIMAGE:
394                 {
395                         bNode *node= nodeGetActive(snode->edittree);
396                         char name[FILE_MAXDIR+FILE_MAXFILE];
397                         
398                         if(node->id)
399                                 strcpy(name, ((Image *)node->id)->name);
400                         else strcpy(name, U.textudir);
401                         if (G.qual & LR_CTRLKEY) {
402                                 activate_imageselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
403                         } else {
404                                 activate_fileselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
405                         }
406                         break;
407                 }
408                 case B_NODE_SETIMAGE:
409                 {
410                         bNode *node= nodeGetActive(snode->edittree);
411                         char name[FILE_MAXDIR+FILE_MAXFILE];
412                         
413                         strcpy(name, ((NodeImageFile *)node->storage)->name);
414                         if (G.qual & LR_CTRLKEY) {
415                                 activate_imageselect(FILE_SPECIAL, "SELECT OUTPUT DIR", name, set_node_imagepath);
416                         } else {
417                                 activate_fileselect(FILE_SPECIAL, "SELECT OUTPUT DIR", name, set_node_imagepath);
418                         }
419                         break;
420                 }
421                 case B_NODE_TREE_EXEC:
422                         // XXX                  snode_handle_recalc(snode);
423                         break;          
424                 default:
425                         /* B_NODE_EXEC */
426                 {
427                         bNode *node= BLI_findlink(&snode->edittree->nodes, event-B_NODE_EXEC);
428                         if(node) {
429                                 NodeTagChanged(snode->edittree, node);
430                                 /* don't use NodeTagIDChanged, it gives far too many recomposites for image, scene layers, ... */
431                                 
432                                 /* not the best implementation of the world... but we need it to work now :) */
433                                 if(node->type==CMP_NODE_R_LAYERS && node->custom2) {
434                                         /* add event for this window (after render curarea can be changed) */
435                                         addqueue(curarea->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
436                                         
437                                         composite_node_render(snode, node);
438                                         // XXX                  snode_handle_recalc(snode);
439                                         
440                                         /* add another event, a render can go fullscreen and open new window */
441                                         addqueue(curarea->win, UI_BUT_EVENT, B_NODE_TREE_EXEC);
442                                 }
443                                 else {
444                                         node= snode_get_editgroup(snode);
445                                         if(node)
446                                                 NodeTagIDChanged(snode->nodetree, node->id);
447                                         
448                                         // XXX                  snode_handle_recalc(snode);
449                                 }
450                         }
451                 }                       
452         }
453 }
454
455 static void texture_node_event(SpaceNode *snode, short event)
456 {
457         switch(event) {
458                 case B_REDR:
459                         // allqueue(REDRAWNODE, 1);
460                         break;
461                 case B_NODE_LOADIMAGE:
462                 {
463                         bNode *node= nodeGetActive(snode->edittree);
464                         char name[FILE_MAXDIR+FILE_MAXFILE];
465                         
466                         if(node->id)
467                                 strcpy(name, ((Image *)node->id)->name);
468                         else strcpy(name, U.textudir);
469                         if (G.qual & LR_CTRLKEY) {
470                                 activate_imageselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
471                         } else {
472                                 activate_fileselect(FILE_SPECIAL, "SELECT IMAGE", name, load_node_image);
473                         }
474                         break;
475                 }
476                 default:
477                         /* B_NODE_EXEC */
478                         ntreeTexCheckCyclics( snode->nodetree );
479                         // XXX                  snode_handle_recalc(snode);
480                         // allqueue(REDRAWNODE, 1);
481                         break;
482         }
483 }
484
485 #endif /* 0  */
486 /* assumes nothing being done in ntree yet, sets the default in/out node */
487 /* called from shading buttons or header */
488 void ED_node_shader_default(Material *ma)
489 {
490         bNode *in, *out;
491         bNodeSocket *fromsock, *tosock;
492         
493         /* but lets check it anyway */
494         if(ma->nodetree) {
495                 printf("error in shader initialize\n");
496                 return;
497         }
498         
499         ma->nodetree= ntreeAddTree(NTREE_SHADER);
500         
501         out= nodeAddNodeType(ma->nodetree, SH_NODE_OUTPUT, NULL, NULL);
502         out->locx= 300.0f; out->locy= 300.0f;
503         
504         in= nodeAddNodeType(ma->nodetree, SH_NODE_MATERIAL, NULL, NULL);
505         in->locx= 10.0f; in->locy= 300.0f;
506         nodeSetActive(ma->nodetree, in);
507         
508         /* only a link from color to color */
509         fromsock= in->outputs.first;
510         tosock= out->inputs.first;
511         nodeAddLink(ma->nodetree, in, fromsock, out, tosock);
512         
513         ntreeSolveOrder(ma->nodetree);  /* needed for pointers */
514 }
515
516 /* assumes nothing being done in ntree yet, sets the default in/out node */
517 /* called from shading buttons or header */
518 void ED_node_composit_default(Scene *sce)
519 {
520         bNode *in, *out;
521         bNodeSocket *fromsock, *tosock;
522         
523         /* but lets check it anyway */
524         if(sce->nodetree) {
525                 printf("error in composit initialize\n");
526                 return;
527         }
528         
529         sce->nodetree= ntreeAddTree(NTREE_COMPOSIT);
530         
531         out= nodeAddNodeType(sce->nodetree, CMP_NODE_COMPOSITE, NULL, NULL);
532         out->locx= 300.0f; out->locy= 400.0f;
533         out->id= &sce->id;
534         
535         in= nodeAddNodeType(sce->nodetree, CMP_NODE_R_LAYERS, NULL, NULL);
536         in->locx= 10.0f; in->locy= 400.0f;
537         in->id= &sce->id;
538         nodeSetActive(sce->nodetree, in);
539         
540         /* links from color to color */
541         fromsock= in->outputs.first;
542         tosock= out->inputs.first;
543         nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
544         
545         ntreeSolveOrder(sce->nodetree); /* needed for pointers */
546         
547         // XXX ntreeCompositForceHidden(sce->nodetree);
548 }
549
550 /* assumes nothing being done in ntree yet, sets the default in/out node */
551 /* called from shading buttons or header */
552 void ED_node_texture_default(Tex *tx)
553 {
554         bNode *in, *out;
555         bNodeSocket *fromsock, *tosock;
556         
557         /* but lets check it anyway */
558         if(tx->nodetree) {
559                 printf("error in texture initialize\n");
560                 return;
561         }
562         
563         tx->nodetree= ntreeAddTree(NTREE_TEXTURE);
564         
565         out= nodeAddNodeType(tx->nodetree, TEX_NODE_OUTPUT, NULL, NULL);
566         out->locx= 300.0f; out->locy= 300.0f;
567         
568         in= nodeAddNodeType(tx->nodetree, TEX_NODE_CHECKER, NULL, NULL);
569         in->locx= 10.0f; in->locy= 300.0f;
570         nodeSetActive(tx->nodetree, in);
571         
572         fromsock= in->outputs.first;
573         tosock= out->inputs.first;
574         nodeAddLink(tx->nodetree, in, fromsock, out, tosock);
575         
576         ntreeSolveOrder(tx->nodetree);  /* needed for pointers */
577 }
578
579 /* Here we set the active tree(s), even called for each redraw now, so keep it fast :) */
580 void snode_set_context(SpaceNode *snode, Scene *scene)
581 {
582         Object *ob= OBACT;
583         bNode *node= NULL;
584         
585         snode->nodetree= NULL;
586         snode->id= snode->from= NULL;
587         
588         if(snode->treetype==NTREE_SHADER) {
589                 /* need active object, or we allow pinning... */
590                 if(ob) {
591                         Material *ma= give_current_material(ob, ob->actcol);
592                         if(ma) {
593                                 snode->from= &ob->id;
594                                 snode->id= &ma->id;
595                                 snode->nodetree= ma->nodetree;
596                         }
597                 }
598         }
599         else if(snode->treetype==NTREE_COMPOSIT) {
600                 snode->from= NULL;
601                 snode->id= &scene->id;
602                 
603                 /* bit clumsy but reliable way to see if we draw first time */
604                 if(snode->nodetree==NULL)
605                         ntreeCompositForceHidden(scene->nodetree, scene);
606                 
607                 snode->nodetree= scene->nodetree;
608         }
609         else if(snode->treetype==NTREE_TEXTURE) {
610                 Tex *tx= NULL;
611
612                 if(snode->texfrom==SNODE_TEX_OBJECT) {
613                         if(ob) {
614                                 tx= give_current_texture(ob, ob->actcol);
615
616                                 if(ob->type == OB_LAMP)
617                                         snode->from= (ID*)ob->data;
618                                 else
619                                         snode->from= (ID*)give_current_material(ob, ob->actcol);
620
621                                 /* from is not set fully for material nodes, should be ID + Node then */
622                         }
623                 }
624                 else if(snode->texfrom==SNODE_TEX_WORLD) {
625                         tx= give_current_world_texture(scene);
626                         snode->from= (ID *)scene->world;
627                 }
628                 else {
629                         MTex *mtex= NULL;
630                         Brush *brush= NULL;
631                         
632                         if(ob && (ob->mode & OB_MODE_SCULPT))
633                                 brush= paint_brush(&scene->toolsettings->sculpt->paint);
634                         else
635                                 brush= paint_brush(&scene->toolsettings->imapaint.paint);
636
637                         if(brush && brush->texact != -1)
638                                 mtex= brush->mtex[brush->texact];
639
640                         snode->from= (ID *)brush;
641
642                         if(mtex)
643                                 tx= mtex->tex;
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                                 
1114                         ED_region_tag_redraw(ar);
1115
1116                         break;
1117                         
1118                 case LEFTMOUSE:
1119                 case MIDDLEMOUSE:
1120                 case RIGHTMOUSE:
1121                         
1122                         MEM_freeN(nsw);
1123                         op->customdata= NULL;
1124                         
1125                         return OPERATOR_FINISHED;
1126         }
1127         
1128         return OPERATOR_RUNNING_MODAL;
1129 }
1130
1131 static int node_resize_invoke(bContext *C, wmOperator *op, wmEvent *event)
1132 {
1133         SpaceNode *snode= CTX_wm_space_node(C);
1134         ARegion *ar= CTX_wm_region(C);
1135         bNode *node= editnode_get_active(snode->edittree);
1136         
1137         if(node) {
1138                 rctf totr;
1139                 
1140                 UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1141                                                                  &snode->mx, &snode->my);
1142                 totr= node->totr;
1143                 totr.xmin= totr.xmax-10.0f;
1144                 totr.ymax= totr.ymin+10.0f;
1145                 
1146                 if(BLI_in_rctf(&totr, snode->mx, snode->my)) {
1147                         NodeSizeWidget *nsw= MEM_callocN(sizeof(NodeSizeWidget), "size widget op data");
1148                         
1149                         op->customdata= nsw;
1150                         nsw->mxstart= snode->mx;
1151                         
1152                         /* store old */
1153                         if(node->flag & NODE_HIDDEN)
1154                                 nsw->oldwidth= node->miniwidth;
1155                         else
1156                                 nsw->oldwidth= node->width;
1157                         
1158                         /* add modal handler */
1159                         WM_event_add_modal_handler(C, &CTX_wm_window(C)->handlers, op);
1160
1161                         return OPERATOR_RUNNING_MODAL;
1162                 }
1163         }
1164         return OPERATOR_PASS_THROUGH;
1165 }
1166
1167 void NODE_OT_resize(wmOperatorType *ot)
1168 {
1169         /* identifiers */
1170         ot->name= "Resize Node";
1171         ot->idname= "NODE_OT_resize";
1172         
1173         /* api callbacks */
1174         ot->invoke= node_resize_invoke;
1175         ot->modal= node_resize_modal;
1176         ot->poll= ED_operator_node_active;
1177         
1178         /* flags */
1179         ot->flag= OPTYPE_BLOCKING;
1180 }
1181
1182
1183 #if 0
1184
1185 /* ******************** rename ******************* */
1186
1187 void node_rename(SpaceNode *snode)
1188 {
1189         bNode *node, *rename_node;
1190         short found_node= 0;
1191
1192         /* check if a node is selected */
1193         for(node= snode->edittree->nodes.first; node; node= node->next) {
1194                 if(node->flag & SELECT) {
1195                         found_node= 1;
1196                         break;
1197                 }
1198         }
1199
1200         if(found_node) {
1201                 rename_node= nodeGetActive(snode->edittree);
1202                 node_rename_but((char *)rename_node->username);
1203         
1204                 // allqueue(REDRAWNODE, 1);
1205         }
1206 }
1207
1208 /* ********************** select ******************** */
1209
1210 /* used in buttons to check context, also checks for edited groups */
1211 bNode *editnode_get_active_idnode(bNodeTree *ntree, short id_code)
1212 {
1213         return nodeGetActiveID(ntree, id_code);
1214 }
1215
1216 /* used in buttons to check context, also checks for edited groups */
1217 Material *editnode_get_active_material(Material *ma)
1218 {
1219         if(ma && ma->use_nodes && ma->nodetree) {
1220                 bNode *node= editnode_get_active_idnode(ma->nodetree, ID_MA);
1221                 if(node)
1222                         return (Material *)node->id;
1223                 else
1224                         return NULL;
1225         }
1226         return ma;
1227 }
1228 #endif /* 0 */
1229
1230
1231 /* no undo here! */
1232 void node_deselectall(SpaceNode *snode, int swap)
1233 {
1234         bNode *node;
1235         
1236         if(swap) {
1237                 for(node= snode->edittree->nodes.first; node; node= node->next)
1238                         if(node->flag & SELECT)
1239                                 break;
1240                 if(node==NULL) {
1241                         for(node= snode->edittree->nodes.first; node; node= node->next)
1242                                 node->flag |= SELECT;
1243                         return;
1244                 }
1245                 /* else pass on to deselect */
1246         }
1247         
1248         for(node= snode->edittree->nodes.first; node; node= node->next)
1249                 node->flag &= ~SELECT;
1250 }
1251
1252
1253 int node_has_hidden_sockets(bNode *node)
1254 {
1255         bNodeSocket *sock;
1256         
1257         for(sock= node->inputs.first; sock; sock= sock->next)
1258                 if(sock->flag & SOCK_HIDDEN)
1259                         return 1;
1260         for(sock= node->outputs.first; sock; sock= sock->next)
1261                 if(sock->flag & SOCK_HIDDEN)
1262                         return 1;
1263         return 0;
1264 }
1265
1266
1267 static void node_hide_unhide_sockets(SpaceNode *snode, bNode *node)
1268 {
1269         bNodeSocket *sock;
1270         
1271         /* unhide all */
1272         if( node_has_hidden_sockets(node) ) {
1273                 for(sock= node->inputs.first; sock; sock= sock->next)
1274                         sock->flag &= ~SOCK_HIDDEN;
1275                 for(sock= node->outputs.first; sock; sock= sock->next)
1276                         sock->flag &= ~SOCK_HIDDEN;
1277         }
1278         else {
1279                 bNode *gnode= snode_get_editgroup(snode);
1280                 
1281                 /* hiding inside group should not break links in other group users */
1282                 if(gnode) {
1283                         nodeGroupSocketUseFlags((bNodeTree *)gnode->id);
1284                         for(sock= node->inputs.first; sock; sock= sock->next)
1285                                 if(!(sock->flag & SOCK_IN_USE))
1286                                         if(sock->link==NULL)
1287                                                 sock->flag |= SOCK_HIDDEN;
1288                         for(sock= node->outputs.first; sock; sock= sock->next)
1289                                 if(!(sock->flag & SOCK_IN_USE))
1290                                         if(nodeCountSocketLinks(snode->edittree, sock)==0)
1291                                                 sock->flag |= SOCK_HIDDEN;
1292                 }
1293                 else {
1294                         /* hide unused sockets */
1295                         for(sock= node->inputs.first; sock; sock= sock->next) {
1296                                 if(sock->link==NULL)
1297                                         sock->flag |= SOCK_HIDDEN;
1298                         }
1299                         for(sock= node->outputs.first; sock; sock= sock->next) {
1300                                 if(nodeCountSocketLinks(snode->edittree, sock)==0)
1301                                         sock->flag |= SOCK_HIDDEN;
1302                         }
1303                 }
1304         }
1305
1306         // allqueue(REDRAWNODE, 1);
1307         snode_verify_groups(snode);
1308
1309 }
1310
1311 /*static*/ int do_header_node(SpaceNode *snode, bNode *node, float mx, float my)
1312 {
1313         rctf totr= node->totr;
1314         
1315         totr.ymin= totr.ymax-20.0f;
1316         
1317         totr.xmax= totr.xmin+15.0f;
1318         if(BLI_in_rctf(&totr, mx, my)) {
1319                 node->flag |= NODE_HIDDEN;
1320                 // allqueue(REDRAWNODE, 0);
1321                 return 1;
1322         }       
1323         
1324         totr.xmax= node->totr.xmax;
1325         totr.xmin= totr.xmax-18.0f;
1326         if(node->typeinfo->flag & NODE_PREVIEW) {
1327                 if(BLI_in_rctf(&totr, mx, my)) {
1328                         node->flag ^= NODE_PREVIEW;
1329                         // allqueue(REDRAWNODE, 0);
1330                         return 1;
1331                 }
1332                 totr.xmin-=18.0f;
1333         }
1334         if(node->type == NODE_GROUP) {
1335                 if(BLI_in_rctf(&totr, mx, my)) {
1336                         snode_make_group_editable(snode, node);
1337                         return 1;
1338                 }
1339                 totr.xmin-=18.0f;
1340         }
1341         if(node->typeinfo->flag & NODE_OPTIONS) {
1342                 if(BLI_in_rctf(&totr, mx, my)) {
1343                         node->flag ^= NODE_OPTIONS;
1344                         // allqueue(REDRAWNODE, 0);
1345                         return 1;
1346                 }
1347                 totr.xmin-=18.0f;
1348         }
1349         /* hide unused sockets */
1350         if(BLI_in_rctf(&totr, mx, my)) {
1351                 node_hide_unhide_sockets(snode, node);
1352         }
1353         
1354         
1355         totr= node->totr;
1356         totr.xmin= totr.xmax-10.0f;
1357         totr.ymax= totr.ymin+10.0f;
1358         if(BLI_in_rctf(&totr, mx, my)) {
1359 //              scale_node(snode, node);
1360                 return 1;
1361         }
1362         return 0;
1363 }
1364
1365 /*static*/ int do_header_hidden_node(SpaceNode *snode, bNode *node, float mx, float my)
1366 {
1367         rctf totr= node->totr;
1368         
1369         totr.xmax= totr.xmin+15.0f;
1370         if(BLI_in_rctf(&totr, mx, my)) {
1371                 node->flag &= ~NODE_HIDDEN;
1372                 // allqueue(REDRAWNODE, 0);
1373                 return 1;
1374         }       
1375         
1376         totr.xmax= node->totr.xmax;
1377         totr.xmin= node->totr.xmax-15.0f;
1378         if(BLI_in_rctf(&totr, mx, my)) {
1379 //              scale_node(snode, node);
1380                 return 1;
1381         }
1382         return 0;
1383 }
1384
1385 static void node_link_viewer(SpaceNode *snode, bNode *tonode)
1386 {
1387         bNode *node;
1388
1389         /* context check */
1390         if(tonode==NULL || tonode->outputs.first==NULL)
1391                 return;
1392         if( ELEM(tonode->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1393                 return;
1394         
1395         /* get viewer */
1396         for(node= snode->edittree->nodes.first; node; node= node->next)
1397                 if( ELEM(node->type, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER)) 
1398                         if(node->flag & NODE_DO_OUTPUT)
1399                                 break;
1400                 
1401         if(node) {
1402                 bNodeLink *link;
1403                 
1404                 /* get link to viewer */
1405                 for(link= snode->edittree->links.first; link; link= link->next)
1406                         if(link->tonode==node)
1407                                 break;
1408
1409                 if(link) {
1410                         link->fromnode= tonode;
1411                         link->fromsock= tonode->outputs.first;
1412                         NodeTagChanged(snode->edittree, node);
1413                         
1414 // XXX                  snode_handle_recalc(snode);
1415                 }
1416         }
1417 }
1418
1419
1420 void node_active_link_viewer(SpaceNode *snode)
1421 {
1422         bNode *node= editnode_get_active(snode->edittree);
1423         if(node)
1424                 node_link_viewer(snode, node);
1425 }
1426
1427 /* return 0, nothing done */
1428 /*static*/ int node_mouse_groupheader(SpaceNode *snode)
1429 {
1430         bNode *gnode;
1431         float mx=0, my=0;
1432 // XXX  short mval[2];
1433         
1434         gnode= snode_get_editgroup(snode);
1435         if(gnode==NULL) return 0;
1436         
1437 // XXX  getmouseco_areawin(mval);
1438 // XXX  areamouseco_to_ipoco(G.v2d, mval, &mx, &my);
1439         
1440         /* click in header or outside? */
1441         if(BLI_in_rctf(&gnode->totr, mx, my)==0) {
1442                 rctf rect= gnode->totr;
1443                 
1444                 rect.ymax += NODE_DY;
1445                 if(BLI_in_rctf(&rect, mx, my)==0)
1446                         snode_make_group_editable(snode, NULL); /* toggles, so exits editmode */
1447 //              else
1448 // XXX                  transform_nodes(snode->nodetree, 'g', "Move group");
1449                 
1450                 return 1;
1451         }
1452         return 0;
1453 }
1454
1455 /* checks snode->mouse position, and returns found node/socket */
1456 /* type is SOCK_IN and/or SOCK_OUT */
1457 static int find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **sockp, int in_out)
1458 {
1459         bNode *node;
1460         bNodeSocket *sock;
1461         rctf rect;
1462         
1463         /* check if we click in a socket */
1464         for(node= snode->edittree->nodes.first; node; node= node->next) {
1465                 
1466                 rect.xmin = snode->mx - NODE_SOCKSIZE+3;
1467                 rect.ymin = snode->my - NODE_SOCKSIZE+3;
1468                 rect.xmax = rect.xmin + 2*NODE_SOCKSIZE+6;
1469                 rect.ymax = rect.ymin + 2*NODE_SOCKSIZE+6;
1470                 
1471                 if (!(node->flag & NODE_HIDDEN)) {
1472                         /* extra padding inside and out - allow dragging on the text areas too */
1473                         if (in_out == SOCK_IN) {
1474                                 rect.xmax += NODE_SOCKSIZE;
1475                                 rect.xmin -= NODE_SOCKSIZE*4;
1476                         } else if (in_out == SOCK_OUT) {
1477                                 rect.xmax += NODE_SOCKSIZE*4;
1478                                 rect.xmin -= NODE_SOCKSIZE;
1479                         }
1480                 }
1481                 
1482                 if(in_out & SOCK_IN) {
1483                         for(sock= node->inputs.first; sock; sock= sock->next) {
1484                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1485                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1486                                                 if(node == visible_node(snode, &rect)) {
1487                                                         *nodep= node;
1488                                                         *sockp= sock;
1489                                                         return 1;
1490                                                 }
1491                                         }
1492                                 }
1493                         }
1494                 }
1495                 if(in_out & SOCK_OUT) {
1496                         for(sock= node->outputs.first; sock; sock= sock->next) {
1497                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1498                                         if(BLI_in_rctf(&rect, sock->locx, sock->locy)) {
1499                                                 if(node == visible_node(snode, &rect)) {
1500                                                         *nodep= node;
1501                                                         *sockp= sock;
1502                                                         return 1;
1503                                                 }
1504                                         }
1505                                 }
1506                         }
1507                 }
1508         }
1509         return 0;
1510 }
1511
1512 static int node_socket_hilights(SpaceNode *snode, int in_out)
1513 {
1514         bNode *node;
1515         bNodeSocket *sock, *tsock, *socksel= NULL;
1516         short redraw= 0;
1517         
1518         if(snode->edittree==NULL) return 0;
1519         
1520         /* deselect socks */
1521         for(node= snode->edittree->nodes.first; node; node= node->next) {
1522                 for(sock= node->inputs.first; sock; sock= sock->next) {
1523                         if(sock->flag & SELECT) {
1524                                 sock->flag &= ~SELECT;
1525                                 redraw++;
1526                                 socksel= sock;
1527                         }
1528                 }
1529                 for(sock= node->outputs.first; sock; sock= sock->next) {
1530                         if(sock->flag & SELECT) {
1531                                 sock->flag &= ~SELECT;
1532                                 redraw++;
1533                                 socksel= sock;
1534                         }
1535                 }
1536         }
1537         
1538         // XXX mousepos should be set here!
1539         
1540         if(find_indicated_socket(snode, &node, &tsock, in_out)) {
1541                 tsock->flag |= SELECT;
1542                 if(redraw==1 && tsock==socksel) redraw= 0;
1543                 else redraw= 1;
1544         }
1545         
1546         return redraw;
1547 }
1548
1549 /* ****************** Add *********************** */
1550
1551 void snode_autoconnect(SpaceNode *snode, bNode *node_to, int flag)
1552 {
1553         bNodeSocket *sock, *sockfrom[8];
1554         bNode *node, *nodefrom[8];
1555         int totsock= 0, socktype=0;
1556
1557         if(node_to==NULL || node_to->inputs.first==NULL)
1558                 return;
1559         
1560         /* no inputs for node allowed (code it) */
1561
1562         /* connect first 1 socket type now */
1563         for(sock= node_to->inputs.first; sock; sock= sock->next)
1564                 if(socktype<sock->type)
1565                         socktype= sock->type;
1566
1567         
1568         /* find potential sockets, max 8 should work */
1569         for(node= snode->edittree->nodes.first; node; node= node->next) {
1570                 if((node->flag & flag) && node!=node_to) {
1571                         for(sock= node->outputs.first; sock; sock= sock->next) {
1572                                 if(!(sock->flag & (SOCK_HIDDEN|SOCK_UNAVAIL))) {
1573                                         sockfrom[totsock]= sock;
1574                                         nodefrom[totsock]= node;
1575                                         totsock++;
1576                                         if(totsock>7)
1577                                                 break;
1578                                 }
1579                         }
1580                 }
1581                 if(totsock>7)
1582                         break;
1583         }
1584
1585         /* now just get matching socket types and create links */
1586         for(sock= node_to->inputs.first; sock; sock= sock->next) {
1587                 int a;
1588                 
1589                 for(a=0; a<totsock; a++) {
1590                         if(sockfrom[a]) {
1591                                 if(sock->type==sockfrom[a]->type && sock->type==socktype) {
1592                                         nodeAddLink(snode->edittree, nodefrom[a], sockfrom[a], node_to, sock);
1593                                         sockfrom[a]= NULL;
1594                                         break;
1595                                 }
1596                         }
1597                 }
1598         }
1599         
1600         ntreeSolveOrder(snode->edittree);
1601 }
1602
1603
1604 /* can be called from menus too, but they should do own undopush and redraws */
1605 bNode *node_add_node(SpaceNode *snode, Scene *scene, int type, float locx, float locy)
1606 {
1607         bNode *node= NULL, *gnode;
1608         
1609         node_deselectall(snode, 0);
1610         
1611         if(type>=NODE_DYNAMIC_MENU) {
1612                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
1613         }
1614         else if(type>=NODE_GROUP_MENU) {
1615                 if(snode->edittree!=snode->nodetree) {
1616                         // XXX error("Can not add a Group in a Group");
1617                         return NULL;
1618                 }
1619                 else {
1620                         bNodeTree *ngroup= BLI_findlink(&G.main->nodetree, type-NODE_GROUP_MENU);
1621                         if(ngroup)
1622                                 node= nodeAddNodeType(snode->edittree, NODE_GROUP, ngroup, NULL);
1623                 }
1624         }
1625         else
1626                 node= nodeAddNodeType(snode->edittree, type, NULL, NULL);
1627         
1628         /* generics */
1629         if(node) {
1630                 node->locx= locx;
1631                 node->locy= locy + 60.0f;               // arbitrary.. so its visible
1632                 node->flag |= SELECT;
1633                 
1634                 gnode= snode_get_editgroup(snode);
1635                 if(gnode) {
1636                         node->locx -= gnode->locx;
1637                         node->locy -= gnode->locy;
1638                 }
1639
1640                 snode_verify_groups(snode);
1641                 node_set_active(snode, node);
1642                 
1643                 if(snode->nodetree->type==NTREE_COMPOSIT) {
1644                         if(ELEM(node->type, CMP_NODE_R_LAYERS, CMP_NODE_COMPOSITE))
1645                                 node->id = &scene->id;
1646                         
1647                         ntreeCompositForceHidden(snode->edittree, scene);
1648                 }
1649                         
1650                 if(node->id)
1651                         id_us_plus(node->id);
1652                         
1653                 NodeTagChanged(snode->edittree, node);
1654         }
1655         
1656         if(snode->nodetree->type==NTREE_TEXTURE) {
1657                 ntreeTexCheckCyclics(snode->edittree);
1658         }
1659         
1660         return node;
1661 }
1662
1663 #if 0
1664
1665 void node_mute(SpaceNode *snode)
1666 {
1667         bNode *node;
1668
1669         /* no disabling inside of groups */
1670         if(snode_get_editgroup(snode))
1671                 return;
1672         
1673         for(node= snode->edittree->nodes.first; node; node= node->next) {
1674                 if(node->flag & SELECT) {
1675                         if(node->inputs.first && node->outputs.first) {
1676                                 if(node->flag & NODE_MUTED)
1677                                         node->flag &= ~NODE_MUTED;
1678                                 else
1679                                         node->flag |= NODE_MUTED;
1680                         }
1681                 }
1682         }
1683         
1684
1685 }
1686
1687 #endif
1688
1689 int node_duplicate_exec(bContext *C, wmOperator *op)
1690 {
1691         SpaceNode *snode= CTX_wm_space_node(C);
1692         
1693         ntreeCopyTree(snode->edittree, 1);      /* 1 == internally selected nodes */
1694         
1695         ntreeSolveOrder(snode->edittree);
1696         snode_verify_groups(snode);
1697         snode_handle_recalc(C, snode);
1698
1699         return OPERATOR_FINISHED;
1700 }
1701
1702 static int node_duplicate_invoke(bContext *C, wmOperator *op, wmEvent *event)
1703 {
1704         node_duplicate_exec(C, op);
1705         
1706         RNA_int_set(op->ptr, "mode", TFM_TRANSLATION);
1707         WM_operator_name_call(C, "TFM_OT_transform", WM_OP_INVOKE_REGION_WIN, op->ptr);
1708         
1709         return OPERATOR_FINISHED;
1710 }
1711
1712 void NODE_OT_duplicate(wmOperatorType *ot)
1713 {
1714         
1715         /* identifiers */
1716         ot->name= "Duplicate Nodes";
1717         ot->description = "Duplicate the nodes.";
1718         ot->idname= "NODE_OT_duplicate";
1719         
1720         /* api callbacks */
1721         ot->invoke= node_duplicate_invoke;
1722         ot->exec= node_duplicate_exec;
1723         
1724         ot->poll= ED_operator_node_active;
1725         
1726         /* flags */
1727         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1728         
1729         /* to give to transform */
1730         RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX);
1731 }
1732
1733 #if 0
1734
1735 static void node_insert_convertor(SpaceNode *snode, bNodeLink *link)
1736 {
1737         bNode *newnode= NULL;
1738         
1739         if(link->fromsock->type==SOCK_RGBA && link->tosock->type==SOCK_VALUE) {
1740                 if(snode->edittree->type==NTREE_SHADER)
1741                         newnode= node_add_node(snode, SH_NODE_RGBTOBW, 0.0f, 0.0f);
1742                 else if(snode->edittree->type==NTREE_COMPOSIT)
1743                         newnode= node_add_node(snode, CMP_NODE_RGBTOBW, 0.0f, 0.0f);
1744                 else
1745                         newnode= NULL;
1746         }
1747         else if(link->fromsock->type==SOCK_VALUE && link->tosock->type==SOCK_RGBA) {
1748                 if(snode->edittree->type==NTREE_SHADER)
1749                         newnode= node_add_node(snode, SH_NODE_VALTORGB, 0.0f, 0.0f);
1750                 else if(snode->edittree->type==NTREE_COMPOSIT)
1751                         newnode= node_add_node(snode, CMP_NODE_VALTORGB, 0.0f, 0.0f);
1752                 else
1753                         newnode= NULL;
1754         }
1755         
1756         if(newnode) {
1757                 /* dangerous assumption to use first in/out socks, but thats fine for now */
1758                 newnode->flag |= NODE_HIDDEN;
1759                 newnode->locx= 0.5f*(link->fromsock->locx + link->tosock->locx);
1760                 newnode->locy= 0.5f*(link->fromsock->locy + link->tosock->locy) + HIDDEN_RAD;
1761                 
1762                 nodeAddLink(snode->edittree, newnode, newnode->outputs.first, link->tonode, link->tosock);
1763                 link->tonode= newnode;
1764                 link->tosock= newnode->inputs.first;
1765         }
1766 }
1767
1768
1769 #endif /* 0 */
1770
1771 /* *************************** add link op ******************** */
1772
1773 /* temp data to pass on to modal */
1774 typedef struct NodeLinkDrag
1775 {
1776         bNode *node;
1777         bNodeSocket *sock;
1778         bNodeLink *link;
1779         int in_out;
1780 } NodeLinkDrag;
1781
1782 /*static*/ void reset_sel_socket(SpaceNode *snode, int in_out)
1783 {
1784         bNode *node;
1785         bNodeSocket *sock;
1786         
1787         for(node= snode->edittree->nodes.first; node; node= node->next) {
1788                 if(in_out & SOCK_IN) {
1789                         for(sock= node->inputs.first; sock; sock= sock->next)
1790                                 if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
1791                 }
1792                 if(in_out & SOCK_OUT) {
1793                         for(sock= node->outputs.first; sock; sock= sock->next)
1794                                 if(sock->flag & SOCK_SEL) sock->flag&= ~SOCK_SEL;
1795                 }
1796         }
1797 }
1798
1799
1800 static void node_remove_extra_links(SpaceNode *snode, bNodeSocket *tsock, bNodeLink *link)
1801 {
1802         bNodeLink *tlink;
1803         bNodeSocket *sock;
1804         
1805         if(tsock && nodeCountSocketLinks(snode->edittree, link->tosock) > tsock->limit) {
1806                 
1807                 for(tlink= snode->edittree->links.first; tlink; tlink= tlink->next) {
1808                         if(link!=tlink && tlink->tosock==link->tosock)
1809                                 break;
1810                 }
1811                 if(tlink) {
1812                         /* is there a free input socket with same type? */
1813                         for(sock= tlink->tonode->inputs.first; sock; sock= sock->next) {
1814                                 if(sock->type==tlink->fromsock->type)
1815                                         if(nodeCountSocketLinks(snode->edittree, sock) < sock->limit)
1816                                                 break;
1817                         }
1818                         if(sock) {
1819                                 tlink->tosock= sock;
1820                                 sock->flag &= ~SOCK_HIDDEN;
1821                         }
1822                         else {
1823                                 nodeRemLink(snode->edittree, tlink);
1824                         }
1825                 }
1826         }
1827 }
1828
1829 /* loop that adds a nodelink, called by function below  */
1830 /* in_out = starting socket */
1831 static int node_link_modal(bContext *C, wmOperator *op, wmEvent *event)
1832 {
1833         SpaceNode *snode= CTX_wm_space_node(C);
1834         ARegion *ar= CTX_wm_region(C);
1835         NodeLinkDrag *nldrag= op->customdata;
1836         bNode *tnode, *node;
1837         bNodeSocket *tsock= NULL, *sock;
1838         bNodeLink *link;
1839         int in_out;
1840
1841         in_out= nldrag->in_out;
1842         node= nldrag->node;
1843         sock= nldrag->sock;
1844         link= nldrag->link;
1845         
1846         UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1847                                                          &snode->mx, &snode->my);
1848
1849         switch (event->type) {
1850                 case MOUSEMOVE:
1851                         
1852                         if(in_out==SOCK_OUT) {
1853                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_IN)) {
1854                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
1855                                                 if(tnode!=node  && link->tonode!=tnode && link->tosock!= tsock) {
1856                                                         link->tonode= tnode;
1857                                                         link->tosock= tsock;
1858                                                         ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
1859                                                 }
1860                                         }
1861                                 }
1862                                 else {
1863                                         link->tonode= NULL;
1864                                         link->tosock= NULL;
1865                                 }
1866                         }
1867                         else {
1868                                 if(find_indicated_socket(snode, &tnode, &tsock, SOCK_OUT)) {
1869                                         if(nodeFindLink(snode->edittree, sock, tsock)==NULL) {
1870                                                 if(nodeCountSocketLinks(snode->edittree, tsock) < tsock->limit) {
1871                                                         if(tnode!=node && link->fromnode!=tnode && link->fromsock!= tsock) {
1872                                                                 link->fromnode= tnode;
1873                                                                 link->fromsock= tsock;
1874                                                                 ntreeSolveOrder(snode->edittree);       /* for interactive red line warning */
1875                                                         }
1876                                                 }
1877                                         }
1878                                 }
1879                                 else {
1880                                         link->fromnode= NULL;
1881                                         link->fromsock= NULL;
1882                                 }
1883                         }
1884                         /* hilight target sockets only */
1885                         node_socket_hilights(snode, in_out==SOCK_OUT?SOCK_IN:SOCK_OUT);
1886                         ED_region_tag_redraw(ar);
1887                         break;
1888                         
1889                 case LEFTMOUSE:
1890                 case RIGHTMOUSE:
1891                 case MIDDLEMOUSE:
1892         
1893                         /* remove link? */
1894                         if(link->tonode==NULL || link->fromnode==NULL) {
1895                                 nodeRemLink(snode->edittree, link);
1896                         }
1897                         else {
1898                                 /* send changed events for original tonode and new */
1899                                 if(link->tonode) 
1900                                         NodeTagChanged(snode->edittree, link->tonode);
1901                                 
1902                                 /* we might need to remove a link */
1903                                 if(in_out==SOCK_OUT) node_remove_extra_links(snode, link->tosock, link);
1904                         }
1905                         
1906                         ntreeSolveOrder(snode->edittree);
1907                         snode_verify_groups(snode);
1908                         snode_handle_recalc(C, snode);
1909                         
1910                         MEM_freeN(op->customdata);
1911                         op->customdata= NULL;
1912                         
1913                         return OPERATOR_FINISHED;
1914         }
1915         
1916         return OPERATOR_RUNNING_MODAL;
1917 }
1918
1919 /* return 1 when socket clicked */
1920 static int node_link_init(SpaceNode *snode, NodeLinkDrag *nldrag)
1921 {
1922         bNodeLink *link;
1923         
1924         /* output indicated? */
1925         if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_OUT)) {
1926                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
1927                         return SOCK_OUT;
1928                 else {
1929                         /* find if we break a link */
1930                         for(link= snode->edittree->links.first; link; link= link->next) {
1931                                 if(link->fromsock==nldrag->sock)
1932                                         break;
1933                         }
1934                         if(link) {
1935                                 nldrag->node= link->tonode;
1936                                 nldrag->sock= link->tosock;
1937                                 nodeRemLink(snode->edittree, link);
1938                                 return SOCK_IN;
1939                         }
1940                 }
1941         }
1942         /* or an input? */
1943         else if(find_indicated_socket(snode, &nldrag->node, &nldrag->sock, SOCK_IN)) {
1944                 if(nodeCountSocketLinks(snode->edittree, nldrag->sock) < nldrag->sock->limit)
1945                         return SOCK_IN;
1946                 else {
1947                         /* find if we break a link */
1948                         for(link= snode->edittree->links.first; link; link= link->next) {
1949                                 if(link->tosock==nldrag->sock)
1950                                         break;
1951                         }
1952                         if(link) {
1953                                 /* send changed event to original tonode */
1954                                 if(link->tonode) 
1955                                         NodeTagChanged(snode->edittree, link->tonode);
1956                                 
1957                                 nldrag->node= link->fromnode;
1958                                 nldrag->sock= link->fromsock;
1959                                 nodeRemLink(snode->edittree, link);
1960                                 return SOCK_OUT;
1961                         }
1962                 }
1963         }
1964         
1965         return 0;
1966 }
1967
1968 static int node_link_invoke(bContext *C, wmOperator *op, wmEvent *event)
1969 {
1970         SpaceNode *snode= CTX_wm_space_node(C);
1971         ARegion *ar= CTX_wm_region(C);
1972         NodeLinkDrag *nldrag= MEM_callocN(sizeof(NodeLinkDrag), "drag link op customdata");
1973         
1974         UI_view2d_region_to_view(&ar->v2d, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin, 
1975                                                          &snode->mx, &snode->my);
1976
1977         nldrag->in_out= node_link_init(snode, nldrag);
1978                 
1979         if(nldrag->in_out) {
1980                 op->customdata= nldrag;
1981                 
1982                 /* we make a temporal link */
1983                 if(nldrag->in_out==SOCK_OUT)
1984                         nldrag->link= nodeAddLink(snode->edittree, nldrag->node, nldrag->sock, NULL, NULL);
1985                 else
1986                         nldrag->link= nodeAddLink(snode->edittree, NULL, NULL, nldrag->node, nldrag->sock);
1987                 
1988                 /* add modal handler */
1989                 WM_event_add_modal_handler(C, &CTX_wm_window(C)->handlers, op);
1990                 
1991                 return OPERATOR_RUNNING_MODAL;
1992         }
1993         else {
1994                 MEM_freeN(nldrag);
1995                 return OPERATOR_CANCELLED|OPERATOR_PASS_THROUGH;
1996         }
1997 }
1998
1999 void NODE_OT_link(wmOperatorType *ot)
2000 {
2001         /* identifiers */
2002         ot->name= "Link Nodes";
2003         ot->idname= "NODE_OT_link";
2004         
2005         /* api callbacks */
2006         ot->invoke= node_link_invoke;
2007         ot->modal= node_link_modal;
2008 //      ot->exec= node_link_exec;
2009         ot->poll= ED_operator_node_active;
2010         
2011         /* flags */
2012         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
2013 }
2014
2015
2016 void node_delete(SpaceNode *snode)
2017 {
2018         bNode *node, *next;
2019         bNodeSocket *sock;
2020         
2021         for(node= snode->edittree->nodes.first; node; node= next) {
2022                 next= node->next;
2023                 if(node->flag & SELECT) {
2024                         /* set selin and selout NULL if the sockets belong to a node to be deleted */
2025                         for(sock= node->inputs.first; sock; sock= sock->next)
2026                                 if(snode->edittree->selin == sock) snode->edittree->selin= NULL;
2027
2028                         for(sock= node->outputs.first; sock; sock= sock->next)
2029                                 if(snode->edittree->selout == sock) snode->edittree->selout= NULL;
2030
2031                         /* check id user here, nodeFreeNode is called for free dbase too */
2032                         if(node->id)
2033                                 node->id->us--;
2034                         nodeFreeNode(snode->edittree, node);
2035                 }
2036         }
2037         
2038         snode_verify_groups(snode);
2039         // NODE_FIX_ME
2040         // snode_handle_recalc(snode);
2041         // allqueue(REDRAWNODE, 1);
2042 }
2043
2044
2045 void node_hide(SpaceNode *snode)
2046 {
2047         bNode *node;
2048         int nothidden=0, ishidden=0;
2049         
2050         for(node= snode->edittree->nodes.first; node; node= node->next) {
2051                 if(node->flag & SELECT) {
2052                         if(node->flag & NODE_HIDDEN)
2053                                 ishidden++;
2054                         else
2055                                 nothidden++;
2056                 }
2057         }
2058         for(node= snode->edittree->nodes.first; node; node= node->next) {
2059                 if(node->flag & SELECT) {
2060                         if( (ishidden && nothidden) || ishidden==0)
2061                                 node->flag |= NODE_HIDDEN;
2062                         else 
2063                                 node->flag &= ~NODE_HIDDEN;
2064                 }
2065         }
2066 }
2067
2068 #if 0
2069
2070 void node_insert_key(SpaceNode *snode)
2071 {
2072         bNode *node= editnode_get_active(snode->edittree);
2073         
2074         if(node == NULL)
2075                 return;
2076         
2077         if(node->type==CMP_NODE_TIME) {
2078                 if(node->custom1<node->custom2) {
2079
2080                         CurveMapping *cumap= node->storage;
2081                         float fval, curval;
2082                 
2083                         curval= (float)(CFRA - node->custom1)/(float)(node->custom2-node->custom1);
2084                         fval= curvemapping_evaluateF(cumap, 0, curval);
2085                         
2086                         if(fbutton(&fval, 0.0f, 1.0f, 10, 10, "Insert Value")) {
2087                                 curvemap_insert(cumap->cm, curval, fval);
2088
2089                         }
2090                 }
2091         }
2092 }
2093
2094 void node_select_linked(SpaceNode *snode, int out)
2095 {
2096         bNodeLink *link;
2097         bNode *node;
2098         
2099         /* NODE_TEST is the free flag */
2100         for(node= snode->edittree->nodes.first; node; node= node->next)
2101                 node->flag &= ~NODE_TEST;
2102
2103         for(link= snode->edittree->links.first; link; link= link->next) {
2104                 if(out) {
2105                         if(link->fromnode->flag & NODE_SELECT)
2106                                 link->tonode->flag |= NODE_TEST;
2107                 }
2108                 else {
2109                         if(link->tonode->flag & NODE_SELECT)
2110                                 link->fromnode->flag |= NODE_TEST;
2111                 }
2112         }
2113         
2114         for(node= snode->edittree->nodes.first; node; node= node->next)
2115                 if(node->flag & NODE_TEST)
2116                         node->flag |= NODE_SELECT;
2117         
2118 }
2119
2120 /* makes a link between selected output and input sockets */
2121 void node_make_link(SpaceNode *snode)
2122 {
2123         bNode *fromnode, *tonode;
2124         bNodeLink *link;
2125         bNodeSocket *outsock= snode->edittree->selout;
2126         bNodeSocket *insock= snode->edittree->selin;
2127
2128         if(!insock || !outsock) return;
2129         if(nodeFindLink(snode->edittree, outsock, insock)) return;
2130
2131         if(nodeFindNode(snode->edittree, outsock, &fromnode, NULL) &&
2132                 nodeFindNode(snode->edittree, insock, &tonode, NULL)) {
2133                 link= nodeAddLink(snode->edittree, fromnode, outsock, tonode, insock);
2134                 NodeTagChanged(snode->edittree, tonode);
2135                 node_remove_extra_links(snode, insock, link);
2136         }
2137         else return;
2138
2139         ntreeSolveOrder(snode->edittree);
2140         snode_verify_groups(snode);
2141         // XXX                  snode_handle_recalc(snode);
2142
2143 }
2144 #endif
2145
2146 /* ********************** Cut Link operator ***************** */
2147
2148 #define LINK_RESOL 12
2149 static int cut_links_intersect(bNodeLink *link, float mcoords[][2], int tot)
2150 {
2151         float coord_array[LINK_RESOL+1][2];
2152         int i, b;
2153         
2154         if(node_link_bezier_points(NULL, NULL, link, coord_array, LINK_RESOL)) {
2155
2156                 for(i=0; i<tot-1; i++)
2157                         for(b=0; b<LINK_RESOL-1; b++)
2158                                 if(IsectLL2Df(mcoords[i], mcoords[i+1], coord_array[b], coord_array[b+1]) > 0)
2159                                         return 1;
2160         }
2161         return 0;
2162 }
2163
2164 static int cut_links_exec(bContext *C, wmOperator *op)
2165 {
2166         SpaceNode *snode= CTX_wm_space_node(C);
2167         ARegion *ar= CTX_wm_region(C);
2168         float mcoords[256][2];
2169         int i= 0;
2170         
2171         RNA_BEGIN(op->ptr, itemptr, "path") {
2172                 float loc[2];
2173                 
2174                 RNA_float_get_array(&itemptr, "loc", loc);
2175                 UI_view2d_region_to_view(&ar->v2d, (short)loc[0], (short)loc[1], 
2176                                                                  &mcoords[i][0], &mcoords[i][1]);
2177                 i++;
2178                 if(i>= 256) break;
2179         }
2180         RNA_END;
2181         
2182         if(i>1) {
2183                 bNodeLink *link, *next;
2184                 
2185                 for(link= snode->edittree->links.first; link; link= next) {
2186                         next= link->next;
2187                         
2188                         if(cut_links_intersect(link, mcoords, i)) {
2189                                 NodeTagChanged(snode->edittree, link->tonode);
2190                                 nodeRemLink(snode->edittree, link);
2191                         }
2192                 }
2193
2194                 ntreeSolveOrder(snode->edittree);
2195                 snode_verify_groups(snode);
2196                 snode_handle_recalc(C, snode);
2197                 
2198                 return OPERATOR_FINISHED;
2199         }
2200         
2201         return OPERATOR_PASS_THROUGH;;
2202 }
2203
2204 void NODE_OT_links_cut(wmOperatorType *ot)
2205 {
2206         PropertyRNA *prop;
2207         
2208         ot->name= "Cut links";
2209         ot->idname= "NODE_OT_links_cut";
2210         
2211         ot->invoke= WM_gesture_lines_invoke;
2212         ot->modal= WM_gesture_lines_modal;
2213         ot->exec= cut_links_exec;
2214         
2215         ot->poll= ED_operator_node_active;
2216         
2217         /* flags */
2218         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2219         
2220         prop= RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
2221         RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
2222         /* internal */
2223         RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
2224 }
2225
2226 /* ******************************** */
2227
2228 /* goes over all scenes, reads render layerss */
2229 void node_read_renderlayers(SpaceNode *snode)
2230 {
2231         Scene *curscene= NULL; // XXX
2232         Scene *scene;
2233         bNode *node;
2234
2235         /* first tag scenes unread */
2236         for(scene= G.main->scene.first; scene; scene= scene->id.next) 
2237                 scene->id.flag |= LIB_DOIT;
2238
2239         for(node= snode->edittree->nodes.first; node; node= node->next) {
2240                 if(node->type==CMP_NODE_R_LAYERS) {
2241                         ID *id= node->id;
2242                         if(id->flag & LIB_DOIT) {
2243                                 RE_ReadRenderResult(curscene, (Scene *)id);
2244                                 ntreeCompositTagRender((Scene *)id);
2245                                 id->flag &= ~LIB_DOIT;
2246                         }
2247                 }
2248         }
2249         
2250         // XXX                  snode_handle_recalc(snode);
2251 }
2252
2253 void node_read_fullsamplelayers(SpaceNode *snode)
2254 {
2255         Scene *curscene= NULL; // XXX
2256         Render *re= RE_NewRender(curscene->id.name);
2257
2258         WM_cursor_wait(1);
2259
2260         //BIF_init_render_callbacks(re, 1);
2261         RE_MergeFullSample(re, curscene, snode->nodetree);
2262         //BIF_end_render_callbacks();
2263         
2264         // allqueue(REDRAWNODE, 1);
2265         // allqueue(REDRAWIMAGE, 1);
2266         
2267         WM_cursor_wait(0);
2268 }
2269
2270 void imagepaint_composite_tags(bNodeTree *ntree, Image *image, ImageUser *iuser)
2271 {
2272         bNode *node;
2273         
2274         if(ntree==NULL)
2275                 return;
2276         
2277         /* search for renderresults */
2278         if(image->type==IMA_TYPE_R_RESULT) {
2279                 for(node= ntree->nodes.first; node; node= node->next) {
2280                         if(node->type==CMP_NODE_R_LAYERS && node->id==NULL) {
2281                                 /* imageuser comes from ImageWin, so indexes are offset 1 */
2282                                 if(node->custom1==iuser->layer-1)
2283                                         NodeTagChanged(ntree, node);
2284                         }
2285                 }
2286         }
2287         else {
2288                 for(node= ntree->nodes.first; node; node= node->next) {
2289                         if(node->id== &image->id)
2290                                 NodeTagChanged(ntree, node);
2291                 }
2292         }
2293 }
2294
2295 /* ********************** */
2296
2297 void node_make_group(SpaceNode *snode)
2298 {
2299         bNode *gnode;
2300         
2301         if(snode->edittree!=snode->nodetree) {
2302 // XXX          error("Can not add a new Group in a Group");
2303                 return;
2304         }
2305         
2306         /* for time being... is too complex to handle */
2307         if(snode->treetype==NTREE_COMPOSIT) {
2308                 for(gnode=snode->nodetree->nodes.first; gnode; gnode= gnode->next) {
2309                         if(gnode->flag & SELECT)
2310                                 if(gnode->type==CMP_NODE_R_LAYERS)
2311                                         break;
2312                 }
2313                 if(gnode) {
2314 // XXX                  error("Can not add RenderLayer in a Group");
2315                         return;
2316                 }
2317         }
2318         
2319         gnode= nodeMakeGroupFromSelected(snode->nodetree);
2320         if(gnode==NULL) {
2321 // XXX          error("Can not make Group");
2322         }
2323         else {
2324                 nodeSetActive(snode->nodetree, gnode);
2325                 ntreeSolveOrder(snode->nodetree);
2326         }
2327 }
2328
2329 #if 0
2330
2331 /* ******************** main event loop ****************** */
2332
2333 void winqreadnodespace(ScrArea *sa, void *spacedata, BWinEvent *evt)
2334 {
2335         SpaceNode *snode= spacedata;
2336         bNode *actnode;
2337         bNodeSocket *actsock;
2338         unsigned short event= evt->event;
2339         short val= evt->val, doredraw=0, fromlib= 0;
2340         
2341         if(sa->win==0) return;
2342         
2343         if(snode->nodetree==NULL) {
2344                 /* no other events should be handled, but floating panels still should get handled */
2345                 uiDoBlocks(&curarea->uiblocks, event, 1);
2346                 return;
2347         }
2348         
2349         if(val) {
2350                 if( node_uiDoBlocks(sa, event)!=UI_NOTHING ) event= 0;
2351                 
2352                 fromlib= (snode->id && snode->id->lib);
2353                 
2354                 switch(event) {
2355                 case LEFTMOUSE:
2356                         if(gpencil_do_paint(sa, L_MOUSE)) {
2357                                 return;
2358                         }
2359                         else if(fromlib) {
2360                                 if(node_mouse_groupheader(snode)==0)
2361                                         //node_mouse_select(snode, event);
2362                         }
2363                         else {
2364                                 
2365                                 if(G.qual & LR_CTRLKEY)
2366                                         if(gesture())
2367                                                 break;
2368                                         
2369 //                              if(node_add_link(snode)==0)
2370                                         if(node_mouse_groupheader(snode)==0)
2371 //                                              if(node_mouse_select(snode, event)==0)
2372                                                         node_border_link_delete(snode);
2373                         }
2374                         break;
2375                         
2376                 case RIGHTMOUSE: 
2377                         if(gpencil_do_paint(sa, R_MOUSE)) {
2378                                 return;
2379                         }
2380                         else if(find_indicated_socket(snode, &actnode, &actsock, SOCK_IN)) {
2381                                 if(actsock->flag & SOCK_SEL) {
2382                                         snode->edittree->selin= NULL;
2383                                         actsock->flag&= ~SOCK_SEL;
2384                                 }
2385                                 else {
2386                                         snode->edittree->selin= actsock;
2387                                         reset_sel_socket(snode, SOCK_IN);
2388                                         actsock->flag|= SOCK_SEL;
2389                                 }
2390                         }
2391                         else if(find_indicated_socket(snode, &actnode, &actsock, SOCK_OUT)) {
2392                                 if(actsock->flag & SOCK_SEL) {
2393                                         snode->edittree->selout= NULL;
2394                                         actsock->flag&= ~SOCK_SEL;
2395                                 }
2396                                 else {
2397                                         snode->edittree->selout= actsock;
2398                                         reset_sel_socket(snode, SOCK_OUT);
2399                                         actsock->flag|= SOCK_SEL;
2400                                 }
2401                         }
2402 //                      else if(!node_mouse_select(snode, event)) 
2403 //                              toolbox_n();
2404
2405                         break;
2406                 case MIDDLEMOUSE:
2407                         if((snode->flag & SNODE_BACKDRAW) && (snode->treetype==NTREE_COMPOSIT)
2408                            && (G.qual==LR_SHIFTKEY)) {
2409                                 snode_bg_viewmove(snode);
2410                         } else {
2411                                 view2dmove(event);
2412                         }
2413                 case WHEELUPMOUSE:
2414                 case WHEELDOWNMOUSE:
2415                         view2dmove(event);      /* in drawipo.c */
2416                         break;
2417                         
2418                 case MOUSEY:
2419                         doredraw= node_socket_hilights(snode, SOCK_IN|SOCK_OUT);
2420                         break;
2421                 
2422                 case UI_BUT_EVENT:
2423                         /* future: handlerize this! */
2424                         if(snode->treetype==NTREE_SHADER)
2425                                 shader_node_event(snode, val);
2426                         else if(snode->treetype==NTREE_COMPOSIT)
2427                                 composit_node_event(snode, val);
2428                         else if(snode->treetype==NTREE_TEXTURE)
2429                                 texture_node_event(snode, val);
2430                         break;
2431                         
2432                 case PADPLUSKEY:
2433                         snode_zoom_in(sa);
2434                         doredraw= 1;
2435                         break;
2436                 case PADMINUS:
2437                         snode_zoom_out(sa);
2438                         doredraw= 1;
2439                         break;
2440                 case HOMEKEY:
2441                         snode_home(sa, snode);
2442                         doredraw= 1;
2443                         break;
2444                 case TABKEY:
2445                         if(fromlib) fromlib= -1;
2446                         else snode_make_group_editable(snode, NULL);
2447                         break;
2448                         
2449                 case AKEY:
2450                         if(G.qual==LR_SHIFTKEY) {
2451                                 if(fromlib) fromlib= -1;
2452                                 else toolbox_n_add();
2453                         }
2454                         else if(G.qual==0) {
2455                                 node_deselectall(snode, 1);
2456                         }
2457                         break;
2458                 case BKEY:
2459                         if(G.qual==0)
2460                                 node_border_select(snode);
2461                         break;
2462                 case CKEY:      /* sort again, showing cyclics */
2463                         ntreeSolveOrder(snode->edittree);
2464                         doredraw= 1;
2465                         break;
2466                 case DKEY:
2467                         if(G.qual==LR_SHIFTKEY) {
2468                                 if(fromlib) fromlib= -1;
2469                                 else node_adduplicate(snode);
2470                         }
2471                         break;
2472                 case EKEY:
2473                         // XXX                  snode_handle_recalc(snode);
2474                         break;
2475                 case FKEY:
2476                         node_make_link(snode);
2477                         break;
2478                 case GKEY:
2479                         if(fromlib) fromlib= -1;
2480                         else {
2481                                 if(G.qual==LR_CTRLKEY) {
2482                                         if(okee("Make Group"))
2483                                                 node_make_group(snode);
2484                                 }
2485                                 else if(G.qual==LR_ALTKEY) {
2486                                         if(okee("Ungroup"))
2487                                                 node_ungroup(snode);
2488                                 }
2489                                 else if(G.qual==LR_SHIFTKEY) {
2490                                         node_addgroup(snode);
2491                                 }
2492 //                              else
2493 // XXX                                  transform_nodes(snode->edittree, 'g', "Move Node");
2494                         }
2495                         break;
2496                 case HKEY:
2497                         node_hide(snode);
2498                         break;
2499                 case IKEY:
2500                         node_insert_key(snode);
2501                         break;
2502                 case LKEY:
2503                         node_select_linked(snode, G.qual==LR_SHIFTKEY);
2504                         break;
2505                 case MKEY:
2506                         node_mute(snode);
2507                         break;
2508                 case RKEY:
2509                         if(G.qual==LR_CTRLKEY) {
2510                                 node_rename(snode);
2511                         } 
2512                         else if(G.qual==LR_SHIFTKEY) {
2513                                 if(okee("Read saved Full Sample Layers"))
2514                                         node_read_fullsamplelayers(snode);
2515                         }
2516                         else {
2517                                 if(okee("Read saved Render Layers"))
2518                                         node_read_renderlayers(snode);
2519                         }
2520                         break;
2521                 case DELKEY:
2522                 case XKEY:
2523                         if(G.qual==LR_ALTKEY) {
2524                                 gpencil_delete_menu();
2525                         }
2526                         else {
2527                                 if(fromlib) fromlib= -1;
2528                                 else node_delete(snode);
2529                         }
2530                         break;
2531                 }
2532         }
2533
2534         if(fromlib==-1)
2535                 error_libdata();
2536         if(doredraw)
2537                 scrarea_queue_winredraw(sa);
2538         if(doredraw==2)
2539                 scrarea_queue_headredraw(sa);
2540 }
2541 #endif
2542
2543 static int node_delete_selection_exec(bContext *C, wmOperator *op)
2544 {
2545         SpaceNode *snode= CTX_wm_space_node(C);
2546         ARegion *ar= CTX_wm_region(C);
2547         
2548         node_delete(snode);
2549         ED_region_tag_redraw(ar);
2550         WM_event_add_notifier(C, NC_SCENE|ND_NODES, NULL); /* Do we need to pass the scene? */
2551
2552         return OPERATOR_FINISHED;
2553 }
2554
2555 /* operators */
2556
2557 void NODE_OT_delete(wmOperatorType *ot)
2558 {
2559         
2560         /* identifiers */
2561         ot->name= "Delete";
2562         ot->idname= "NODE_OT_delete";
2563         
2564         /* api callbacks */
2565         ot->exec= node_delete_selection_exec;
2566         ot->poll= ED_operator_node_active;
2567         
2568         /* flags */
2569         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
2570 }
2571