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