Code refactoring: split lamp functions from object.c into new lamp.c.
[blender.git] / source / blender / editors / render / render_preview.c
1 /* 
2  *
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  * The Original Code is Copyright (C) Blender Foundation.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/editors/render/render_preview.c
30  *  \ingroup edrend
31  */
32
33
34 /* global includes */
35
36 #include <stdlib.h>
37 #include <math.h>
38 #include <string.h>
39
40 #ifndef WIN32
41 #include <unistd.h>
42 #else
43 #include <io.h>
44 #endif   
45 #include "MEM_guardedalloc.h"
46
47 #include "BLO_readfile.h" 
48
49 #include "BLI_math.h"
50 #include "BLI_blenlib.h"
51 #include "BLI_threads.h"
52 #include "BLI_utildefines.h"
53
54 #include "DNA_world_types.h"
55 #include "DNA_camera_types.h"
56 #include "DNA_material_types.h"
57 #include "DNA_node_types.h"
58 #include "DNA_object_types.h"
59 #include "DNA_lamp_types.h"
60 #include "DNA_space_types.h"
61 #include "DNA_view3d_types.h"
62 #include "DNA_scene_types.h"
63 #include "DNA_brush_types.h"
64 #include "DNA_screen_types.h"
65
66 #include "BKE_brush.h"
67 #include "BKE_context.h"
68 #include "BKE_depsgraph.h"
69 #include "BKE_global.h"
70 #include "BKE_idprop.h"
71 #include "BKE_image.h"
72 #include "BKE_icons.h"
73 #include "BKE_lamp.h"
74 #include "BKE_library.h"
75 #include "BKE_main.h"
76 #include "BKE_material.h"
77 #include "BKE_node.h"
78 #include "BKE_object.h"
79 #include "BKE_texture.h"
80 #include "BKE_world.h"
81
82 #include "IMB_imbuf.h"
83 #include "IMB_imbuf_types.h"
84
85 #include "BIF_gl.h"
86 #include "BIF_glutil.h"
87
88 #include "PIL_time.h"
89
90 #include "RE_pipeline.h"
91
92
93 #include "WM_api.h"
94 #include "WM_types.h"
95
96 #include "ED_render.h"
97 #include "ED_view3d.h"
98
99 #include "UI_interface.h"
100
101 #include "render_intern.h"
102
103 ImBuf* get_brush_icon(Brush *brush)
104 {
105         static const int flags = IB_rect|IB_multilayer|IB_metadata;
106
107         char path[240];
108         char *folder;
109
110         if (!(brush->icon_imbuf)) {
111                 if (brush->flag & BRUSH_CUSTOM_ICON) {
112
113                         if (brush->icon_filepath[0]) {
114                                 // first use the path directly to try and load the file
115
116                                 BLI_strncpy(path, brush->icon_filepath, sizeof(brush->icon_filepath));
117                                 BLI_path_abs(path, G.main->name);
118
119                                 brush->icon_imbuf= IMB_loadiffname(path, flags);
120
121                                 // otherwise lets try to find it in other directories
122                                 if (!(brush->icon_imbuf)) {
123                                         folder= BLI_get_folder(BLENDER_DATAFILES, "brushicons");
124
125                                         BLI_make_file_string(G.main->name, path, folder, brush->icon_filepath);
126
127                                         if (path[0])
128                                                 brush->icon_imbuf= IMB_loadiffname(path, flags);
129                                 }
130
131                                 if (brush->icon_imbuf)
132                                         BKE_icon_changed(BKE_icon_getid(&brush->id));
133                         }
134                 }
135         }
136
137         if (!(brush->icon_imbuf))
138                 brush->id.icon_id = 0;
139
140         return brush->icon_imbuf;
141 }
142
143 typedef struct ShaderPreview {
144         /* from wmJob */
145         void *owner;
146         short *stop, *do_update;
147         
148         Scene *scene;
149         ID *id;
150         ID *parent;
151         MTex *slot;
152         
153         /* datablocks with nodes need full copy during preview render, glsl uses it too */
154         Material *matcopy;
155         Tex *texcopy;
156         Lamp *lampcopy;
157         World *worldcopy;
158         
159         float col[4];           /* active object color */
160         
161         int sizex, sizey;
162         unsigned int *pr_rect;
163         int pr_method;
164         
165 } ShaderPreview;
166
167 /* *************************** Preview for buttons *********************** */
168
169 static Main *pr_main= NULL;
170
171 void ED_preview_init_dbase(void)
172 {
173 #ifndef WITH_HEADLESS
174         BlendFileData *bfd;
175         extern int datatoc_preview_blend_size;
176         extern char datatoc_preview_blend[];
177         const int fileflags= G.fileflags;
178         
179         G.fileflags |= G_FILE_NO_UI;
180         bfd= BLO_read_from_memory(datatoc_preview_blend, datatoc_preview_blend_size, NULL);
181         if (bfd) {
182                 pr_main= bfd->main;
183                 
184                 MEM_freeN(bfd);
185         }
186         G.fileflags= fileflags;
187 #endif
188 }
189
190 void ED_preview_free_dbase(void)
191 {
192         if(pr_main)
193                 free_main(pr_main);
194 }
195
196 static int preview_mat_has_sss(Material *mat, bNodeTree *ntree)
197 {
198         if(mat) {
199                 if(mat->sss_flag & MA_DIFF_SSS)
200                         return 1;
201                 if(mat->nodetree)
202                         if( preview_mat_has_sss(NULL, mat->nodetree))
203                                 return 1;
204         }
205         else if(ntree) {
206                 bNode *node;
207                 for(node= ntree->nodes.first; node; node= node->next) {
208                         if(node->type==NODE_GROUP && node->id) {
209                                 if( preview_mat_has_sss(NULL, (bNodeTree *)node->id))
210                                         return 1;
211                         }
212                         else if(node->id && ELEM(node->type, SH_NODE_MATERIAL, SH_NODE_MATERIAL_EXT)) {
213                                 mat= (Material *)node->id;
214                                 if(mat->sss_flag & MA_DIFF_SSS)
215                                         return 1;
216                         }
217                 }
218         }
219         return 0;
220 }
221
222 /* call this with a pointer to initialize preview scene */
223 /* call this with NULL to restore assigned ID pointers in preview scene */
224 static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPreview *sp)
225 {
226         Scene *sce;
227         Base *base;
228         
229         if(pr_main==NULL) return NULL;
230         
231         sce= pr_main->scene.first;
232         if(sce) {
233                 
234                 /* this flag tells render to not execute depsgraph or ipos etc */
235                 sce->r.scemode |= R_PREVIEWBUTS;
236                 /* set world always back, is used now */
237                 sce->world= pr_main->world.first;
238                 /* now: exposure copy */
239                 if(scene->world) {
240                         sce->world->exp= scene->world->exp;
241                         sce->world->range= scene->world->range;
242                 }
243                 
244                 sce->r.color_mgt_flag = scene->r.color_mgt_flag;
245                 
246                 /* prevent overhead for small renders and icons (32) */
247                 if(id && sp->sizex < 40)
248                         sce->r.xparts= sce->r.yparts= 1;
249                 else
250                         sce->r.xparts= sce->r.yparts= 4;
251                 
252                 /* exception: don't color manage texture previews or icons */
253                 if((id && sp->pr_method==PR_ICON_RENDER) || id_type == ID_TE)
254                         sce->r.color_mgt_flag &= ~R_COLOR_MANAGEMENT;
255                 
256                 if((id && sp->pr_method==PR_ICON_RENDER) && id_type != ID_WO)
257                         sce->r.alphamode= R_ALPHAPREMUL;
258                 else
259                         sce->r.alphamode= R_ADDSKY;
260
261                 sce->r.cfra= scene->r.cfra;
262                 BLI_strncpy(sce->r.engine, scene->r.engine, sizeof(sce->r.engine));
263                 
264                 if(id_type==ID_MA) {
265                         Material *mat= NULL, *origmat= (Material *)id;
266                         
267                         if(origmat) {
268                                 /* work on a copy */
269                                 mat= localize_material(origmat);
270                                 sp->matcopy= mat;
271                                 BLI_addtail(&pr_main->mat, mat);
272                                 
273                                 init_render_material(mat, 0, NULL);             /* call that retrieves mode_l */
274                                 end_render_material(mat);
275                                 
276                                 /* un-useful option */
277                                 if(sp->pr_method==PR_ICON_RENDER)
278                                         mat->shade_flag &= ~MA_OBCOLOR;
279
280                                 /* turn on raytracing if needed */
281                                 if(mat->mode_l & MA_RAYMIRROR)
282                                         sce->r.mode |= R_RAYTRACE;
283                                 if(mat->material_type == MA_TYPE_VOLUME)
284                                         sce->r.mode |= R_RAYTRACE;
285                                 if((mat->mode_l & MA_RAYTRANSP) && (mat->mode_l & MA_TRANSP))
286                                         sce->r.mode |= R_RAYTRACE;
287                                 if(preview_mat_has_sss(mat, NULL))
288                                         sce->r.mode |= R_SSS;
289                                 
290                                 /* turn off fake shadows if needed */
291                                 /* this only works in a specific case where the preview.blend contains
292                                  * an object starting with 'c' which has a material linked to it (not the obdata)
293                                  * and that material has a fake shadow texture in the active texture slot */
294                                 for(base= sce->base.first; base; base= base->next) {
295                                         if(base->object->id.name[2]=='c') {
296                                                 Material *shadmat= give_current_material(base->object, base->object->actcol);
297                                                 if(shadmat) {
298                                                         if (mat->mode & MA_SHADBUF) shadmat->septex = 0;
299                                                         else shadmat->septex |= 1;
300                                                 }
301                                         }
302                                 }
303                                 
304                                 /* turn off bounce lights for volume, 
305                                  * doesn't make much visual difference and slows it down too */
306                                 if(mat->material_type == MA_TYPE_VOLUME) {
307                                         for(base= sce->base.first; base; base= base->next) {
308                                                 if(base->object->type == OB_LAMP) {
309                                                         /* if doesn't match 'Lamp.002' --> main key light */
310                                                         if( strcmp(base->object->id.name+2, "Lamp.002") != 0 ) {
311                                                                 base->object->restrictflag |= OB_RESTRICT_RENDER;
312                                                         }
313                                                 }
314                                         }
315                                 }
316
317                                 
318                                 if(sp->pr_method==PR_ICON_RENDER) {
319                                         if (mat->material_type == MA_TYPE_HALO) {
320                                                 sce->lay= 1<<MA_FLAT;
321                                         } 
322                                         else {
323                                                 sce->lay= 1<<MA_SPHERE_A;
324                                         }
325                                 }
326                                 else {
327                                         sce->lay= 1<<mat->pr_type;
328                                         if(mat->nodetree && sp->pr_method==PR_NODE_RENDER) {
329                                                 /* two previews, they get copied by wmJob */
330                                                 ntreeInitPreview(mat->nodetree, sp->sizex, sp->sizey);
331                                                 ntreeInitPreview(origmat->nodetree, sp->sizex, sp->sizey);
332                                         }
333                                 }
334                         }
335                         else {
336                                 sce->r.mode &= ~(R_OSA|R_RAYTRACE|R_SSS);
337                                 
338                         }
339                         
340                         for(base= sce->base.first; base; base= base->next) {
341                                 if(base->object->id.name[2]=='p') {
342                                         /* copy over object color, in case material uses it */
343                                         copy_v4_v4(base->object->col, sp->col);
344                                         
345                                         if(OB_TYPE_SUPPORT_MATERIAL(base->object->type)) {
346                                                 /* don't use assign_material, it changed mat->id.us, which shows in the UI */
347                                                 Material ***matar= give_matarar(base->object);
348                                                 int actcol= MAX2(base->object->actcol > 0, 1) - 1;
349
350                                                 if(matar && actcol < base->object->totcol)
351                                                         (*matar)[actcol]= mat;
352                                         } else if (base->object->type == OB_LAMP) {
353                                                 base->object->restrictflag &= ~OB_RESTRICT_RENDER;
354                                         }
355                                 }
356                         }
357                 }
358                 else if(id_type==ID_TE) {
359                         Tex *tex= NULL, *origtex= (Tex *)id;
360                         
361                         if(origtex) {
362                                 tex= localize_texture(origtex);
363                                 sp->texcopy= tex;
364                                 BLI_addtail(&pr_main->tex, tex);
365                         }                       
366                         sce->lay= 1<<MA_TEXTURE;
367                         
368                         for(base= sce->base.first; base; base= base->next) {
369                                 if(base->object->id.name[2]=='t') {
370                                         Material *mat= give_current_material(base->object, base->object->actcol);
371                                         if(mat && mat->mtex[0]) {
372                                                 mat->mtex[0]->tex= tex;
373                                                 
374                                                 if(tex && sp->slot)
375                                                         mat->mtex[0]->which_output = sp->slot->which_output;
376                                                 
377                                                 /* show alpha in this case */
378                                                 if(tex==NULL || (tex->flag & TEX_PRV_ALPHA)) {
379                                                         mat->mtex[0]->mapto |= MAP_ALPHA;
380                                                         mat->alpha= 0.0f;
381                                                 }
382                                                 else {
383                                                         mat->mtex[0]->mapto &= ~MAP_ALPHA;
384                                                         mat->alpha= 1.0f;
385                                                 }
386                                         }
387                                 }
388                         }
389
390                         if(tex && tex->nodetree && sp->pr_method==PR_NODE_RENDER) {
391                                 /* two previews, they get copied by wmJob */
392                                 ntreeInitPreview(origtex->nodetree, sp->sizex, sp->sizey);
393                                 ntreeInitPreview(tex->nodetree, sp->sizex, sp->sizey);
394                         }
395                 }
396                 else if(id_type==ID_LA) {
397                         Lamp *la= NULL, *origla= (Lamp *)id;
398
399                         /* work on a copy */
400                         if(origla) {
401                                 la= localize_lamp(origla);
402                                 sp->lampcopy= la;
403                                 BLI_addtail(&pr_main->lamp, la);
404                         }
405                         
406                         if(la && la->type==LA_SUN && (la->sun_effect_type & LA_SUN_EFFECT_SKY)) {
407                                 sce->lay= 1<<MA_ATMOS;
408                                 sce->world= scene->world;
409                                 sce->camera= (Object *)BLI_findstring(&pr_main->object, "CameraAtmo", offsetof(ID, name)+2);
410                         }
411                         else {
412                                 sce->lay= 1<<MA_LAMP;
413                                 sce->world= NULL;
414                                 sce->camera= (Object *)BLI_findstring(&pr_main->object, "Camera", offsetof(ID, name)+2);
415                         }
416                         sce->r.mode &= ~R_SHADOW;
417                         
418                         for(base= sce->base.first; base; base= base->next) {
419                                 if(base->object->id.name[2]=='p') {
420                                         if(base->object->type==OB_LAMP)
421                                                 base->object->data= la;
422                                 }
423                         }
424
425                         if(la && la->nodetree && sp->pr_method==PR_NODE_RENDER) {
426                                 /* two previews, they get copied by wmJob */
427                                 ntreeInitPreview(origla->nodetree, sp->sizex, sp->sizey);
428                                 ntreeInitPreview(la->nodetree, sp->sizex, sp->sizey);
429                         }
430                 }
431                 else if(id_type==ID_WO) {
432                         World *wrld= NULL, *origwrld= (World *)id;
433
434                         if(origwrld) {
435                                 wrld= localize_world(origwrld);
436                                 sp->worldcopy= wrld;
437                                 BLI_addtail(&pr_main->world, wrld);
438                         }
439
440                         sce->lay= 1<<MA_SKY;
441                         sce->world= wrld;
442
443                         if(wrld && wrld->nodetree && sp->pr_method==PR_NODE_RENDER) {
444                                 /* two previews, they get copied by wmJob */
445                                 ntreeInitPreview(wrld->nodetree, sp->sizex, sp->sizey);
446                                 ntreeInitPreview(origwrld->nodetree, sp->sizex, sp->sizey);
447                         }
448                 }
449                 
450                 return sce;
451         }
452         
453         return NULL;
454 }
455
456 /* new UI convention: draw is in pixel space already. */
457 /* uses ROUNDBOX button in block to get the rect */
458 static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int first, rcti *rect, rcti *newrect)
459 {
460         Render *re;
461         RenderResult rres;
462         char name[32];
463         int do_gamma_correct=0;
464         int offx=0, newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
465
466         if (id && GS(id->name) != ID_TE) {
467                 /* exception: don't color manage texture previews - show the raw values */
468                 if (sce) do_gamma_correct = sce->r.color_mgt_flag & R_COLOR_MANAGEMENT;
469         }
470
471         if(!split || first) sprintf(name, "Preview %p", (void *)sa);
472         else sprintf(name, "SecondPreview %p", (void *)sa);
473
474         if(split) {
475                 if(first) {
476                         offx= 0;
477                         newx= newx/2;
478                 }
479                 else {
480                         offx= newx/2;
481                         newx= newx - newx/2;
482                 }
483         }
484
485         re= RE_GetRender(name);
486         RE_AcquireResultImage(re, &rres);
487
488         if(rres.rectf) {
489                 
490                 if(ABS(rres.rectx-newx)<2 && ABS(rres.recty-newy)<2) {
491                         newrect->xmax= MAX2(newrect->xmax, rect->xmin + rres.rectx + offx);
492                         newrect->ymax= MAX2(newrect->ymax, rect->ymin + rres.recty);
493
494                         glaDrawPixelsSafe_to32(rect->xmin+offx, rect->ymin, rres.rectx, rres.recty, rres.rectx, rres.rectf, do_gamma_correct);
495
496                         RE_ReleaseResultImage(re);
497                         return 1;
498                 }
499         }
500
501         RE_ReleaseResultImage(re);
502         return 0;
503 }
504
505 void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, rcti *rect)
506 {
507         if(idp) {
508                 ScrArea *sa= CTX_wm_area(C);
509                 Scene *sce = CTX_data_scene(C);
510                 ID *id = (ID *)idp;
511                 ID *parent= (ID *)parentp;
512                 MTex *slot= (MTex *)slotp;
513                 SpaceButs *sbuts= sa->spacedata.first;
514                 rcti newrect;
515                 int ok;
516                 int newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
517
518                 newrect.xmin= rect->xmin;
519                 newrect.xmax= rect->xmin;
520                 newrect.ymin= rect->ymin;
521                 newrect.ymax= rect->ymin;
522
523                 if(parent) {
524                         ok = ed_preview_draw_rect(sa, sce, id, 1, 1, rect, &newrect);
525                         ok &= ed_preview_draw_rect(sa, sce, parent, 1, 0, rect, &newrect);
526                 }
527                 else
528                         ok = ed_preview_draw_rect(sa, sce, id, 0, 0, rect, &newrect);
529
530                 if(ok)
531                         *rect= newrect;
532
533                 /* check for spacetype... */
534                 if(sbuts->spacetype==SPACE_BUTS && sbuts->preview) {
535                         sbuts->preview= 0;
536                         ok= 0;
537                 }
538         
539                 if(ok==0) {
540                         ED_preview_shader_job(C, sa, id, parent, slot, newx, newy, PR_BUTS_RENDER);
541                 }
542         }       
543 }
544
545 /* **************************** new shader preview system ****************** */
546
547 /* inside thread, called by renderer, sets job update value */
548 static void shader_preview_draw(void *spv, RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect))
549 {
550         ShaderPreview *sp= spv;
551         
552         *(sp->do_update)= 1;
553 }
554
555 /* called by renderer, checks job value */
556 static int shader_preview_break(void *spv)
557 {
558         ShaderPreview *sp= spv;
559
560         return *(sp->stop);
561 }
562
563 /* outside thread, called before redraw notifiers, it moves finished preview over */
564 static void shader_preview_updatejob(void *spv)
565 {
566         ShaderPreview *sp= spv;
567         
568         if(sp->id) {
569                 if(sp->pr_method==PR_NODE_RENDER) {
570                         if( GS(sp->id->name) == ID_MA) {
571                                 Material *mat= (Material *)sp->id;
572                                 
573                                 if(sp->matcopy && mat->nodetree && sp->matcopy->nodetree)
574                                         ntreeLocalSync(sp->matcopy->nodetree, mat->nodetree);
575                         }
576                         else if( GS(sp->id->name) == ID_TE) {
577                                 Tex *tex= (Tex *)sp->id;
578                                 
579                                 if(sp->texcopy && tex->nodetree && sp->texcopy->nodetree)
580                                         ntreeLocalSync(sp->texcopy->nodetree, tex->nodetree);
581                         }
582                         else if( GS(sp->id->name) == ID_WO) {
583                                 World *wrld= (World *)sp->id;
584                                 
585                                 if(sp->worldcopy && wrld->nodetree && sp->worldcopy->nodetree)
586                                         ntreeLocalSync(sp->worldcopy->nodetree, wrld->nodetree);
587                         }
588                         else if( GS(sp->id->name) == ID_LA) {
589                                 Lamp *la= (Lamp *)sp->id;
590                                 
591                                 if(sp->lampcopy && la->nodetree && sp->lampcopy->nodetree)
592                                         ntreeLocalSync(sp->lampcopy->nodetree, la->nodetree);
593                         }
594                 }               
595         }
596 }
597
598 static void shader_preview_render(ShaderPreview *sp, ID *id, int split, int first)
599 {
600         Render *re;
601         Scene *sce;
602         float oldlens;
603         short idtype= GS(id->name);
604         char name[32];
605         int sizex;
606         
607         /* get the stuff from the builtin preview dbase */
608         sce= preview_prepare_scene(sp->scene, id, idtype, sp); // XXX sizex
609         if(sce==NULL) return;
610         
611         if(!split || first) sprintf(name, "Preview %p", sp->owner);
612         else sprintf(name, "SecondPreview %p", sp->owner);
613         re= RE_GetRender(name);
614         
615         /* full refreshed render from first tile */
616         if(re==NULL)
617                 re= RE_NewRender(name);
618                 
619         /* sce->r gets copied in RE_InitState! */
620         sce->r.scemode &= ~(R_MATNODE_PREVIEW|R_TEXNODE_PREVIEW);
621         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
622
623         if(sp->pr_method==PR_ICON_RENDER) {
624                 sce->r.scemode |= R_NO_IMAGE_LOAD;
625                 sce->r.mode |= R_OSA;
626         }
627         else if(sp->pr_method==PR_NODE_RENDER) {
628                 if(idtype == ID_MA) sce->r.scemode |= R_MATNODE_PREVIEW;
629                 else if(idtype == ID_TE) sce->r.scemode |= R_TEXNODE_PREVIEW;
630                 sce->r.mode &= ~R_OSA;
631         }
632         else {  /* PR_BUTS_RENDER */
633                 sce->r.mode |= R_OSA;
634         }
635
636         /* in case of split preview, use border render */
637         if(split) {
638                 if(first) sizex= sp->sizex/2;
639                 else sizex= sp->sizex - sp->sizex/2;
640         }
641         else sizex= sp->sizex;
642
643         /* allocates or re-uses render result */
644         sce->r.xsch= sizex;
645         sce->r.ysch= sp->sizey;
646         sce->r.size= 100;
647
648         /* callbacs are cleared on GetRender() */
649         if(ELEM(sp->pr_method, PR_BUTS_RENDER, PR_NODE_RENDER)) {
650                 RE_display_draw_cb(re, sp, shader_preview_draw);
651         }
652         /* set this for all previews, default is react to G.afbreek still */
653         RE_test_break_cb(re, sp, shader_preview_break);
654         
655         /* lens adjust */
656         oldlens= ((Camera *)sce->camera->data)->lens;
657         if(sizex > sp->sizey)
658                 ((Camera *)sce->camera->data)->lens *= (float)sp->sizey/(float)sizex;
659
660         /* entire cycle for render engine */
661         RE_PreviewRender(re, pr_main, sce);
662
663         ((Camera *)sce->camera->data)->lens= oldlens;
664
665         /* handle results */
666         if(sp->pr_method==PR_ICON_RENDER) {
667                 // char *rct= (char *)(sp->pr_rect + 32*16 + 16);
668                 
669                 if(sp->pr_rect)
670                         RE_ResultGet32(re, sp->pr_rect);
671         }
672         else {
673                 /* validate owner */
674                 //if(ri->rect==NULL)
675                 //      ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
676                 //RE_ResultGet32(re, ri->rect);
677         }
678
679         /* unassign the pointers, reset vars */
680         preview_prepare_scene(sp->scene, NULL, GS(id->name), sp);
681         
682         /* XXX bad exception, end-exec is not being called in render, because it uses local main */
683 //      if(idtype == ID_TE) {
684 //              Tex *tex= (Tex *)id;
685 //              if(tex->use_nodes && tex->nodetree)
686 //                      ntreeEndExecTree(tex->nodetree);
687 //      }
688
689 }
690
691 /* runs inside thread for material and icons */
692 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
693 {
694         ShaderPreview *sp= customdata;
695
696         sp->stop= stop;
697         sp->do_update= do_update;
698
699         if(sp->parent) {
700                 shader_preview_render(sp, sp->id, 1, 1);
701                 shader_preview_render(sp, sp->parent, 1, 0);
702         }
703         else
704                 shader_preview_render(sp, sp->id, 0, 0);
705
706         *do_update= 1;
707 }
708
709 static void shader_preview_free(void *customdata)
710 {
711         ShaderPreview *sp= customdata;
712         
713         if(sp->matcopy) {
714                 struct IDProperty *properties;
715                 int a;
716                 
717                 /* node previews */
718                 shader_preview_updatejob(sp);
719                 
720                 /* get rid of copied material */
721                 BLI_remlink(&pr_main->mat, sp->matcopy);
722                 
723                 /* free_material decrements texture, prevent this. hack alert! */
724                 for(a=0; a<MAX_MTEX; a++) {
725                         MTex *mtex= sp->matcopy->mtex[a];
726                         if(mtex && mtex->tex) mtex->tex= NULL;
727                 }
728                 
729                 free_material(sp->matcopy);
730
731                 properties= IDP_GetProperties((ID *)sp->matcopy, FALSE);
732                 if (properties) {
733                         IDP_FreeProperty(properties);
734                         MEM_freeN(properties);
735                 }
736                 MEM_freeN(sp->matcopy);
737         }
738         if(sp->texcopy) {
739                 struct IDProperty *properties;
740                 /* node previews */
741                 shader_preview_updatejob(sp);
742                 
743                 /* get rid of copied texture */
744                 BLI_remlink(&pr_main->tex, sp->texcopy);
745                 free_texture(sp->texcopy);
746                 
747                 properties= IDP_GetProperties((ID *)sp->texcopy, FALSE);
748                 if (properties) {
749                         IDP_FreeProperty(properties);
750                         MEM_freeN(properties);
751                 }
752                 MEM_freeN(sp->texcopy);
753         }
754         if(sp->worldcopy) {
755                 struct IDProperty *properties;
756                 /* node previews */
757                 shader_preview_updatejob(sp);
758                 
759                 /* get rid of copied world */
760                 BLI_remlink(&pr_main->world, sp->worldcopy);
761                 free_world(sp->worldcopy);
762                 
763                 properties= IDP_GetProperties((ID *)sp->worldcopy, FALSE);
764                 if (properties) {
765                         IDP_FreeProperty(properties);
766                         MEM_freeN(properties);
767                 }
768                 MEM_freeN(sp->worldcopy);
769         }
770         if(sp->lampcopy) {
771                 struct IDProperty *properties;
772                 /* node previews */
773                 shader_preview_updatejob(sp);
774                 
775                 /* get rid of copied lamp */
776                 BLI_remlink(&pr_main->lamp, sp->lampcopy);
777                 free_lamp(sp->lampcopy);
778                 
779                 properties= IDP_GetProperties((ID *)sp->lampcopy, FALSE);
780                 if (properties) {
781                         IDP_FreeProperty(properties);
782                         MEM_freeN(properties);
783                 }
784                 MEM_freeN(sp->lampcopy);
785         }
786         
787         MEM_freeN(sp);
788 }
789
790 /* ************************* icon preview ********************** */
791
792 static void icon_copy_rect(ImBuf *ibuf, unsigned int w, unsigned int h, unsigned int *rect)
793 {
794         struct ImBuf *ima;
795         unsigned int *drect, *srect;
796         float scaledx, scaledy;
797         short ex, ey, dx, dy;
798
799         /* paranoia test */
800         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL))
801                 return;
802         
803         /* waste of cpu cyles... but the imbuf API has no other way to scale fast (ton) */
804         ima = IMB_dupImBuf(ibuf);
805         
806         if (!ima) 
807                 return;
808         
809         if (ima->x > ima->y) {
810                 scaledx = (float)w;
811                 scaledy =  ( (float)ima->y/(float)ima->x )*(float)w;
812         }
813         else {                  
814                 scaledx =  ( (float)ima->x/(float)ima->y )*(float)h;
815                 scaledy = (float)h;
816         }
817         
818         ex = (short)scaledx;
819         ey = (short)scaledy;
820         
821         dx = (w - ex) / 2;
822         dy = (h - ey) / 2;
823         
824         IMB_scalefastImBuf(ima, ex, ey);
825         
826         /* if needed, convert to 32 bits */
827         if(ima->rect==NULL)
828                 IMB_rect_from_float(ima);
829
830         srect = ima->rect;
831         drect = rect;
832
833         drect+= dy*w+dx;
834         for (;ey > 0; ey--){            
835                 memcpy(drect,srect, ex * sizeof(int));
836                 drect += w;
837                 srect += ima->x;
838         }
839
840         IMB_freeImBuf(ima);
841 }
842
843 static void set_alpha(char *cp, int sizex, int sizey, char alpha) 
844 {
845         int a, size= sizex*sizey;
846
847         for(a=0; a<size; a++, cp+=4)
848                 cp[3]= alpha;
849 }
850
851 static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
852 {
853         ShaderPreview *sp= customdata;
854         ID *id= sp->id;
855         short idtype= GS(id->name);
856
857         if(idtype == ID_IM) {
858                 Image *ima= (Image*)id;
859                 ImBuf *ibuf= NULL;
860                 ImageUser iuser= {NULL};
861
862                 /* ima->ok is zero when Image cannot load */
863                 if(ima==NULL || ima->ok==0)
864                         return;
865
866                 /* setup dummy image user */
867                 iuser.ok= iuser.framenr= 1;
868                 iuser.scene= sp->scene;
869                 
870                 /* elubie: this needs to be changed: here image is always loaded if not
871                    already there. Very expensive for large images. Need to find a way to 
872                    only get existing ibuf */
873                 ibuf = BKE_image_get_ibuf(ima, &iuser);
874                 if(ibuf==NULL || ibuf->rect==NULL)
875                         return;
876                 
877                 icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);
878
879                 *do_update= 1;
880         }
881         else if(idtype == ID_BR) {
882                 Brush *br= (Brush*)id;
883
884                 br->icon_imbuf= get_brush_icon(br);
885
886                 memset(sp->pr_rect, 0x888888, sp->sizex*sp->sizey*sizeof(unsigned int));
887
888                 if(!(br->icon_imbuf) || !(br->icon_imbuf->rect))
889                         return;
890
891                 icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);
892
893                 *do_update= 1;
894         }
895         else {
896                 /* re-use shader job */
897                 shader_preview_startjob(customdata, stop, do_update);
898
899                 /* world is rendered with alpha=0, so it wasn't displayed 
900                    this could be render option for sky to, for later */
901                 if(idtype == ID_WO) {
902                         set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
903                 }
904                 else if(idtype == ID_MA) {
905                         Material* ma = (Material*)id;
906
907                         if(ma->material_type == MA_TYPE_HALO)
908                                 set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
909                 }
910         }
911 }
912
913 /* use same function for icon & shader, so the job manager
914    does not run two of them at the same time. */
915
916 static void common_preview_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
917 {
918         ShaderPreview *sp= customdata;
919
920         if(sp->pr_method == PR_ICON_RENDER)
921                 icon_preview_startjob(customdata, stop, do_update);
922         else
923                 shader_preview_startjob(customdata, stop, do_update);
924 }
925
926 static void common_preview_endjob(void *customdata)
927 {
928         ShaderPreview *sp= customdata;
929
930         if(sp->id && GS(sp->id->name) == ID_BR)
931                 WM_main_add_notifier(NC_BRUSH|NA_EDITED, sp->id);
932 }
933
934 /* exported functions */
935
936 void ED_preview_icon_job(const bContext *C, void *owner, ID *id, unsigned int *rect, int sizex, int sizey)
937 {
938         wmJob *steve;
939         ShaderPreview *sp;
940         
941         /* suspended start means it starts after 1 timer step, see WM_jobs_timer below */
942         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Icon Preview", WM_JOB_EXCL_RENDER|WM_JOB_SUSPEND);
943         sp= MEM_callocN(sizeof(ShaderPreview), "shader preview");
944
945         /* customdata for preview thread */
946         sp->scene= CTX_data_scene(C);
947         sp->owner= id;
948         sp->sizex= sizex;
949         sp->sizey= sizey;
950         sp->pr_method= PR_ICON_RENDER;
951         sp->pr_rect= rect;
952         sp->id = id;
953
954         /* setup job */
955         WM_jobs_customdata(steve, sp, shader_preview_free);
956         WM_jobs_timer(steve, 0.25, NC_MATERIAL, NC_MATERIAL);
957         WM_jobs_callbacks(steve, common_preview_startjob, NULL, NULL, common_preview_endjob);
958
959         WM_jobs_start(CTX_wm_manager(C), steve);
960 }
961
962 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, MTex *slot, int sizex, int sizey, int method)
963 {
964         Object *ob= CTX_data_active_object(C);
965         wmJob *steve;
966         ShaderPreview *sp;
967
968         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Shader Preview", WM_JOB_EXCL_RENDER);
969         sp= MEM_callocN(sizeof(ShaderPreview), "shader preview");
970
971         /* customdata for preview thread */
972         sp->scene= CTX_data_scene(C);
973         sp->owner= owner;
974         sp->sizex= sizex;
975         sp->sizey= sizey;
976         sp->pr_method= method;
977         sp->id = id;
978         sp->parent= parent;
979         sp->slot= slot;
980         if(ob && ob->totcol) copy_v4_v4(sp->col, ob->col);
981         else sp->col[0]= sp->col[1]= sp->col[2]= sp->col[3]= 1.0f;
982         
983         /* setup job */
984         WM_jobs_customdata(steve, sp, shader_preview_free);
985         WM_jobs_timer(steve, 0.1, NC_MATERIAL, NC_MATERIAL);
986         WM_jobs_callbacks(steve, common_preview_startjob, NULL, shader_preview_updatejob, NULL);
987         
988         WM_jobs_start(CTX_wm_manager(C), steve);
989 }
990
991 void ED_preview_kill_jobs(const struct bContext *C)
992 {
993         wmWindowManager *wm= CTX_wm_manager(C);
994         if(wm)
995                 WM_jobs_kill(wm, NULL, common_preview_startjob);
996 }
997