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