901bd8ce8fd818cbab74b9db86592278f85d8f38
[blender-staging.git] / source / blender / editors / render / render_preview.c
1 /* 
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) Blender Foundation.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 /* global includes */
31
32 #include <stdlib.h>
33 #include <math.h>
34 #include <string.h>
35
36 #ifndef WIN32
37 #include <unistd.h>
38 #else
39 #include <io.h>
40 #endif   
41 #include "MEM_guardedalloc.h"
42
43 #include "BLO_readfile.h" 
44
45 #include "BLI_math.h"
46 #include "BLI_blenlib.h"
47 #include "BLI_threads.h"
48
49 #include "DNA_world_types.h"
50 #include "DNA_camera_types.h"
51 #include "DNA_material_types.h"
52 #include "DNA_object_types.h"
53 #include "DNA_lamp_types.h"
54 #include "DNA_space_types.h"
55 #include "DNA_view3d_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_brush_types.h"
58 #include "DNA_screen_types.h"
59
60 #include "BKE_context.h"
61 #include "BKE_depsgraph.h"
62 #include "BKE_global.h"
63 #include "BKE_image.h"
64 #include "BKE_icons.h"
65 #include "BKE_library.h"
66 #include "BKE_main.h"
67 #include "BKE_texture.h"
68 #include "BKE_material.h"
69 #include "BKE_node.h"
70 #include "BKE_world.h"
71 #include "BKE_texture.h"
72 #include "BKE_utildefines.h"
73 #include "BKE_brush.h"
74
75 #include "IMB_imbuf.h"
76 #include "IMB_imbuf_types.h"
77
78 #include "BIF_gl.h"
79 #include "BIF_glutil.h"
80
81 #include "PIL_time.h"
82
83 #include "RE_pipeline.h"
84
85
86 #include "WM_api.h"
87 #include "WM_types.h"
88
89 #include "ED_datafiles.h"
90 #include "ED_render.h"
91 #include "ED_view3d.h"
92
93 #include "UI_interface.h"
94
95 #include "render_intern.h"
96
97 #define PR_XMIN         10
98 #define PR_YMIN         5
99 #define PR_XMAX         200
100 #define PR_YMAX         195
101
102 /* XXX */
103 static int qtest() {return 0;}
104 /* XXX */
105
106 ImBuf* get_brush_icon(Brush *brush)
107 {
108         static const int flags = IB_rect|IB_multilayer|IB_metadata;
109
110         char path[240];
111         char *folder;
112
113         if (!(brush->icon_imbuf)) {
114                 if (brush->flag & BRUSH_CUSTOM_ICON) {
115
116                         if (brush->icon_filepath[0]) {
117                                 // first use the path directly to try and load the file
118
119                                 BLI_strncpy(path, brush->icon_filepath, sizeof(brush->icon_filepath));
120                                 BLI_path_abs(path, G.sce);
121
122                                 brush->icon_imbuf= IMB_loadiffname(path, flags);
123
124                                 // otherwise lets try to find it in other directories
125                                 if (!(brush->icon_imbuf)) {
126                                         folder= BLI_get_folder(BLENDER_DATAFILES, "brushicons");
127
128                                         path[0]= 0;
129
130                                         BLI_make_file_string(G.sce, path, folder, brush->icon_filepath);
131
132                                         if (path[0])
133                                                 brush->icon_imbuf= IMB_loadiffname(path, flags);
134                                 }
135                         }
136                 }
137         }
138
139         if (!(brush->icon_imbuf))
140                 brush->id.icon_id = 0;
141         else
142                 BKE_icon_changed(BKE_icon_getid(&(brush->id)));
143
144         return brush->icon_imbuf;
145 }
146
147 typedef struct ShaderPreview {
148         /* from wmJob */
149         void *owner;
150         short *stop, *do_update;
151         
152         Scene *scene;
153         ID *id;
154         ID *parent;
155         MTex *slot;
156         
157         int sizex, sizey;
158         unsigned int *pr_rect;
159         int pr_method;
160         
161 } ShaderPreview;
162
163
164
165 /* unused now */
166 void draw_tex_crop(Tex *tex)
167 {
168         rcti rct;
169         int ret= 0;
170         
171         if(tex==0) return;
172         
173         if(tex->type==TEX_IMAGE) {
174                 if(tex->cropxmin==0.0f) ret++;
175                 if(tex->cropymin==0.0f) ret++;
176                 if(tex->cropxmax==1.0f) ret++;
177                 if(tex->cropymax==1.0f) ret++;
178                 if(ret==4) return;
179                 
180                 rct.xmin= PR_XMIN+2+tex->cropxmin*(PR_XMAX-PR_XMIN-4);
181                 rct.xmax= PR_XMIN+2+tex->cropxmax*(PR_XMAX-PR_XMIN-4);
182                 rct.ymin= PR_YMIN+2+tex->cropymin*(PR_YMAX-PR_YMIN-4);
183                 rct.ymax= PR_YMIN+2+tex->cropymax*(PR_YMAX-PR_YMIN-4);
184
185                 glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); 
186
187                 glColor3ub(0, 0, 0);
188                 glRecti(rct.xmin+1,  rct.ymin-1,  rct.xmax+1,  rct.ymax-1); 
189
190                 glColor3ub(255, 255, 255);
191                 glRecti(rct.xmin,  rct.ymin,  rct.xmax,  rct.ymax);
192
193                 glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);                      
194         }
195         
196 }
197
198 /* temporal abuse; if id_code is -1 it only does texture.... solve! */
199 void BIF_preview_changed(short id_code)
200 {
201 #if 0   
202         ScrArea *sa;
203         
204         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
205                 if(sa->spacetype==SPACE_BUTS) {
206                         SpaceButs *sbuts= sa->spacedata.first;
207                         if(sbuts->mainb==CONTEXT_SHADING) {
208                                 int tab= sbuts->tab[CONTEXT_SHADING];
209                                 if(tab==TAB_SHADING_MAT && (id_code==ID_MA || id_code==ID_TE)) {
210                                         if (sbuts->ri) sbuts->ri->curtile= 0;
211                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
212                                 }
213                                 else if(tab==TAB_SHADING_TEX && (id_code==ID_TE || id_code==-1)) {
214                                         if (sbuts->ri) sbuts->ri->curtile= 0;
215                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
216                                 }
217                                 else if(tab==TAB_SHADING_LAMP && (id_code==ID_LA || id_code==ID_TE)) {
218                                         if (sbuts->ri) sbuts->ri->curtile= 0;
219                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
220                                 }
221                                 else if(tab==TAB_SHADING_WORLD && (id_code==ID_WO || id_code==ID_TE)) {
222                                         if (sbuts->ri) sbuts->ri->curtile= 0;
223                                         addafterqueue(sa->win, RENDERPREVIEW, 1);
224                                 }
225                         }
226                         else if (sbuts->ri) 
227                                 sbuts->ri->curtile= 0;  /* ensure changes always result in re-render when context is restored */
228                 }
229                 else if(sa->spacetype==SPACE_NODE) {
230                         SpaceNode *snode= sa->spacedata.first;
231                         if(snode->treetype==NTREE_SHADER && (id_code==ID_MA || id_code==ID_TE)) {
232                                 snode_tag_dirty(snode);
233                         }
234                 }
235                 else if(sa->spacetype==SPACE_VIEW3D) {
236                         View3D *vd= sa->spacedata.first;
237                         /* if is has a renderinfo, we consider that reason for signalling */
238                         if (vd->ri) {
239                                 vd->ri->curtile= 0;
240                                 addafterqueue(sa->win, RENDERPREVIEW, 1);
241                         }
242                 }
243         }
244
245         if(ELEM4(id_code, ID_MA, ID_TE, ID_LA, ID_WO)) {
246                 Object *ob;
247                 Material *ma;
248
249                 if(id_code == ID_WO) {
250                         for(ma=G.main->mat.first; ma; ma=ma->id.next) {
251                                 if(ma->gpumaterial.first) {
252                                         GPU_material_free(ma);
253                                 }
254                         }
255                 }
256                 else if(id_code == ID_LA) {
257                         for(ob=G.main->object.first; ob; ob=ob->id.next) {
258                                 if(ob->gpulamp.first) {
259                                         GPU_lamp_free(ob);
260                                 }
261                         }
262
263                         for(ma=G.main->mat.first; ma; ma=ma->id.next) {
264                                 if(ma->gpumaterial.first) {
265                                         GPU_material_free(ma);
266                                 }
267                         }
268                 } else if(OBACT) {
269                         Object *ob = OBACT;
270
271                         ma= give_current_material(ob, ob->actcol);
272                         if(ma && ma->gpumaterial.first) {
273                                 GPU_material_free(ma);
274                         }
275                 }
276         }
277 #endif
278 }
279
280 /* *************************** Preview for buttons *********************** */
281
282 static Main *pr_main= NULL;
283
284 void ED_preview_init_dbase(void)
285 {
286         BlendFileData *bfd;
287         extern int datatoc_preview_blend_size;
288         extern char datatoc_preview_blend[];
289         
290         G.fileflags |= G_FILE_NO_UI;
291         bfd= BLO_read_from_memory(datatoc_preview_blend, datatoc_preview_blend_size, NULL);
292         if (bfd) {
293                 pr_main= bfd->main;
294                 
295                 MEM_freeN(bfd);
296         }
297         G.fileflags &= ~G_FILE_NO_UI;
298 }
299
300 void ED_preview_free_dbase(void)
301 {
302         if(pr_main)
303                 free_main(pr_main);
304 }
305
306 static Object *find_object(ListBase *lb, const char *name)
307 {
308         Object *ob;
309         for(ob= lb->first; ob; ob= ob->id.next)
310                 if(strcmp(ob->id.name+2, name)==0)
311                         break;
312         return ob;
313 }
314
315 /* call this with a pointer to initialize preview scene */
316 /* call this with NULL to restore assigned ID pointers in preview scene */
317 static Scene *preview_prepare_scene(Scene *scene, ID *id, int id_type, ShaderPreview *sp)
318 {
319         Scene *sce;
320         Base *base;
321         
322         if(pr_main==NULL) return NULL;
323         
324         sce= pr_main->scene.first;
325         if(sce) {
326                 /* this flag tells render to not execute depsgraph or ipos etc */
327                 sce->r.scemode |= R_PREVIEWBUTS;
328                 /* set world always back, is used now */
329                 sce->world= pr_main->world.first;
330                 /* now: exposure copy */
331                 if(scene->world) {
332                         sce->world->exp= scene->world->exp;
333                         sce->world->range= scene->world->range;
334                 }
335                 
336                 sce->r.color_mgt_flag = scene->r.color_mgt_flag;
337                 /* exception: don't color manage texture previews or icons */
338                 if((sp && sp->pr_method==PR_ICON_RENDER) || id_type == ID_TE)
339                         sce->r.color_mgt_flag &= ~R_COLOR_MANAGEMENT;
340                 if((sp && sp->pr_method==PR_ICON_RENDER) && id_type != ID_WO)
341                         sce->r.alphamode= R_ALPHAPREMUL;
342                 else
343                         sce->r.alphamode= R_ADDSKY;
344
345                 sce->r.cfra= scene->r.cfra;
346                 strcpy(sce->r.engine, scene->r.engine);
347                 
348                 if(id_type==ID_MA) {
349                         Material *mat= (Material *)id;
350                         
351                         if(id) {
352                                 init_render_material(mat, 0, NULL);             /* call that retrieves mode_l */
353                                 end_render_material(mat);
354                                 
355                                 /* turn on raytracing if needed */
356                                 if(mat->mode_l & MA_RAYMIRROR)
357                                         sce->r.mode |= R_RAYTRACE;
358                                 if(mat->material_type == MA_TYPE_VOLUME)
359                                         sce->r.mode |= R_RAYTRACE;
360                                 if((mat->mode_l & MA_RAYTRANSP) && (mat->mode_l & MA_TRANSP))
361                                         sce->r.mode |= R_RAYTRACE;
362                                 if(mat->sss_flag & MA_DIFF_SSS)
363                                         sce->r.mode |= R_SSS;
364                                 
365                                 /* turn off fake shadows if needed */
366                                 /* this only works in a specific case where the preview.blend contains
367                                  * an object starting with 'c' which has a material linked to it (not the obdata)
368                                  * and that material has a fake shadow texture in the active texture slot */
369                                 for(base= sce->base.first; base; base= base->next) {
370                                         if(base->object->id.name[2]=='c') {
371                                                 Material *shadmat= give_current_material(base->object, base->object->actcol);
372                                                 if(shadmat) {
373                                                         if (mat->mode & MA_SHADBUF) shadmat->septex = 0;
374                                                         else shadmat->septex |= 1;
375                                                 }
376                                         }
377                                 }
378                                 
379                                 /* turn off bounce lights for volume, 
380                                  * doesn't make much visual difference and slows it down too */
381                                 if(mat->material_type == MA_TYPE_VOLUME) {
382                                         for(base= sce->base.first; base; base= base->next) {
383                                                 if(base->object->type == OB_LAMP) {
384                                                         /* if doesn't match 'Lamp.002' --> main key light */
385                                                         if( strcmp(base->object->id.name+2, "Lamp.002") != 0 ) {
386                                                                 base->object->restrictflag |= OB_RESTRICT_RENDER;
387                                                         }
388                                                 }
389                                         }
390                                 }
391
392                                 
393                                 if(sp && sp->pr_method==PR_ICON_RENDER) {
394                                         if (mat->material_type == MA_TYPE_HALO) {
395                                                 sce->lay= 1<<MA_FLAT;
396                                         } 
397                                         else {
398                                                 sce->lay= 1<<MA_SPHERE_A;
399                                         }
400                                 }
401                                 else {
402                                         sce->lay= 1<<mat->pr_type;
403                                         if(mat->nodetree && sp->pr_method==PR_NODE_RENDER)
404                                                 ntreeInitPreview(mat->nodetree, sp->sizex, sp->sizey);
405                                 }
406                         }
407                         else {
408                                 sce->r.mode &= ~(R_OSA|R_RAYTRACE|R_SSS);
409                         }
410                         
411                         for(base= sce->base.first; base; base= base->next) {
412                                 if(base->object->id.name[2]=='p') {
413                                         if(ELEM4(base->object->type, OB_MESH, OB_CURVE, OB_SURF, OB_MBALL)) {
414                                                 /* don't use assign_material, it changed mat->id.us, which shows in the UI */
415                                                 Material ***matar= give_matarar(base->object);
416                                                 int actcol= MAX2(base->object->actcol > 0, 1) - 1;
417
418                                                 if(matar && actcol < base->object->totcol)
419                                                         (*matar)[actcol]= mat;
420                                         } else if (base->object->type == OB_LAMP) {
421                                                 base->object->restrictflag &= ~OB_RESTRICT_RENDER;
422                                         }
423                                 }
424                         }
425                 }
426                 else if(id_type==ID_TE) {
427                         Tex *tex= (Tex *)id;
428                         
429                         sce->lay= 1<<MA_TEXTURE;
430                         
431                         for(base= sce->base.first; base; base= base->next) {
432                                 if(base->object->id.name[2]=='t') {
433                                         Material *mat= give_current_material(base->object, base->object->actcol);
434                                         if(mat && mat->mtex[0]) {
435                                                 mat->mtex[0]->tex= tex;
436                                                 
437                                                 if(sp && sp->slot)
438                                                         mat->mtex[0]->which_output = sp->slot->which_output;
439                                                 
440                                                 /* show alpha in this case */
441                                                 if(tex==NULL || (tex->flag & TEX_PRV_ALPHA)) {
442                                                         mat->mtex[0]->mapto |= MAP_ALPHA;
443                                                         mat->alpha= 0.0f;
444                                                 }
445                                                 else {
446                                                         mat->mtex[0]->mapto &= ~MAP_ALPHA;
447                                                         mat->alpha= 1.0f;
448                                                 }
449                                         }
450                                 }
451                         }
452
453                         if(tex && tex->nodetree && sp && sp->pr_method==PR_NODE_RENDER)
454                                 ntreeInitPreview(tex->nodetree, sp->sizex, sp->sizey);
455                 }
456                 else if(id_type==ID_LA) {
457                         Lamp *la= (Lamp *)id;
458                         
459                         if(la && la->type==LA_SUN && (la->sun_effect_type & LA_SUN_EFFECT_SKY)) {
460                                 sce->lay= 1<<MA_ATMOS;
461                                 sce->world= scene->world;
462                                 sce->camera= (Object *)find_object(&pr_main->object, "CameraAtmo");
463                         }
464                         else {
465                                 sce->lay= 1<<MA_LAMP;
466                                 sce->world= NULL;
467                                 sce->camera= (Object *)find_object(&pr_main->object, "Camera");
468                         }
469                         sce->r.mode &= ~R_SHADOW;
470                         
471                         for(base= sce->base.first; base; base= base->next) {
472                                 if(base->object->id.name[2]=='p') {
473                                         if(base->object->type==OB_LAMP)
474                                                 base->object->data= la;
475                                 }
476                         }
477                 }
478                 else if(id_type==ID_WO) {
479                         sce->lay= 1<<MA_SKY;
480                         sce->world= (World *)id;
481                 }
482                 
483                 return sce;
484         }
485         
486         return NULL;
487 }
488
489 /* new UI convention: draw is in pixel space already. */
490 /* uses ROUNDBOX button in block to get the rect */
491 static int ed_preview_draw_rect(ScrArea *sa, Scene *sce, ID *id, int split, int first, rcti *rect, rcti *newrect)
492 {
493         Render *re;
494         RenderResult rres;
495         char name[32];
496         int gamma_correct=0;
497         int offx=0, newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
498
499         if (id && GS(id->name) != ID_TE) {
500                 /* exception: don't color manage texture previews - show the raw values */
501                 if (sce) gamma_correct = sce->r.color_mgt_flag & R_COLOR_MANAGEMENT;
502         }
503
504         if(!split || first) sprintf(name, "Preview %p", sa);
505         else sprintf(name, "SecondPreview %p", sa);
506
507         if(split) {
508                 if(first) {
509                         offx= 0;
510                         newx= newx/2;
511                 }
512                 else {
513                         offx= newx/2;
514                         newx= newx - newx/2;
515                 }
516         }
517
518         re= RE_GetRender(name);
519         RE_AcquireResultImage(re, &rres);
520
521         if(rres.rectf) {
522                 
523                 if(ABS(rres.rectx-newx)<2 && ABS(rres.recty-newy)<2) {
524                         newrect->xmax= MAX2(newrect->xmax, rect->xmin + rres.rectx + offx);
525                         newrect->ymax= MAX2(newrect->ymax, rect->ymin + rres.recty);
526
527                         glaDrawPixelsSafe_to32(rect->xmin+offx, rect->ymin, rres.rectx, rres.recty, rres.rectx, rres.rectf, gamma_correct);
528
529                         RE_ReleaseResultImage(re);
530                         return 1;
531                 }
532         }
533
534         RE_ReleaseResultImage(re);
535         return 0;
536 }
537
538 void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, rcti *rect)
539 {
540         if(idp) {
541                 ScrArea *sa= CTX_wm_area(C);
542                 Scene *sce = CTX_data_scene(C);
543                 ID *id = (ID *)idp;
544                 ID *parent= (ID *)parentp;
545                 MTex *slot= (MTex *)slotp;
546                 SpaceButs *sbuts= sa->spacedata.first;
547                 rcti newrect;
548                 int ok;
549                 int newx= rect->xmax-rect->xmin, newy= rect->ymax-rect->ymin;
550
551                 newrect.xmin= rect->xmin;
552                 newrect.xmax= rect->xmin;
553                 newrect.ymin= rect->ymin;
554                 newrect.ymax= rect->ymin;
555
556                 if(parent) {
557                         ok = ed_preview_draw_rect(sa, sce, parent, 1, 1, rect, &newrect);
558                         ok &= ed_preview_draw_rect(sa, sce, id, 1, 0, rect, &newrect);
559                 }
560                 else
561                         ok = ed_preview_draw_rect(sa, sce, id, 0, 0, rect, &newrect);
562
563                 if(ok)
564                         *rect= newrect;
565
566                 /* check for spacetype... */
567                 if(sbuts->spacetype==SPACE_BUTS && sbuts->preview) {
568                         sbuts->preview= 0;
569                         ok= 0;
570                 }
571                 
572                 if(ok==0) {
573                         ED_preview_shader_job(C, sa, id, parent, slot, newx, newy, PR_BUTS_RENDER);
574                 }
575         }       
576 }
577
578 /* ******************************** Icon Preview **************************** */
579
580 void ED_preview_icon_draw(const bContext *C, void *idp, void *arg1, void *arg2, rcti *rect)
581 {
582 }
583
584 /* *************************** Preview for 3d window *********************** */
585
586 void view3d_previewrender_progress(RenderResult *rr, volatile rcti *renrect)
587 {
588 //      ScrArea *sa= NULL; // XXX
589 //      View3D *v3d= NULL; // XXX
590         RenderLayer *rl;
591         int ofsx=0, ofsy=0;
592         
593         if(renrect) return;
594         
595         rl= rr->layers.first;
596         
597         /* this case is when we render envmaps... */
598 //      if(rr->rectx > v3d->ri->pr_rectx || rr->recty > v3d->ri->pr_recty)
599 //              return;
600         
601 //      ofsx= v3d->ri->disprect.xmin + rr->tilerect.xmin;
602 //      ofsy= v3d->ri->disprect.ymin + rr->tilerect.ymin;
603         
604         glDrawBuffer(GL_FRONT);
605 //      glaDefine2DArea(&sa->winrct);
606         glaDrawPixelsSafe_to32(ofsx, ofsy, rr->rectx, rr->recty, rr->rectx, rl->rectf, 0);
607         bglFlush();
608         glDrawBuffer(GL_BACK);
609
610 }
611
612 void BIF_view3d_previewrender_signal(ScrArea *sa, short signal)
613 {
614 #if 0
615         View3D *v3d= sa->spacedata.first;
616         
617         /* this can be called from other window... solve! */
618         if(sa->spacetype!=SPACE_VIEW3D)
619                 return; // XXX
620            
621         if(v3d && v3d->ri) {
622                 RenderInfo *ri= v3d->ri;
623                 ri->status &= ~signal;
624                 ri->curtile= 0;
625                 //printf("preview signal %d\n", signal);
626                 if(ri->re && (signal & PR_DBASE))
627                         RE_Database_Free(ri->re);
628
629 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
630         }
631 #endif
632 }
633
634 void BIF_view3d_previewrender_free(View3D *v3d)
635 {
636 #if 0
637         if(v3d->ri) {
638                 RenderInfo *ri= v3d->ri;
639                 if(ri->re) {
640 //                      printf("free render\n");
641                         RE_Database_Free(ri->re);
642                         RE_FreeRender(ri->re);
643                         ri->re= NULL;
644                 }
645                 if (v3d->ri->rect) MEM_freeN(v3d->ri->rect);
646                 MEM_freeN(v3d->ri);
647                 v3d->ri= NULL;
648         }
649 #endif
650 }
651
652 /* returns 1 if OK, do not call while in panel space!  */
653 static int view3d_previewrender_get_rects(ScrArea *sa, rctf *viewplane, RenderInfo *ri, float *clipsta, float *clipend, int *ortho, float *pixsize)
654 {
655         View3D *v3d= NULL; // XXX
656         RegionView3D *rv3d= NULL; // XXX
657         int rectx, recty;
658 //      uiBlock *block;
659         
660 //      block= uiFindOpenPanelBlockName(&sa->uiblocks, "Preview");
661 //      if(block==NULL) return 0;
662         
663         /* calculate preview rect size */
664 //      BLI_init_rctf(viewplane, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
665 //      uiPanelPush(block);
666 //      ui_graphics_to_window_rct(sa->win, viewplane, &ri->disprect);
667 //      uiPanelPop(block);
668         
669         /* correction for gla draw */
670 //      BLI_translate_rcti(&ri->disprect, -sa->winrct.xmin, -sa->winrct.ymin);
671         
672         *ortho= get_view3d_viewplane(v3d, rv3d, sa->winx, sa->winy, viewplane, clipsta, clipend, pixsize);
673
674         rectx= ri->disprect.xmax - ri->disprect.xmin;
675         recty= ri->disprect.ymax - ri->disprect.ymin;
676         
677         if(rectx<4 || recty<4) return 0;
678         
679         if(ri->rect && (rectx!=ri->pr_rectx || recty!=ri->pr_recty)) {
680                 MEM_freeN(ri->rect);
681                 ri->rect= NULL;
682                 ri->curtile= 0;
683                 printf("changed size\n");
684         }
685         ri->pr_rectx= rectx;
686         ri->pr_recty= recty;
687         
688         return 1;
689 }
690
691 /* called before a panel gets moved/scaled, makes sure we can see through */
692 void BIF_view3d_previewrender_clear(ScrArea *sa)
693 {
694 #if 0
695         View3D *v3d= sa->spacedata.first;
696
697         if(v3d->ri) {
698                 RenderInfo *ri= v3d->ri;
699                 ri->curtile= 0;
700                 if(ri->rect)
701                         MEM_freeN(ri->rect);
702                 ri->rect= NULL;
703         }
704 #endif
705 }
706
707 /* afterqueue call */
708 void BIF_view3d_previewrender(Main *bmain, Scene *scene, ScrArea *sa)
709 {
710         View3D *v3d= sa->spacedata.first;
711         RegionView3D *rv3d= NULL; // XXX
712         Render *re;
713         RenderInfo *ri=NULL;    /* preview struct! */
714         RenderStats *rstats;
715         RenderData rdata;
716         rctf viewplane;
717         float clipsta, clipend, pixsize;
718         int orth;
719         
720         /* first get the render info right */
721 //      if (!v3d->ri) {
722 //              ri= v3d->ri= MEM_callocN(sizeof(RenderInfo), "butsrenderinfo");
723 //              ri->tottile= 10000;
724 //      }
725 //      ri= v3d->ri;
726         
727         if(0==view3d_previewrender_get_rects(sa, &viewplane, ri, &clipsta, &clipend, &orth, &pixsize))
728                 return;
729         
730         /* render is finished, so return */
731         if(ri->tottile && ri->curtile>=ri->tottile) return;
732
733         /* or return with a new event */
734         if(qtest()) {
735 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
736                 return;
737         }
738         //printf("Enter previewrender\n");
739         /* ok, are we rendering all over? */
740         if(ri->re==NULL) {
741                 char name[32];
742                 
743                 ri->status= 0;
744                 
745                 sprintf(name, "View3dPreview %p", sa);
746                 re= ri->re= RE_NewRender(name);
747                 //RE_display_draw_cb(re, view3d_previewrender_progress);
748                 //RE_stats_draw_cb(re, view3d_previewrender_stats);
749                 //RE_test_break_cb(re, qtest);
750                 
751                 /* no osa, blur, seq, layers, etc for preview render */
752                 rdata= scene->r;
753                 rdata.mode &= ~(R_OSA|R_MBLUR);
754                 rdata.scemode &= ~(R_DOSEQ|R_DOCOMP|R_FREE_IMAGE);
755                 rdata.layers.first= rdata.layers.last= NULL;
756                 rdata.renderer= R_INTERN;
757                  
758                 RE_InitState(re, NULL, &rdata, NULL, sa->winx, sa->winy, &ri->disprect);
759         
760                 if(orth)
761                         RE_SetOrtho(re, &viewplane, clipsta, clipend);
762                 else
763                         RE_SetWindow(re, &viewplane, clipsta, clipend);
764                 RE_SetPixelSize(re, pixsize);
765                 
766                 /* until here are no escapes */
767                 ri->status |= PR_DISPRECT;
768                 ri->curtile= 0;
769                 //printf("new render\n");
770         }
771
772         re= ri->re;
773         
774         PIL_sleep_ms(100);      /* wait 0.1 second if theres really no event... */
775         if(qtest()==0)  {
776                 
777                 /* check status */
778                 if((ri->status & PR_DISPRECT)==0) {
779                         RE_SetDispRect(ri->re, &ri->disprect);
780                         if(orth)
781                                 RE_SetOrtho(ri->re, &viewplane, clipsta, clipend);
782                         else
783                                 RE_SetWindow(ri->re, &viewplane, clipsta, clipend);
784                         RE_SetPixelSize(re, pixsize);
785                         ri->status |= PR_DISPRECT;
786                         ri->curtile= 0;
787                         //printf("disprect update\n");
788                 }
789                 if((ri->status & PR_DBASE)==0) {
790                         unsigned int lay= scene->lay;
791                         
792                         RE_SetView(re, rv3d->viewmat);
793                         
794                         /* allow localview render for objects with lights in normal layers */
795                         if(v3d->lay & 0xFF000000)
796                                 lay |= v3d->lay;
797                         else lay= v3d->lay;
798                         
799                         RE_Database_FromScene(re, scene, lay, 0);               // 0= dont use camera view
800                         
801                         rstats= RE_GetStats(re);
802                         if(rstats->convertdone) 
803                                 ri->status |= PR_DBASE|PR_PROJECTED|PR_ROTATED;
804                         ri->curtile= 0;
805                         
806                         /* database can have created render-resol data... */
807                         if(rstats->convertdone) 
808                                 DAG_scene_flush_update(bmain, scene, scene->lay, 0);
809                         
810                         //printf("dbase update\n");
811                 }
812                 if((ri->status & PR_PROJECTED)==0) {
813                         if(ri->status & PR_DBASE) {
814                                 if(orth)
815                                         RE_SetOrtho(ri->re, &viewplane, clipsta, clipend);
816                                 else
817                                         RE_SetWindow(ri->re, &viewplane, clipsta, clipend);
818                                 RE_DataBase_ApplyWindow(re);
819                                 ri->status |= PR_PROJECTED;
820                         }
821                         ri->curtile= 0;
822                         //printf("project update\n");
823                 }
824         
825                 /* OK, can we enter render code? */
826                 if(ri->status==(PR_DISPRECT|PR_DBASE|PR_PROJECTED|PR_ROTATED)) {
827                         //printf("curtile %d tottile %d\n", ri->curtile, ri->tottile);
828                         RE_TileProcessor(ri->re); //, ri->curtile, 0);
829         
830                         if(ri->rect==NULL)
831                                 ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "preview view3d rect");
832                         
833                         RE_ResultGet32(ri->re, ri->rect);
834                 }
835                 
836                 rstats= RE_GetStats(ri->re);
837 //              if(rstats->totpart==rstats->partsdone && rstats->partsdone)
838 //                      addqueue(sa->win, REDRAW, 1);
839 //              else
840 //                      addafterqueue(sa->win, RENDERPREVIEW, 1);
841                 
842                 ri->curtile= rstats->partsdone;
843                 ri->tottile= rstats->totpart;
844         }
845         else {
846 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
847         }
848         
849         //printf("\n");
850 }
851
852 /* in panel space! */
853 static void view3d_previewdraw_rect(ScrArea *sa, uiBlock *block, RenderInfo *ri)
854 {
855 //      rctf dispf;
856         
857         if(ri->rect==NULL)
858                 return;
859         
860 //      BLI_init_rctf(&dispf, 15.0f, (block->maxx - block->minx)-15.0f, 15.0f, (block->maxy - block->miny)-15.0f);
861 //      ui_graphics_to_window_rct(sa->win, &dispf, &ri->disprect);
862
863         /* correction for gla draw */
864 //      BLI_translate_rcti(&ri->disprect, -sa->winrct.xmin, -sa->winrct.ymin);
865         
866         /* when panel scale changed, free rect */
867         if(ri->disprect.xmax-ri->disprect.xmin != ri->pr_rectx ||
868            ri->disprect.ymax-ri->disprect.ymin != ri->pr_recty) {
869                 MEM_freeN(ri->rect);
870                 ri->rect= NULL;
871         }
872         else {
873 //              glaDefine2DArea(&sa->winrct);
874                 glaDrawPixelsSafe(ri->disprect.xmin, ri->disprect.ymin, ri->pr_rectx, ri->pr_recty, ri->pr_rectx, GL_RGBA, GL_UNSIGNED_BYTE, ri->rect);
875         }       
876 }
877
878 /* is panel callback, supposed to be called with correct panel offset matrix */
879 void BIF_view3d_previewdraw(struct ScrArea *sa, struct uiBlock *block)
880 {
881         RegionView3D *rv3d= NULL;
882
883 //      if (v3d->ri==NULL || v3d->ri->rect==NULL) 
884 //              addafterqueue(sa->win, RENDERPREVIEW, 1);
885 //      else {
886                 view3d_previewdraw_rect(sa, block, rv3d->ri);
887 //              if(v3d->ri->curtile==0) 
888 //                      addafterqueue(sa->win, RENDERPREVIEW, 1);
889 //      }
890 }
891
892
893 /* **************************** new shader preview system ****************** */
894
895 /* inside thread, called by renderer, sets job update value */
896 static void shader_preview_draw(void *spv, RenderResult *rr, volatile struct rcti *rect)
897 {
898         ShaderPreview *sp= spv;
899         
900         *(sp->do_update)= 1;
901 }
902
903 /* called by renderer, checks job value */
904 static int shader_preview_break(void *spv)
905 {
906         ShaderPreview *sp= spv;
907         
908         return *(sp->stop);
909 }
910
911 /* outside thread, called before redraw notifiers, it moves finished preview over */
912 static void shader_preview_updatejob(void *spv)
913 {
914 //      ShaderPreview *sp= spv;
915         
916 }
917
918 static void shader_preview_render(ShaderPreview *sp, ID *id, int split, int first)
919 {
920         Render *re;
921         Scene *sce;
922         float oldlens;
923         short idtype= GS(id->name);
924         char name[32];
925         int sizex;
926
927         /* get the stuff from the builtin preview dbase */
928         sce= preview_prepare_scene(sp->scene, id, idtype, sp); // XXX sizex
929         if(sce==NULL) return;
930         
931         if(!split || first) sprintf(name, "Preview %p", sp->owner);
932         else sprintf(name, "SecondPreview %p", sp->owner);
933         re= RE_GetRender(name);
934         
935         /* full refreshed render from first tile */
936         if(re==NULL)
937                 re= RE_NewRender(name);
938                 
939         /* sce->r gets copied in RE_InitState! */
940         sce->r.scemode &= ~(R_MATNODE_PREVIEW|R_TEXNODE_PREVIEW);
941         sce->r.scemode &= ~R_NO_IMAGE_LOAD;
942
943         if(sp->pr_method==PR_ICON_RENDER) {
944                 sce->r.scemode |= R_NO_IMAGE_LOAD;
945                 sce->r.mode |= R_OSA;
946         }
947         else if(sp->pr_method==PR_NODE_RENDER) {
948                 if(idtype == ID_MA) sce->r.scemode |= R_MATNODE_PREVIEW;
949                 else if(idtype == ID_TE) sce->r.scemode |= R_TEXNODE_PREVIEW;
950                 sce->r.mode |= R_OSA;
951         }
952         else {  /* PR_BUTS_RENDER */
953                 sce->r.mode |= R_OSA;
954         }
955
956         /* in case of split preview, use border render */
957         if(split) {
958                 if(first) sizex= sp->sizex/2;
959                 else sizex= sp->sizex - sp->sizex/2;
960         }
961         else sizex= sp->sizex;
962
963         /* allocates or re-uses render result */
964         sce->r.xsch= sizex;
965         sce->r.ysch= sp->sizey;
966         sce->r.size= 100;
967
968         /* callbacs are cleared on GetRender() */
969         if(ELEM(sp->pr_method, PR_BUTS_RENDER, PR_NODE_RENDER)) {
970                 RE_display_draw_cb(re, sp, shader_preview_draw);
971                 RE_test_break_cb(re, sp, shader_preview_break);
972         }
973         /* lens adjust */
974         oldlens= ((Camera *)sce->camera->data)->lens;
975         if(sizex > sp->sizey)
976                 ((Camera *)sce->camera->data)->lens *= (float)sp->sizey/(float)sizex;
977
978         /* entire cycle for render engine */
979         RE_PreviewRender(re, G.main, sce);
980
981         ((Camera *)sce->camera->data)->lens= oldlens;
982
983         /* handle results */
984         if(sp->pr_method==PR_ICON_RENDER) {
985                 if(sp->pr_rect)
986                         RE_ResultGet32(re, sp->pr_rect);
987         }
988         else {
989                 /* validate owner */
990                 //if(ri->rect==NULL)
991                 //      ri->rect= MEM_mallocN(sizeof(int)*ri->pr_rectx*ri->pr_recty, "BIF_previewrender");
992                 //RE_ResultGet32(re, ri->rect);
993         }
994
995         /* unassign the pointers, reset vars */
996         preview_prepare_scene(sp->scene, NULL, GS(id->name), NULL);
997 }
998
999 /* runs inside thread for material and icons */
1000 static void shader_preview_startjob(void *customdata, short *stop, short *do_update)
1001 {
1002         ShaderPreview *sp= customdata;
1003
1004         sp->stop= stop;
1005         sp->do_update= do_update;
1006
1007         if(sp->parent) {
1008                 shader_preview_render(sp, sp->parent, 1, 1);
1009                 shader_preview_render(sp, sp->id, 1, 0);
1010         }
1011         else
1012                 shader_preview_render(sp, sp->id, 0, 0);
1013
1014         *do_update= 1;
1015 }
1016
1017 static void shader_preview_free(void *customdata)
1018 {
1019         ShaderPreview *sp= customdata;
1020         
1021         MEM_freeN(sp);
1022 }
1023
1024 /* ************************* icon preview ********************** */
1025
1026 static void icon_copy_rect(ImBuf *ibuf, unsigned int w, unsigned int h, unsigned int *rect)
1027 {
1028         struct ImBuf *ima;
1029         unsigned int *drect, *srect;
1030         float scaledx, scaledy;
1031         short ex, ey, dx, dy;
1032
1033         /* paranoia test */
1034         if(ibuf==NULL || (ibuf->rect==NULL && ibuf->rect_float==NULL))
1035                 return;
1036         
1037         /* waste of cpu cyles... but the imbuf API has no other way to scale fast (ton) */
1038         ima = IMB_dupImBuf(ibuf);
1039         
1040         if (!ima) 
1041                 return;
1042         
1043         if (ima->x > ima->y) {
1044                 scaledx = (float)w;
1045                 scaledy =  ( (float)ima->y/(float)ima->x )*(float)w;
1046         }
1047         else {                  
1048                 scaledx =  ( (float)ima->x/(float)ima->y )*(float)h;
1049                 scaledy = (float)h;
1050         }
1051         
1052         ex = (short)scaledx;
1053         ey = (short)scaledy;
1054         
1055         dx = (w - ex) / 2;
1056         dy = (h - ey) / 2;
1057         
1058         IMB_scalefastImBuf(ima, ex, ey);
1059         
1060         /* if needed, convert to 32 bits */
1061         if(ima->rect==NULL)
1062                 IMB_rect_from_float(ima);
1063
1064         srect = ima->rect;
1065         drect = rect;
1066
1067         drect+= dy*w+dx;
1068         for (;ey > 0; ey--){            
1069                 memcpy(drect,srect, ex * sizeof(int));
1070                 drect += w;
1071                 srect += ima->x;
1072         }
1073
1074         IMB_freeImBuf(ima);
1075 }
1076
1077 static void set_alpha(char *cp, int sizex, int sizey, char alpha) 
1078 {
1079         int a, size= sizex*sizey;
1080
1081         for(a=0; a<size; a++, cp+=4)
1082                 cp[3]= alpha;
1083 }
1084
1085 static void icon_preview_startjob(void *customdata, short *stop, short *do_update)
1086 {
1087         ShaderPreview *sp= customdata;
1088         ID *id= sp->id;
1089         short idtype= GS(id->name);
1090
1091         if(idtype == ID_IM) {
1092                 Image *ima= (Image*)id;
1093                 ImBuf *ibuf= NULL;
1094                 ImageUser iuser;
1095
1096                 /* ima->ok is zero when Image cannot load */
1097                 if(ima==NULL || ima->ok==0)
1098                         return;
1099
1100                 /* setup dummy image user */
1101                 memset(&iuser, 0, sizeof(ImageUser));
1102                 iuser.ok= iuser.framenr= 1;
1103                 iuser.scene= sp->scene;
1104                 
1105                 /* elubie: this needs to be changed: here image is always loaded if not
1106                    already there. Very expensive for large images. Need to find a way to 
1107                    only get existing ibuf */
1108                 ibuf = BKE_image_get_ibuf(ima, &iuser);
1109                 if(ibuf==NULL || ibuf->rect==NULL)
1110                         return;
1111                 
1112                 icon_copy_rect(ibuf, sp->sizex, sp->sizey, sp->pr_rect);
1113
1114                 *do_update= 1;
1115         }
1116         else if(idtype == ID_BR) {
1117                 Brush *br= (Brush*)id;
1118
1119                 br->icon_imbuf= get_brush_icon(br);
1120
1121                 if(!(br->icon_imbuf) || !(br->icon_imbuf->rect))
1122                         return;
1123
1124                 memset(sp->pr_rect, 0x888888, sp->sizex*sp->sizey*sizeof(unsigned int));
1125                 icon_copy_rect(br->icon_imbuf, sp->sizex, sp->sizey, sp->pr_rect);
1126
1127                 *do_update= 1;
1128         }
1129         else {
1130                 /* re-use shader job */
1131                 shader_preview_startjob(customdata, stop, do_update);
1132
1133                 /* world is rendered with alpha=0, so it wasn't displayed 
1134                    this could be render option for sky to, for later */
1135                 if(idtype == ID_WO) {
1136                         set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
1137                 }
1138                 else if(idtype == ID_MA) {
1139                         Material* ma = (Material*)id;
1140
1141                         if(ma->material_type == MA_TYPE_HALO)
1142                                 set_alpha((char*)sp->pr_rect, sp->sizex, sp->sizey, 255);
1143                 }
1144         }
1145 }
1146
1147 /* use same function for icon & shader, so the job manager
1148    does not run two of them at the same time. */
1149
1150 static void common_preview_startjob(void *customdata, short *stop, short *do_update, float *progress)
1151 {
1152         ShaderPreview *sp= customdata;
1153
1154         if(sp->pr_method == PR_ICON_RENDER)
1155                 icon_preview_startjob(customdata, stop, do_update);
1156         else
1157                 shader_preview_startjob(customdata, stop, do_update);
1158 }
1159
1160 static void common_preview_endjob(void *customdata)
1161 {
1162         ShaderPreview *sp= customdata;
1163
1164         if(sp->id && GS(sp->id->name) == ID_BR)
1165                 WM_main_add_notifier(NC_BRUSH|NA_EDITED, sp->id);
1166 }
1167
1168 /* exported functions */
1169
1170 void ED_preview_icon_job(const bContext *C, void *owner, ID *id, unsigned int *rect, int sizex, int sizey)
1171 {
1172         wmJob *steve;
1173         ShaderPreview *sp;
1174
1175         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Icon Preview", WM_JOB_EXCL_RENDER);
1176         sp= MEM_callocN(sizeof(ShaderPreview), "shader preview");
1177
1178         /* customdata for preview thread */
1179         sp->scene= CTX_data_scene(C);
1180         sp->owner= id;
1181         sp->sizex= sizex;
1182         sp->sizey= sizey;
1183         sp->pr_method= PR_ICON_RENDER;
1184         sp->pr_rect= rect;
1185         sp->id = id;
1186         
1187         /* setup job */
1188         WM_jobs_customdata(steve, sp, shader_preview_free);
1189         WM_jobs_timer(steve, 0.1, NC_MATERIAL, NC_MATERIAL);
1190         WM_jobs_callbacks(steve, common_preview_startjob, NULL, NULL, common_preview_endjob);
1191
1192         WM_jobs_start(CTX_wm_manager(C), steve);
1193 }
1194
1195 void ED_preview_shader_job(const bContext *C, void *owner, ID *id, ID *parent, MTex *slot, int sizex, int sizey, int method)
1196 {
1197         wmJob *steve;
1198         ShaderPreview *sp;
1199
1200         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), owner, "Shader Preview", WM_JOB_EXCL_RENDER);
1201         sp= MEM_callocN(sizeof(ShaderPreview), "shader preview");
1202
1203         /* customdata for preview thread */
1204         sp->scene= CTX_data_scene(C);
1205         sp->owner= owner;
1206         sp->sizex= sizex;
1207         sp->sizey= sizey;
1208         sp->pr_method= method;
1209         sp->id = id;
1210         sp->parent= parent;
1211         sp->slot= slot;
1212         
1213         /* setup job */
1214         WM_jobs_customdata(steve, sp, shader_preview_free);
1215         WM_jobs_timer(steve, 0.1, NC_MATERIAL, NC_MATERIAL);
1216         WM_jobs_callbacks(steve, common_preview_startjob, NULL, shader_preview_updatejob, NULL);
1217         
1218         WM_jobs_start(CTX_wm_manager(C), steve);
1219 }
1220
1221 void ED_preview_kill_jobs(const struct bContext *C)
1222 {
1223         wmWindowManager *wm= CTX_wm_manager(C);
1224         if(wm)
1225                 WM_jobs_kill(wm, NULL, common_preview_startjob);
1226 }
1227