Merging r44140 through r44226 from trunk into soc-2011-tomato
[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[FILE_MAX];
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 typedef struct IconPreviewSize {
168         struct IconPreviewSize *next, *prev;
169         int sizex, sizey;
170         unsigned int *rect;
171 } IconPreviewSize;
172
173 typedef struct IconPreview {
174         Scene *scene;
175         void *owner;
176         ID *id;
177         ListBase sizes;
178 } IconPreview;
179
180 /* *************************** Preview for buttons *********************** */
181
182 static Main *pr_main= NULL;
183
184 void ED_preview_init_dbase(void)
185 {
186 #ifndef WITH_HEADLESS
187         BlendFileData *bfd;
188         extern int datatoc_preview_blend_size;
189         extern char datatoc_preview_blend[];
190         const int fileflags= G.fileflags;
191         
192         G.fileflags |= G_FILE_NO_UI;
193         bfd= BLO_read_from_memory(datatoc_preview_blend, datatoc_preview_blend_size, NULL);
194         if (bfd) {
195                 pr_main= bfd->main;
196                 
197                 MEM_freeN(bfd);
198         }
199         G.fileflags= fileflags;
200 #endif
201 }
202
203 void ED_preview_free_dbase(void)
204 {
205         if(pr_main)
206                 free_main(pr_main);
207 }
208
209 static int preview_mat_has_sss(Material *mat, bNodeTree *ntree)
210 {
211         if(mat) {
212                 if(mat->sss_flag & MA_DIFF_SSS)
213                         return 1;
214                 if(mat->nodetree)
215                         if( preview_mat_has_sss(NULL, mat->nodetree))
216                                 return 1;
217         }
218         else if(ntree) {
219                 bNode *node;
220                 for(node= ntree->nodes.first; node; node= node->next) {
221                         if(node->type==NODE_GROUP && node->id) {
222                                 if( preview_mat_has_sss(NULL, (bNodeTree *)node->id))
223                                         return 1;
224                         }
225                         else if(node->id && ELEM(node->type, SH_NODE_MATERIAL, SH_NODE_MATERIAL_EXT)) {
226                                 mat= (Material *)node->id;
227                                 if(mat->sss_flag & MA_DIFF_SSS)
228                                         return 1;
229                         }
230                 }
231         }
232         return 0;
233 }
234
235 /* call this with a pointer to initialize preview scene */
236 /* call this with NULL to restore assigned ID pointers in preview scene */
237 static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPreview *sp)
238 {
239         Scene *sce;
240         Base *base;
241         
242         if(pr_main==NULL) return NULL;
243         
244         sce= pr_main->scene.first;
245         if(sce) {
246                 
247                 /* this flag tells render to not execute depsgraph or ipos etc */
248                 sce->r.scemode |= R_PREVIEWBUTS;
249                 /* set world always back, is used now */
250                 sce->world= pr_main->world.first;
251                 /* now: exposure copy */
252                 if(scene->world) {
253                         sce->world->exp= scene->world->exp;
254                         sce->world->range= scene->world->range;
255                 }
256                 
257                 sce->r.color_mgt_flag = scene->r.color_mgt_flag;
258                 
259                 /* prevent overhead for small renders and icons (32) */
260                 if(id && sp->sizex < 40)
261                         sce->r.xparts= sce->r.yparts= 1;
262                 else
263                         sce->r.xparts= sce->r.yparts= 4;
264                 
265                 /* exception: don't color manage texture previews or icons */
266                 if((id && sp->pr_method==PR_ICON_RENDER) || id_type == ID_TE)
267                         sce->r.color_mgt_flag &= ~R_COLOR_MANAGEMENT;
268                 
269                 if((id && sp->pr_method==PR_ICON_RENDER) && id_type != ID_WO)
270                         sce->r.alphamode= R_ALPHAPREMUL;
271                 else
272                         sce->r.alphamode= R_ADDSKY;
273
274                 sce->r.cfra= scene->r.cfra;
275                 BLI_strncpy(sce->r.engine, scene->r.engine, sizeof(sce->r.engine));
276                 
277                 if(id_type==ID_MA) {
278                         Material *mat= NULL, *origmat= (Material *)id;
279                         
280                         if(origmat) {
281                                 /* work on a copy */
282                                 mat= localize_material(origmat);
283                                 sp->matcopy= mat;
284                                 BLI_addtail(&pr_main->mat, mat);
285                                 
286                                 init_render_material(mat, 0, NULL);             /* call that retrieves mode_l */
287                                 end_render_material(mat);
288                                 
289                                 /* un-useful option */
290                                 if(sp->pr_method==PR_ICON_RENDER)
291                                         mat->shade_flag &= ~MA_OBCOLOR;
292
293                                 /* turn on raytracing if needed */
294                                 if(mat->mode_l & MA_RAYMIRROR)
295                                         sce->r.mode |= R_RAYTRACE;
296                                 if(mat->material_type == MA_TYPE_VOLUME)
297                                         sce->r.mode |= R_RAYTRACE;
298                                 if((mat->mode_l & MA_RAYTRANSP) && (mat->mode_l & MA_TRANSP))
299                                         sce->r.mode |= R_RAYTRACE;
300                                 if(preview_mat_has_sss(mat, NULL))
301                                         sce->r.mode |= R_SSS;
302                                 
303                                 /* turn off fake shadows if needed */
304                                 /* this only works in a specific case where the preview.blend contains
305                                  * an object starting with 'c' which has a material linked to it (not the obdata)
306                                  * and that material has a fake shadow texture in the active texture slot */
307                                 for(base= sce->base.first; base; base= base->next) {
308                                         if(base->object->id.name[2]=='c') {
309                                                 Material *shadmat= give_current_material(base->object, base->object->actcol);
310                                                 if(shadmat) {
311                                                         if (mat->mode & MA_SHADBUF) shadmat->septex = 0;
312                                                         else shadmat->septex |= 1;
313                                                 }
314                                         }
315                                 }
316                                 
317                                 /* turn off bounce lights for volume, 
318                                  * doesn't make much visual difference and slows it down too */
319                                 if(mat->material_type == MA_TYPE_VOLUME) {
320                                         for(base= sce->base.first; base; base= base->next) {
321                                                 if(base->object->type == OB_LAMP) {
322                                                         /* if doesn't match 'Lamp.002' --> main key light */
323                                                         if( strcmp(base->object->id.name+2, "Lamp.002") != 0 ) {
324                                                                 base->object->restrictflag |= OB_RESTRICT_RENDER;
325                                                         }
326                                                 }
327                                         }
328                                 }
329
330                                 
331                                 if(sp->pr_method==PR_ICON_RENDER) {
332                                         if (mat->material_type == MA_TYPE_HALO) {
333                                                 sce->lay= 1<<MA_FLAT;
334                                         } 
335                                         else {
336                                                 sce->lay= 1<<MA_SPHERE_A;
337                                         }
338                                 }
339                                 else {
340                                         sce->lay= 1<<mat->pr_type;
341                                         if(mat->nodetree && sp->pr_method==PR_NODE_RENDER) {
342                                                 /* two previews, they get copied by wmJob */
343                                                 ntreeInitPreview(mat->nodetree, sp->sizex, sp->sizey);
344                                                 ntreeInitPreview(origmat->nodetree, sp->sizex, sp->sizey);
345                                         }
346                                 }
347                         }
348                         else {
349                                 sce->r.mode &= ~(R_OSA|R_RAYTRACE|R_SSS);
350                                 
351                         }
352                         
353                         for(base= sce->base.first; base; base= base->next) {
354                                 if(base->object->id.name[2]=='p') {
355                                         /* copy over object color, in case material uses it */
356                                         copy_v4_v4(base->object->col, sp->col);
357                                         
358                                         if(OB_TYPE_SUPPORT_MATERIAL(base->object->type)) {
359                                                 /* don't use assign_material, it changed mat->id.us, which shows in the UI */
360                                                 Material ***matar= give_matarar(base->object);
361                                                 int actcol= MAX2(base->object->actcol > 0, 1) - 1;
362
363                                                 if(matar && actcol < base->object->totcol)
364                                                         (*matar)[actcol]= mat;
365                                         } else if (base->object->type == OB_LAMP) {
366                                                 base->object->restrictflag &= ~OB_RESTRICT_RENDER;
367                                         }
368                                 }
369                         }
370                 }
371                 else if(id_type==ID_TE) {
372                         Tex *tex= NULL, *origtex= (Tex *)id;
373                         
374                         if(origtex) {
375                                 tex= localize_texture(origtex);
376                                 sp->texcopy= tex;
377                                 BLI_addtail(&pr_main->tex, tex);
378                         }                       
379                         sce->lay= 1<<MA_TEXTURE;
380                         
381                         for(base= sce->base.first; base; base= base->next) {
382                                 if(base->object->id.name[2]=='t') {
383                                         Material *mat= give_current_material(base->object, base->object->actcol);
384                                         if(mat && mat->mtex[0]) {
385                                                 mat->mtex[0]->tex= tex;
386                                                 
387                                                 if(tex && sp->slot)
388                                                         mat->mtex[0]->which_output = sp->slot->which_output;
389                                                 
390                                                 /* show alpha in this case */
391                                                 if(tex==NULL || (tex->flag & TEX_PRV_ALPHA)) {
392                                                         mat->mtex[0]->mapto |= MAP_ALPHA;
393                                                         mat->alpha= 0.0f;
394                                                 }
395                                                 else {
396                                                         mat->mtex[0]->mapto &= ~MAP_ALPHA;
397                                                         mat->alpha= 1.0f;
398                                                 }
399                                         }
400                                 }
401                         }
402
403                         if(tex && tex->nodetree && sp->pr_method==PR_NODE_RENDER) {
404                                 /* two previews, they get copied by wmJob */
405                                 ntreeInitPreview(origtex->nodetree, sp->sizex, sp->sizey);
406                                 ntreeInitPreview(tex->nodetree, sp->sizex, sp->sizey);
407                         }
408                 }
409                 else if(id_type==ID_LA) {
410                         Lamp *la= NULL, *origla= (Lamp *)id;
411
412                         /* work on a copy */
413                         if(origla) {
414                                 la= localize_lamp(origla);
415                                 sp->lampcopy= la;
416                                 BLI_addtail(&pr_main->lamp, la);
417                         }
418                         
419                         if(la && la->type==LA_SUN && (la->sun_effect_type & LA_SUN_EFFECT_SKY)) {
420                                 sce->lay= 1<<MA_ATMOS;
421                                 sce->world= scene->world;
422                                 sce->camera= (Object *)BLI_findstring(&pr_main->object, "CameraAtmo", offsetof(ID, name)+2);
423                         }
424                         else {
425                                 sce->lay= 1<<MA_LAMP;
426                                 sce->world= NULL;
427                                 sce->camera= (Object *)BLI_findstring(&pr_main->object, "Camera", offsetof(ID, name)+2);
428                         }
429                         sce->r.mode &= ~R_SHADOW;
430                         
431                         for(base= sce->base.first; base; base= base->next) {
432                                 if(base->object->id.name[2]=='p') {
433                                         if(base->object->type==OB_LAMP)
434                                                 base->object->data= la;
435                                 }
436                         }
437
438                         if(la && la->nodetree && sp->pr_method==PR_NODE_RENDER) {
439                                 /* two previews, they get copied by wmJob */
440                                 ntreeInitPreview(origla->nodetree, sp->sizex, sp->sizey);
441                                 ntreeInitPreview(la->nodetree, sp->sizex, sp->sizey);
442                         }
443                 }
444                 else if(id_type==ID_WO) {
445                         World *wrld= NULL, *origwrld= (World *)id;
446
447                         if(origwrld) {
448                                 wrld= localize_world(origwrld);
449                                 sp->worldcopy= wrld;
450                                 BLI_addtail(&pr_main->world, wrld);
451                         }
452
453                         sce->lay= 1<<MA_SKY;
454                         sce->world= wrld;
455
456                         if(wrld && wrld->nodetree && sp->pr_method==PR_NODE_RENDER) {
457                                 /* two previews, they get copied by wmJob */
458                                 ntreeInitPreview(wrld->nodetree, sp->sizex, sp->sizey);
459                                 ntreeInitPreview(origwrld->nodetree, sp->sizex, sp->sizey);
460                         }
461                 }
462                 
463                 return sce;
464         }
465         
466         return NULL;
467 }
468
469 /* new UI convention: draw is in pixel space already. */
470 /* uses ROUNDBOX button in block to get the rect */
471 static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int first, rcti *rect, rcti *newrect)
472 {
473         Render *re;
474         RenderResult rres;
475         char name[32];
476         int do_gamma_correct=0, do_predivide=0;
477         int offx=0, newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
478
479         if (id && GS(id->name) != ID_TE) {
480                 /* exception: don't color manage texture previews - show the raw values */
481                 if (sce) {
482                         do_gamma_correct = sce->r.color_mgt_flag & R_COLOR_MANAGEMENT;
483                         do_predivide = sce->r.color_mgt_flag & R_COLOR_MANAGEMENT_PREDIVIDE;
484                 }
485         }
486
487         if(!split || first) sprintf(name, "Preview %p", (void *)sa);
488         else sprintf(name, "SecondPreview %p", (void *)sa);
489
490         if(split) {
491                 if(first) {
492                         offx= 0;
493                         newx= newx/2;
494                 }
495                 else {
496                         offx= newx/2;
497                         newx= newx - newx/2;
498                 }
499         }
500
501         re= RE_GetRender(name);
502         RE_AcquireResultImage(re, &rres);
503
504         if(rres.rectf) {
505                 
506                 if(ABS(rres.rectx-newx)<2 && ABS(rres.recty-newy)<2) {
507
508                         newrect->xmax= MAX2(newrect->xmax, rect->xmin + rres.rectx + offx);
509                         newrect->ymax= MAX2(newrect->ymax, rect->ymin + rres.recty);
510
511                         if(rres.rectx && rres.recty) {
512                                 /* temporary conversion to byte for drawing */
513                                 float fx= rect->xmin + offx;
514                                 float fy= rect->ymin;
515                                 int profile_from= (do_gamma_correct)? IB_PROFILE_LINEAR_RGB: IB_PROFILE_SRGB;
516                                 int dither= 0;
517                                 unsigned char *rect_byte;
518
519                                 rect_byte= MEM_mallocN(rres.rectx*rres.recty*sizeof(int), "ed_preview_draw_rect");
520
521                                 IMB_buffer_byte_from_float(rect_byte, rres.rectf,
522                                         4, dither, IB_PROFILE_SRGB, profile_from, do_predivide, 
523                                         rres.rectx, rres.recty, rres.rectx, rres.rectx);
524
525                                 glaDrawPixelsSafe(fx, fy, rres.rectx, rres.recty, rres.rectx, GL_RGBA, GL_UNSIGNED_BYTE, rect_byte);
526
527                                 MEM_freeN(rect_byte);
528                         }
529
530                         RE_ReleaseResultImage(re);
531                         return 1;
532                 }
533         }
534
535         RE_ReleaseResultImage(re);
536         return 0;
537 }
538
539 void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, rcti *rect)
540 {
541         if(idp) {
542                 ScrArea *sa= CTX_wm_area(C);
543                 Scene *sce = CTX_data_scene(C);
544                 ID *id = (ID *)idp;
545                 ID *parent= (ID *)parentp;
546                 MTex *slot= (MTex *)slotp;
547                 SpaceButs *sbuts= sa->spacedata.first;
548                 rcti newrect;
549                 int ok;
550                 int newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
551
552                 newrect.xmin= rect->xmin;
553                 newrect.xmax= rect->xmin;
554                 newrect.ymin= rect->ymin;
555                 newrect.ymax= rect->ymin;
556
557                 if(parent) {
558                         ok = ed_preview_draw_rect(sa, sce, id, 1, 1, rect, &newrect);
559                         ok &= ed_preview_draw_rect(sa, sce, parent, 1, 0, rect, &newrect);
560                 }
561                 else
562                         ok = ed_preview_draw_rect(sa, sce, id, 0, 0, rect, &newrect);
563
564                 if(ok)
565                         *rect= newrect;
566
567                 /* check for spacetype... */
568                 if(sbuts->spacetype==SPACE_BUTS && sbuts->preview) {
569                         sbuts->preview= 0;
570                         ok= 0;
571                 }
572         
573                 if(ok==0) {
574                         ED_preview_shader_job(C, sa, id, parent, slot, newx, newy, PR_BUTS_RENDER);
575                 }
576         }       
577 }
578
579 /* **************************** new shader preview system ****************** */
580
581 /* inside thread, called by renderer, sets job update value */
582 static void shader_preview_draw(void *spv, RenderResult *UNUSED(rr), volatile struct rcti *UNUSED(rect))
583 {
584         ShaderPreview *sp= spv;
585         
586         *(sp->do_update)= 1;
587 }
588
589 /* called by renderer, checks job value */
590 static int shader_preview_break(void *spv)
591 {
592         ShaderPreview *sp= spv;
593
594         return *(sp->stop);
595 }
596
597 /* outside thread, called before redraw notifiers, it moves finished preview over */
598 static void shader_preview_updatejob(void *spv)
599 {
600         ShaderPreview *sp= spv;
601         
602         if(sp->id) {
603                 if(sp->pr_method==PR_NODE_RENDER) {
604                         if( GS(sp->id->name) == ID_MA) {
605                                 Material *mat= (Material *)sp->id;
606                                 
607                                 if(sp->matcopy && mat->nodetree && sp->matcopy->nodetree)
608                                         ntreeLocalSync(sp->matcopy->nodetree, mat->nodetree);
609                         }
610                         else if( GS(sp->id->name) == ID_TE) {
611                                 Tex *tex= (Tex *)sp->id;
612                                 
613                                 if(sp->texcopy && tex->nodetree && sp->texcopy->nodetree)
614                                         ntreeLocalSync(sp->texcopy->nodetree, tex->nodetree);
615                         }
616                         else if( GS(sp->id->name) == ID_WO) {
617                                 World *wrld= (World *)sp->id;
618                                 
619                                 if(sp->worldcopy && wrld->nodetree && sp->worldcopy->nodetree)
620                                         ntreeLocalSync(sp->worldcopy->nodetree, wrld->nodetree);
621                         }
622                         else if( GS(sp->id->name) == ID_LA) {
623                                 Lamp *la= (Lamp *)sp->id;
624                                 
625                                 if(sp->lampcopy && la->nodetree && sp->lampcopy->nodetree)
626                                         ntreeLocalSync(sp->lampcopy->nodetree, la->nodetree);
627                         }
628                 }               
629         }
630 }
631
632 static void shader_preview_render(ShaderPreview *sp, ID *id, int split, int first)
633 {
634         Render *re;
635         Scene *sce;
636         float oldlens;
637         short idtype= GS(id->name);
638         char name[32];
639         int sizex;
640         
641         /* get the stuff from the builtin preview dbase */
642         sce= preview_prepare_scene(sp->scene, id, idtype, sp); // XXX sizex
643         if(sce==NULL) return;
644         
645         if(!split || first) sprintf(name, "Preview %p", sp->owner);
646         else sprintf(name, "SecondPreview %p", sp->owner);
647         re= RE_GetRender(name);
648         
649         /* full refreshed render from first tile */
650         if(re==NULL)
651                 re= RE_NewRender(name);
652                 
653         /* sce->r gets copied in RE_InitState! */
654         sce->r.scemode &= ~(R_MATNODE_PREVIEW|R_TEXNODE_PREVIEW);
655         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
656
657         if(sp->pr_method==PR_ICON_RENDER) {
658                 sce->r.scemode |= R_NO_IMAGE_LOAD;
659                 sce->r.mode |= R_OSA;
660         }
661         else if(sp->pr_method==PR_NODE_RENDER) {
662                 if(idtype == ID_MA) sce->r.scemode |= R_MATNODE_PREVIEW;
663                 else if(idtype == ID_TE) sce->r.scemode |= R_TEXNODE_PREVIEW;
664                 sce->r.mode &= ~R_OSA;
665         }
666         else {  /* PR_BUTS_RENDER */
667                 sce->r.mode |= R_OSA;
668         }
669
670         /* in case of split preview, use border render */
671         if(split) {
672                 if(first) sizex= sp->sizex/2;
673                 else sizex= sp->sizex - sp->sizex/2;
674         }
675         else sizex= sp->sizex;
676
677         /* allocates or re-uses render result */
678         sce->r.xsch= sizex;
679         sce->r.ysch= sp->sizey;
680         sce->r.size= 100;
681
682         /* callbacs are cleared on GetRender() */
683         if(ELEM(sp->pr_method, PR_BUTS_RENDER, PR_NODE_RENDER)) {
684                 RE_display_draw_cb(re, sp, shader_preview_draw);
685         }
686         /* set this for all previews, default is react to G.afbreek still */
687         RE_test_break_cb(re, sp, shader_preview_break);
688         
689         /* lens adjust */
690         oldlens= ((Camera *)sce->camera->data)->lens;
691         if(sizex > sp->sizey)
692                 ((Camera *)sce->camera->data)->lens *= (float)sp->sizey/(float)sizex;
693
694         /* entire cycle for render engine */
695         RE_PreviewRender(re, pr_main, sce);
696
697         ((Camera *)sce->camera->data)->lens= oldlens;
698
699         /* handle results */
700         if(sp->pr_method==PR_ICON_RENDER) {
701                 // char *rct= (char *)(sp->pr_rect + 32*16 + 16);
702                 
703                 if(sp->pr_rect)
704                         RE_ResultGet32(re, sp->pr_rect);
705         }
706         else {
707                 /* validate owner */
708                 //if(ri->rect==NULL)
709                 //      ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
710                 //RE_ResultGet32(re, ri->rect);
711         }
712
713         /* unassign the pointers, reset vars */
714         preview_prepare_scene(sp->scene, NULL, GS(id->name), sp);
715         
716         /* XXX bad exception, end-exec is not being called in render, because it uses local main */
717 //      if(idtype == ID_TE) {
718 //              Tex *tex= (Tex *)id;
719 //              if(tex->use_nodes && tex->nodetree)
720 //                      ntreeEndExecTree(tex->nodetree);
721 //      }
722
723 }
724
725 /* runs inside thread for material and icons */
726 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
727 {
728         ShaderPreview *sp= customdata;
729
730         sp->stop= stop;
731         sp->do_update= do_update;
732
733         if(sp->parent) {
734                 shader_preview_render(sp, sp->id, 1, 1);
735                 shader_preview_render(sp, sp->parent, 1, 0);
736         }
737         else
738                 shader_preview_render(sp, sp->id, 0, 0);
739
740         *do_update= 1;
741 }
742
743 static void shader_preview_free(void *customdata)
744 {
745         ShaderPreview *sp= customdata;
746         
747         if(sp->matcopy) {
748                 struct IDProperty *properties;
749                 int a;
750                 
751                 /* node previews */
752                 shader_preview_updatejob(sp);
753                 
754                 /* get rid of copied material */
755                 BLI_remlink(&pr_main->mat, sp->matcopy);
756                 
757                 /* free_material decrements texture, prevent this. hack alert! */
758                 for(a=0; a<MAX_MTEX; a++) {
759                         MTex *mtex= sp->matcopy->mtex[a];
760                         if(mtex && mtex->tex) mtex->tex= NULL;
761                 }
762                 
763                 free_material(sp->matcopy);
764
765                 properties= IDP_GetProperties((ID *)sp->matcopy, FALSE);
766                 if (properties) {
767                         IDP_FreeProperty(properties);
768                         MEM_freeN(properties);
769                 }
770                 MEM_freeN(sp->matcopy);
771         }
772         if(sp->texcopy) {
773                 struct IDProperty *properties;
774                 /* node previews */
775                 shader_preview_updatejob(sp);
776                 
777                 /* get rid of copied texture */
778                 BLI_remlink(&pr_main->tex, sp->texcopy);
779                 free_texture(sp->texcopy);
780                 
781                 properties= IDP_GetProperties((ID *)sp->texcopy, FALSE);
782                 if (properties) {
783                         IDP_FreeProperty(properties);
784                         MEM_freeN(properties);
785                 }
786                 MEM_freeN(sp->texcopy);
787         }
788         if(sp->worldcopy) {
789                 struct IDProperty *properties;
790                 /* node previews */
791                 shader_preview_updatejob(sp);
792                 
793                 /* get rid of copied world */
794                 BLI_remlink(&pr_main->world, sp->worldcopy);
795                 free_world(sp->worldcopy);
796                 
797                 properties= IDP_GetProperties((ID *)sp->worldcopy, FALSE);
798                 if (properties) {
799                         IDP_FreeProperty(properties);
800                         MEM_freeN(properties);
801                 }
802                 MEM_freeN(sp->worldcopy);
803         }
804         if(sp->lampcopy) {
805                 struct IDProperty *properties;
806                 /* node previews */
807                 shader_preview_updatejob(sp);
808                 
809                 /* get rid of copied lamp */
810                 BLI_remlink(&pr_main->lamp, sp->lampcopy);
811                 free_lamp(sp->lampcopy);
812                 
813                 properties= IDP_GetProperties((ID *)sp->lampcopy, FALSE);
814                 if (properties) {
815                         IDP_FreeProperty(properties);
816                         MEM_freeN(properties);
817                 }
818                 MEM_freeN(sp->lampcopy);
819         }
820         
821         MEM_freeN(sp);
822 }
823
824 /* ************************* icon preview ********************** */
825
826 static void icon_copy_rect(ImBuf *ibuf, unsigned int w, unsigned int h, unsigned int *rect)
827 {
828         struct ImBuf *ima;
829         unsigned int *drect, *srect;
830         float scaledx, scaledy;
831         short ex, ey, dx, dy;
832
833         /* paranoia test */
834         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL))
835                 return;
836         
837         /* waste of cpu cyles... but the imbuf API has no other way to scale fast (ton) */
838         ima = IMB_dupImBuf(ibuf);
839         
840         if (!ima) 
841                 return;
842         
843         if (ima->x > ima->y) {
844                 scaledx = (float)w;
845                 scaledy =  ( (float)ima->y/(float)ima->x )*(float)w;
846         }
847         else {                  
848                 scaledx =  ( (float)ima->x/(float)ima->y )*(float)h;
849                 scaledy = (float)h;
850         }
851         
852         ex = (short)scaledx;
853         ey = (short)scaledy;
854         
855         dx = (w - ex) / 2;
856         dy = (h - ey) / 2;
857         
858         IMB_scalefastImBuf(ima, ex, ey);
859         
860         /* if needed, convert to 32 bits */
861         if(ima->rect==NULL)
862                 IMB_rect_from_float(ima);
863
864         srect = ima->rect;
865         drect = rect;
866
867         drect+= dy*w+dx;
868         for (;ey > 0; ey--){            
869                 memcpy(drect,srect, ex * sizeof(int));
870                 drect += w;
871                 srect += ima->x;
872         }
873
874         IMB_freeImBuf(ima);
875 }
876
877 static void set_alpha(char *cp, int sizex, int sizey, char alpha) 
878 {
879         int a, size= sizex*sizey;
880
881         for(a=0; a<size; a++, cp+=4)
882                 cp[3]= alpha;
883 }
884
885 static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
886 {
887         ShaderPreview *sp= customdata;
888         ID *id= sp->id;
889         short idtype= GS(id->name);
890
891         if(idtype == ID_IM) {
892                 Image *ima= (Image*)id;
893                 ImBuf *ibuf= NULL;
894                 ImageUser iuser= {NULL};
895
896                 /* ima->ok is zero when Image cannot load */
897                 if(ima==NULL || ima->ok==0)
898                         return;
899
900                 /* setup dummy image user */
901                 iuser.ok= iuser.framenr= 1;
902                 iuser.scene= sp->scene;
903                 
904                 /* elubie: this needs to be changed: here image is always loaded if not
905                    already there. Very expensive for large images. Need to find a way to 
906                    only get existing ibuf */
907                 ibuf = BKE_image_get_ibuf(ima, &iuser);
908                 if(ibuf==NULL || ibuf->rect==NULL)
909                         return;
910                 
911                 icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);
912
913                 *do_update= 1;
914         }
915         else if(idtype == ID_BR) {
916                 Brush *br= (Brush*)id;
917
918                 br->icon_imbuf= get_brush_icon(br);
919
920                 memset(sp->pr_rect, 0x888888, sp->sizex*sp->sizey*sizeof(unsigned int));
921
922                 if(!(br->icon_imbuf) || !(br->icon_imbuf->rect))
923                         return;
924
925                 icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);
926
927                 *do_update= 1;
928         }
929         else {
930                 /* re-use shader job */
931                 shader_preview_startjob(customdata, stop, do_update);
932
933                 /* world is rendered with alpha=0, so it wasn't displayed 
934                    this could be render option for sky to, for later */
935                 if(idtype == ID_WO) {
936                         set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
937                 }
938                 else if(idtype == ID_MA) {
939                         Material* ma = (Material*)id;
940
941                         if(ma->material_type == MA_TYPE_HALO)
942                                 set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
943                 }
944         }
945 }
946
947 /* use same function for icon & shader, so the job manager
948    does not run two of them at the same time. */
949
950 static void common_preview_startjob(void *customdata, short *stop, short *do_update, float *UNUSED(progress))
951 {
952         ShaderPreview *sp= customdata;
953
954         if(sp->pr_method == PR_ICON_RENDER)
955                 icon_preview_startjob(customdata, stop, do_update);
956         else
957                 shader_preview_startjob(customdata, stop, do_update);
958 }
959
960 /* exported functions */
961
962 static void icon_preview_add_size(IconPreview *ip, unsigned int *rect, int sizex, int sizey)
963 {
964         IconPreviewSize *cur_size = ip->sizes.first, *new_size;
965
966         while (cur_size) {
967                 if (cur_size->sizex == sizex && cur_size->sizey == sizey) {
968                         /* requested size is already in list, no need to add it again */
969                         return;
970                 }
971
972                 cur_size = cur_size->next;
973         }
974
975         new_size = MEM_callocN(sizeof(IconPreviewSize), "IconPreviewSize");
976         new_size->sizex = sizex;
977         new_size->sizey = sizey;
978         new_size->rect = rect;
979
980         BLI_addtail(&ip->sizes, new_size);
981 }
982
983 static void icon_preview_startjob_all_sizes(void *customdata, short *stop, short *do_update, float *progress)
984 {
985         IconPreview *ip = (IconPreview *)customdata;
986         IconPreviewSize *cur_size = ip->sizes.first;
987
988         while (cur_size) {
989                 ShaderPreview sp;
990
991                 memset(&sp, 0, sizeof(ShaderPreview));
992
993                 /* construct shader preview from image size and previewcustomdata */
994                 sp.scene= ip->scene;
995                 sp.owner= ip->owner;
996                 sp.sizex= cur_size->sizex;
997                 sp.sizey= cur_size->sizey;
998                 sp.pr_method= PR_ICON_RENDER;
999                 sp.pr_rect= cur_size->rect;
1000                 sp.id = ip->id;
1001
1002                 common_preview_startjob(&sp, stop, do_update, progress);
1003
1004                 cur_size = cur_size->next;
1005         }
1006 }
1007
1008 static void icon_preview_endjob(void *customdata)
1009 {
1010         IconPreview *ip = customdata;
1011
1012         if (ip->id && GS(ip->id->name) == ID_BR)
1013                 WM_main_add_notifier(NC_BRUSH|NA_EDITED, ip->id);
1014 }
1015
1016 static void icon_preview_free(void *customdata)
1017 {
1018         IconPreview *ip = (IconPreview *)customdata;
1019
1020         BLI_freelistN(&ip->sizes);
1021         MEM_freeN(ip);
1022 }
1023
1024 void ED_preview_icon_job(const bContext *C, void *owner, ID *id, unsigned int *rect, int sizex, int sizey)
1025 {
1026         wmJob *steve;
1027         IconPreview *ip, *old_ip;
1028         
1029         /* suspended start means it starts after 1 timer step, see WM_jobs_timer below */
1030         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Icon Preview", WM_JOB_EXCL_RENDER|WM_JOB_SUSPEND);
1031
1032         ip= MEM_callocN(sizeof(IconPreview), "icon preview");
1033
1034         /* render all resolutions from suspended job too */
1035         old_ip= WM_jobs_get_customdata(steve);
1036         if (old_ip)
1037                 BLI_movelisttolist(&ip->sizes, &old_ip->sizes);
1038
1039         /* customdata for preview thread */
1040         ip->scene= CTX_data_scene(C);
1041         ip->owner= id;
1042         ip->id= id;
1043
1044         icon_preview_add_size(ip, rect, sizex, sizey);
1045
1046         /* setup job */
1047         WM_jobs_customdata(steve, ip, icon_preview_free);
1048         WM_jobs_timer(steve, 0.25, NC_MATERIAL, NC_MATERIAL);
1049         WM_jobs_callbacks(steve, icon_preview_startjob_all_sizes, NULL, NULL, icon_preview_endjob);
1050
1051         WM_jobs_start(CTX_wm_manager(C), steve);
1052 }
1053
1054 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, MTex *slot, int sizex, int sizey, int method)
1055 {
1056         Object *ob= CTX_data_active_object(C);
1057         wmJob *steve;
1058         ShaderPreview *sp;
1059
1060         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Shader Preview", WM_JOB_EXCL_RENDER);
1061         sp= MEM_callocN(sizeof(ShaderPreview), "shader preview");
1062
1063         /* customdata for preview thread */
1064         sp->scene= CTX_data_scene(C);
1065         sp->owner= owner;
1066         sp->sizex= sizex;
1067         sp->sizey= sizey;
1068         sp->pr_method= method;
1069         sp->id = id;
1070         sp->parent= parent;
1071         sp->slot= slot;
1072         if(ob && ob->totcol) copy_v4_v4(sp->col, ob->col);
1073         else sp->col[0]= sp->col[1]= sp->col[2]= sp->col[3]= 1.0f;
1074         
1075         /* setup job */
1076         WM_jobs_customdata(steve, sp, shader_preview_free);
1077         WM_jobs_timer(steve, 0.1, NC_MATERIAL, NC_MATERIAL);
1078         WM_jobs_callbacks(steve, common_preview_startjob, NULL, shader_preview_updatejob, NULL);
1079         
1080         WM_jobs_start(CTX_wm_manager(C), steve);
1081 }
1082
1083 void ED_preview_kill_jobs(const struct bContext *C)
1084 {
1085         wmWindowManager *wm= CTX_wm_manager(C);
1086         if(wm)
1087                 WM_jobs_kill(wm, NULL, common_preview_startjob);
1088 }
1089