whitespace edits, make formatting for functions consustent at least within the file.
[blender.git] / source / blender / editors / object / object_bake.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) 2004 by Blender Foundation
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): Morten Mikkelsen,
26  *                 Sergey Sharybin
27  *
28  * ***** END GPL LICENSE BLOCK *****
29  */
30
31 /** \file blender/editors/object/object_bake.c
32  *  \ingroup edobj
33  */
34
35
36 /*
37         meshtools.c: no editmode (violated already :), tools operating on meshes
38 */
39
40 #include <string.h>
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_scene_types.h"
45 #include "DNA_screen_types.h"
46 #include "DNA_space_types.h"
47 #include "DNA_world_types.h"
48 #include "DNA_object_types.h"
49 #include "DNA_mesh_types.h"
50 #include "DNA_meshdata_types.h"
51
52 #include "BLI_blenlib.h"
53 #include "BLI_threads.h"
54 #include "BLI_utildefines.h"
55 #include "BLI_math.h"
56 #include "BLI_math_geom.h"
57
58 #include "BKE_blender.h"
59 #include "BKE_context.h"
60 #include "BKE_global.h"
61 #include "BKE_image.h"
62 #include "BKE_main.h"
63 #include "BKE_multires.h"
64 #include "BKE_report.h"
65 #include "BKE_cdderivedmesh.h"
66 #include "BKE_modifier.h"
67 #include "BKE_DerivedMesh.h"
68 #include "BKE_subsurf.h"
69
70 #include "RE_pipeline.h"
71 #include "RE_shader_ext.h"
72
73 #include "PIL_time.h"
74
75 #include "IMB_imbuf_types.h"
76 #include "IMB_imbuf.h"
77
78 #include "GPU_draw.h" /* GPU_free_image */
79
80 #include "WM_api.h"
81 #include "WM_types.h"
82
83 #include "ED_object.h"
84
85 #include "object_intern.h"
86
87 /* ****************** multires BAKING ********************** */
88
89 /* holder of per-object data needed for bake job
90    needed to make job totally thread-safe */
91 typedef struct MultiresBakerJobData {
92         struct MultiresBakerJobData *next, *prev;
93         DerivedMesh *lores_dm, *hires_dm;
94         int simple, lvl, tot_lvl;
95 } MultiresBakerJobData;
96
97 /* data passing to multires-baker job */
98 typedef struct {
99         ListBase data;
100         int bake_clear, bake_filter;
101         short mode, use_lores_mesh;
102 } MultiresBakeJob;
103
104 /* data passing to multires baker */
105 typedef struct {
106         DerivedMesh *lores_dm, *hires_dm;
107         int simple, lvl, tot_lvl, bake_filter;
108         short mode, use_lores_mesh;
109
110         int tot_obj, tot_image;
111         ListBase image;
112
113         int baked_objects, baked_faces;
114
115         short *stop;
116         short *do_update;
117         float *progress;
118 } MultiresBakeRender;
119
120 typedef void (*MPassKnownData)(DerivedMesh *lores_dm, DerivedMesh *hires_dm, const void *bake_data,
121                                const int face_index, const int lvl, const float st[2],
122                                float tangmat[3][3], const int x, const int y);
123
124 typedef void* (*MInitBakeData)(MultiresBakeRender *bkr, Image* ima);
125 typedef void (*MApplyBakeData)(void *bake_data);
126 typedef void (*MFreeBakeData)(void *bake_data);
127
128 typedef struct {
129         MVert *mvert;
130         MFace *mface;
131         MTFace *mtface;
132         float *pvtangent;
133         float *precomputed_normals;
134         int w, h;
135         int face_index;
136         int i0, i1, i2;
137         DerivedMesh *lores_dm, *hires_dm;
138         int lvl;
139         void *bake_data;
140         MPassKnownData pass_data;
141 } MResolvePixelData;
142
143 typedef void (*MFlushPixel)(const MResolvePixelData *data, const int x, const int y);
144
145 typedef struct {
146         int w, h;
147         char *texels;
148         const MResolvePixelData *data;
149         MFlushPixel flush_pixel;
150 } MBakeRast;
151
152 typedef struct {
153         float *heights;
154         float height_min, height_max;
155         Image *ima;
156         DerivedMesh *ssdm;
157 } MHeightBakeData;
158
159 static void multiresbake_get_normal(const MResolvePixelData *data, float norm[], const int face_num, const int vert_index)
160 {
161         unsigned int indices[]= {data->mface[face_num].v1, data->mface[face_num].v2,
162                                  data->mface[face_num].v3, data->mface[face_num].v4};
163         const int smoothnormal= (data->mface[face_num].flag & ME_SMOOTH);
164
165         if(!smoothnormal)  { /* flat */
166                 if(data->precomputed_normals) {
167                         copy_v3_v3(norm, &data->precomputed_normals[3*face_num]);
168                 } else {
169                         float nor[3];
170                         float *p0, *p1, *p2;
171                         const int iGetNrVerts= data->mface[face_num].v4!=0 ? 4 : 3;
172
173                         p0= data->mvert[indices[0]].co;
174                         p1= data->mvert[indices[1]].co;
175                         p2= data->mvert[indices[2]].co;
176
177                         if(iGetNrVerts==4) {
178                                 float *p3= data->mvert[indices[3]].co;
179                                 normal_quad_v3(nor, p0, p1, p2, p3);
180                         } else {
181                                 normal_tri_v3(nor, p0, p1, p2);
182                         }
183
184                         copy_v3_v3(norm, nor);
185                 }
186         } else {
187                 short *no= data->mvert[indices[vert_index]].no;
188
189                 normal_short_to_float_v3(norm, no);
190                 normalize_v3(norm);
191         }
192 }
193
194 static void init_bake_rast(MBakeRast *bake_rast, const ImBuf *ibuf, const MResolvePixelData *data, MFlushPixel flush_pixel)
195 {
196         memset(bake_rast, 0, sizeof(MBakeRast));
197
198         bake_rast->texels = ibuf->userdata;
199         bake_rast->w= ibuf->x;
200         bake_rast->h= ibuf->y;
201         bake_rast->data= data;
202         bake_rast->flush_pixel= flush_pixel;
203 }
204
205 static void flush_pixel(const MResolvePixelData *data, const int x, const int y)
206 {
207         float st[2]= {(x+0.5f)/data->w, (y+0.5f)/data->h};
208         float *st0, *st1, *st2;
209         float *tang0, *tang1, *tang2;
210         float no0[3], no1[3], no2[3];
211         float fUV[2], from_tang[3][3], to_tang[3][3];
212         float u, v, w, sign;
213         int r;
214
215         const int i0= data->i0;
216         const int i1= data->i1;
217         const int i2= data->i2;
218
219         st0= data->mtface[data->face_index].uv[i0];
220         st1= data->mtface[data->face_index].uv[i1];
221         st2= data->mtface[data->face_index].uv[i2];
222
223         tang0= data->pvtangent + data->face_index*16 + i0*4;
224         tang1= data->pvtangent + data->face_index*16 + i1*4;
225         tang2= data->pvtangent + data->face_index*16 + i2*4;
226
227         multiresbake_get_normal(data, no0, data->face_index, i0);       /* can optimize these 3 into one call */
228         multiresbake_get_normal(data, no1, data->face_index, i1);
229         multiresbake_get_normal(data, no2, data->face_index, i2);
230
231         resolve_tri_uv(fUV, st, st0, st1, st2);
232
233         u= fUV[0];
234         v= fUV[1];
235         w= 1-u-v;
236
237         /* the sign is the same at all face vertices for any non degenerate face.
238            Just in case we clamp the interpolated value though. */
239         sign= (tang0[3]*u + tang1[3]*v + tang2[3]*w)<0 ? (-1.0f) : 1.0f;
240
241         /* this sequence of math is designed specifically as is with great care
242            to be compatible with our shader. Please don't change without good reason. */
243         for(r= 0; r<3; r++) {
244                 from_tang[0][r]= tang0[r]*u + tang1[r]*v + tang2[r]*w;
245                 from_tang[2][r]= no0[r]*u + no1[r]*v + no2[r]*w;
246         }
247
248         cross_v3_v3v3(from_tang[1], from_tang[2], from_tang[0]);  /* B = sign * cross(N, T)  */
249         mul_v3_fl(from_tang[1], sign);
250         invert_m3_m3(to_tang, from_tang);
251         /* sequence end */
252
253         data->pass_data(data->lores_dm, data->hires_dm, data->bake_data,
254                         data->face_index, data->lvl, st, to_tang, x, y);
255 }
256
257 static void set_rast_triangle(const MBakeRast *bake_rast, const int x, const int y)
258 {
259         const int w= bake_rast->w;
260         const int h= bake_rast->h;
261
262         if(x>=0 && x<w && y>=0 && y<h) {
263                 if((bake_rast->texels[y*w+x])==0) {
264                         flush_pixel(bake_rast->data, x, y);
265                         bake_rast->texels[y*w+x]= FILTER_MASK_USED;
266                 }
267         }
268 }
269
270 static void rasterize_half(const MBakeRast *bake_rast,
271                            const float s0_s, const float t0_s, const float s1_s, const float t1_s,
272                            const float s0_l, const float t0_l, const float s1_l, const float t1_l,
273                            const int y0_in, const int y1_in, const int is_mid_right)
274 {
275         const int s_stable= fabsf(t1_s-t0_s)>FLT_EPSILON ? 1 : 0;
276         const int l_stable= fabsf(t1_l-t0_l)>FLT_EPSILON ? 1 : 0;
277         const int w= bake_rast->w;
278         const int h= bake_rast->h;
279         int y, y0, y1;
280
281         if(y1_in<=0 || y0_in>=h)
282                 return;
283
284         y0= y0_in<0 ? 0 : y0_in;
285         y1= y1_in>=h ? h : y1_in;
286
287         for(y= y0; y<y1; y++) {
288                 /*-b(x-x0) + a(y-y0) = 0 */
289                 int iXl, iXr, x;
290                 float x_l= s_stable!=0 ? (s0_s + (((s1_s-s0_s)*(y-t0_s))/(t1_s-t0_s))) : s0_s;
291                 float x_r= l_stable!=0 ? (s0_l + (((s1_l-s0_l)*(y-t0_l))/(t1_l-t0_l))) : s0_l;
292
293                 if(is_mid_right!=0)
294                         SWAP(float, x_l, x_r);
295
296                 iXl= (int)ceilf(x_l);
297                 iXr= (int)ceilf(x_r);
298
299                 if(iXr>0 && iXl<w) {
300                         iXl= iXl<0?0:iXl;
301                         iXr= iXr>=w?w:iXr;
302
303                         for(x= iXl; x<iXr; x++)
304                                 set_rast_triangle(bake_rast, x, y);
305                 }
306         }
307 }
308
309 static void bake_rasterize(const MBakeRast *bake_rast, const float st0_in[2], const float st1_in[2], const float st2_in[2])
310 {
311         const int w= bake_rast->w;
312         const int h= bake_rast->h;
313         float slo= st0_in[0]*w - 0.5f;
314         float tlo= st0_in[1]*h - 0.5f;
315         float smi= st1_in[0]*w - 0.5f;
316         float tmi= st1_in[1]*h - 0.5f;
317         float shi= st2_in[0]*w - 0.5f;
318         float thi= st2_in[1]*h - 0.5f;
319         int is_mid_right= 0, ylo, yhi, yhi_beg;
320
321         /* skip degenerates */
322         if((slo==smi && tlo==tmi) || (slo==shi && tlo==thi) || (smi==shi && tmi==thi))
323                 return;
324
325         /* sort by T */
326         if(tlo>tmi && tlo>thi) {
327                 SWAP(float, shi, slo);
328                 SWAP(float, thi, tlo);
329         } else if(tmi>thi) {
330                 SWAP(float, shi, smi);
331                 SWAP(float, thi, tmi);
332         }
333
334         if(tlo>tmi) {
335                 SWAP(float, slo, smi);
336                 SWAP(float, tlo, tmi);
337         }
338
339         /* check if mid point is to the left or to the right of the lo-hi edge */
340         is_mid_right= (-(shi-slo)*(tmi-thi) + (thi-tlo)*(smi-shi))>0 ? 1 : 0;
341         ylo= (int) ceilf(tlo);
342         yhi_beg= (int) ceilf(tmi);
343         yhi= (int) ceilf(thi);
344
345         /*if(fTmi>ceilf(fTlo))*/
346         rasterize_half(bake_rast, slo, tlo, smi, tmi, slo, tlo, shi, thi, ylo, yhi_beg, is_mid_right);
347         rasterize_half(bake_rast, smi, tmi, shi, thi, slo, tlo, shi, thi, yhi_beg, yhi, is_mid_right);
348 }
349
350 static int multiresbake_test_break(MultiresBakeRender *bkr)
351 {
352         if(!bkr->stop) {
353                 /* this means baker is executed outside from job system */
354                 return 0;
355         }
356
357         return G.afbreek;
358 }
359
360 static void do_multires_bake(MultiresBakeRender *bkr, Image* ima, MPassKnownData passKnownData,
361                              MInitBakeData initBakeData, MApplyBakeData applyBakeData, MFreeBakeData freeBakeData)
362 {
363         DerivedMesh *dm= bkr->lores_dm;
364         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
365         const int lvl= bkr->lvl;
366         const int tot_face= dm->getNumFaces(dm);
367         MVert *mvert= dm->getVertArray(dm);
368         MFace *mface= dm->getFaceArray(dm);
369         MTFace *mtface= dm->getFaceDataArray(dm, CD_MTFACE);
370         float *pvtangent= NULL;
371
372         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) == -1)
373                 DM_add_tangent_layer(dm);
374
375         pvtangent= DM_get_face_data_layer(dm, CD_TANGENT);
376
377         if(tot_face > 0) {  /* sanity check */
378                 int f= 0;
379                 MBakeRast bake_rast;
380                 MResolvePixelData data={NULL};
381
382                 data.mface= mface;
383                 data.mvert= mvert;
384                 data.mtface= mtface;
385                 data.pvtangent= pvtangent;
386                 data.precomputed_normals= dm->getFaceDataArray(dm, CD_NORMAL);  /* don't strictly need this */
387                 data.w= ibuf->x;
388                 data.h= ibuf->y;
389                 data.lores_dm= dm;
390                 data.hires_dm= bkr->hires_dm;
391                 data.lvl= lvl;
392                 data.pass_data= passKnownData;
393
394                 if(initBakeData)
395                         data.bake_data= initBakeData(bkr, ima);
396
397                 init_bake_rast(&bake_rast, ibuf, &data, flush_pixel);
398
399                 for(f= 0; f<tot_face; f++) {
400                         MTFace *mtfate= &mtface[f];
401                         int verts[3][2], nr_tris, t;
402
403                         if(multiresbake_test_break(bkr))
404                                 break;
405
406                         if(mtfate->tpage!=ima)
407                                 continue;
408
409                         data.face_index= f;
410
411                         /* might support other forms of diagonal splits later on such as
412                            split by shortest diagonal.*/
413                         verts[0][0]=0;
414                         verts[1][0]=1;
415                         verts[2][0]=2;
416
417                         verts[0][1]=0;
418                         verts[1][1]=2;
419                         verts[2][1]=3;
420
421                         nr_tris= mface[f].v4!=0 ? 2 : 1;
422                         for(t= 0; t<nr_tris; t++) {
423                                 data.i0= verts[0][t];
424                                 data.i1= verts[1][t];
425                                 data.i2 =verts[2][t];
426
427                                 bake_rasterize(&bake_rast, mtfate->uv[data.i0], mtfate->uv[data.i1], mtfate->uv[data.i2]);
428                         }
429
430                         bkr->baked_faces++;
431
432                         if(bkr->do_update)
433                                 *bkr->do_update= 1;
434
435                         if(bkr->progress)
436                                 *bkr->progress= ((float)bkr->baked_objects + (float)bkr->baked_faces / tot_face) / bkr->tot_obj;
437                 }
438
439                 if(applyBakeData)
440                         applyBakeData(data.bake_data);
441
442                 if(freeBakeData)
443                         freeBakeData(data.bake_data);
444         }
445 }
446
447 static void interp_bilinear_quad_data(float data[4][3], float u, float v, float res[3])
448 {
449         float vec[3];
450
451         copy_v3_v3(res, data[0]);
452         mul_v3_fl(res, (1-u)*(1-v));
453         copy_v3_v3(vec, data[1]);
454         mul_v3_fl(vec, u*(1-v)); add_v3_v3(res, vec);
455         copy_v3_v3(vec, data[2]);
456         mul_v3_fl(vec, u*v); add_v3_v3(res, vec);
457         copy_v3_v3(vec, data[3]);
458         mul_v3_fl(vec, (1-u)*v); add_v3_v3(res, vec);
459 }
460
461 static void interp_barycentric_tri_data(float data[3][3], float u, float v, float res[3])
462 {
463         float vec[3];
464
465         copy_v3_v3(res, data[0]);
466         mul_v3_fl(res, u);
467         copy_v3_v3(vec, data[1]);
468         mul_v3_fl(vec, v); add_v3_v3(res, vec);
469         copy_v3_v3(vec, data[2]);
470         mul_v3_fl(vec, 1.0f-u-v); add_v3_v3(res, vec);
471 }
472
473 /* mode = 0: interpolate normals,
474    mode = 1: interpolate coord */
475 static void interp_bilinear_grid(DMGridData *grid, int grid_size, float crn_x, float crn_y, int mode, float res[3])
476 {
477         int x0, x1, y0, y1;
478         float u, v;
479         float data[4][3];
480
481         x0= (int) crn_x;
482         x1= x0>=(grid_size-1) ? (grid_size-1) : (x0+1);
483
484         y0= (int) crn_y;
485         y1= y0>=(grid_size-1) ? (grid_size-1) : (y0+1);
486
487         u= crn_x-x0;
488         v= crn_y-y0;
489
490         if(mode == 0) {
491                 copy_v3_v3(data[0], grid[y0 * grid_size + x0].no);
492                 copy_v3_v3(data[1], grid[y0 * grid_size + x1].no);
493                 copy_v3_v3(data[2], grid[y1 * grid_size + x1].no);
494                 copy_v3_v3(data[3], grid[y1 * grid_size + x0].no);
495         } else {
496                 copy_v3_v3(data[0], grid[y0 * grid_size + x0].co);
497                 copy_v3_v3(data[1], grid[y0 * grid_size + x1].co);
498                 copy_v3_v3(data[2], grid[y1 * grid_size + x1].co);
499                 copy_v3_v3(data[3], grid[y1 * grid_size + x0].co);
500         }
501
502         interp_bilinear_quad_data(data, u, v, res);
503 }
504
505 static void get_ccgdm_data(DerivedMesh *lodm, DerivedMesh *hidm,  const int lvl, const int face_index, const float u, const float v, float co[3], float n[3])
506 {
507         MFace mface;
508         DMGridData **grid_data;
509         float crn_x, crn_y;
510         int grid_size, S, face_side;
511         int *grid_offset, g_index;
512
513         lodm->getFace(lodm, face_index, &mface);
514
515         grid_size= hidm->getGridSize(hidm);
516         grid_data= hidm->getGridData(hidm);
517         grid_offset= hidm->getGridOffset(hidm);
518
519         face_side= (grid_size<<1)-1;
520
521         if(lvl==0) {
522                 g_index= grid_offset[face_index];
523                 S= mdisp_rot_face_to_crn(mface.v4 ? 4 : 3, face_side, u*(face_side-1), v*(face_side-1), &crn_x, &crn_y);
524         } else {
525                 const int *index= lodm->getFaceDataArray(lodm, CD_ORIGINDEX);
526                 int side= (1 << (lvl-1)) + 1;
527                 int grid_index= index[face_index];
528                 int loc_offs= face_index % (1<<(2*lvl));
529                 int cell_index= loc_offs % ((side-1)*(side-1));
530                 int cell_side= grid_size / (side-1);
531                 int row= cell_index / (side-1);
532                 int col= cell_index % (side-1);
533
534                 S= face_index / (1<<(2*(lvl-1))) - grid_offset[grid_index];
535                 g_index= grid_offset[grid_index];
536
537                 crn_y= (row * cell_side) + u * cell_side;
538                 crn_x= (col * cell_side) + v * cell_side;
539         }
540
541         CLAMP(crn_x, 0.0f, grid_size);
542         CLAMP(crn_y, 0.0f, grid_size);
543
544         if(n != NULL)
545                 interp_bilinear_grid(grid_data[g_index + S], grid_size, crn_x, crn_y, 0, n);
546
547         if(co != NULL)
548                 interp_bilinear_grid(grid_data[g_index + S], grid_size, crn_x, crn_y, 1, co);
549 }
550
551 /* mode = 0: interpolate normals,
552    mode = 1: interpolate coord */
553 static void interp_bilinear_mface(DerivedMesh *dm, MFace *mface, const float u, const float v, const int mode, float res[3])
554 {
555         float data[4][3];
556
557         if(mode == 0) {
558                 dm->getVertNo(dm, mface->v1, data[0]);
559                 dm->getVertNo(dm, mface->v2, data[1]);
560                 dm->getVertNo(dm, mface->v3, data[2]);
561                 dm->getVertNo(dm, mface->v4, data[3]);
562         } else {
563                 dm->getVertCo(dm, mface->v1, data[0]);
564                 dm->getVertCo(dm, mface->v2, data[1]);
565                 dm->getVertCo(dm, mface->v3, data[2]);
566                 dm->getVertCo(dm, mface->v4, data[3]);
567         }
568
569         interp_bilinear_quad_data(data, u, v, res);
570 }
571
572 /* mode = 0: interpolate normals,
573    mode = 1: interpolate coord */
574 static void interp_barycentric_mface(DerivedMesh *dm, MFace *mface, const float u, const float v, const int mode, float res[3])
575 {
576         float data[3][3];
577
578         if(mode == 0) {
579                 dm->getVertNo(dm, mface->v1, data[0]);
580                 dm->getVertNo(dm, mface->v2, data[1]);
581                 dm->getVertNo(dm, mface->v3, data[2]);
582         } else {
583                 dm->getVertCo(dm, mface->v1, data[0]);
584                 dm->getVertCo(dm, mface->v2, data[1]);
585                 dm->getVertCo(dm, mface->v3, data[2]);
586         }
587
588         interp_barycentric_tri_data(data, u, v, res);
589 }
590
591 static void *init_heights_data(MultiresBakeRender *bkr, Image* ima)
592 {
593         MHeightBakeData *height_data;
594         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
595
596         height_data= MEM_callocN(sizeof(MHeightBakeData), "MultiresBake heightData");
597
598         height_data->ima= ima;
599         height_data->heights= MEM_callocN(sizeof(float)*ibuf->x*ibuf->y, "MultiresBake heights");
600         height_data->height_max= -FLT_MAX;
601         height_data->height_min= FLT_MAX;
602
603         if(!bkr->use_lores_mesh) {
604                 SubsurfModifierData smd= {{NULL}};
605                 int ss_lvl= bkr->tot_lvl - bkr->lvl;
606
607                 CLAMP(ss_lvl, 0, 6);
608
609                 smd.levels= smd.renderLevels= ss_lvl;
610                 smd.flags|= eSubsurfModifierFlag_SubsurfUv;
611
612                 if(bkr->simple)
613                         smd.subdivType= ME_SIMPLE_SUBSURF;
614
615                 height_data->ssdm= subsurf_make_derived_from_derived(bkr->lores_dm, &smd, 0, NULL, 0, 0, 0);
616         }
617
618         return (void*)height_data;
619 }
620
621 static void apply_heights_data(void *bake_data)
622 {
623         MHeightBakeData *height_data= (MHeightBakeData*)bake_data;
624         ImBuf *ibuf= BKE_image_get_ibuf(height_data->ima, NULL);
625         int x, y, i;
626         float height, *heights= height_data->heights;
627         float min= height_data->height_min, max= height_data->height_max;
628
629         for(x= 0; x<ibuf->x; x++) {
630                 for(y =0; y<ibuf->y; y++) {
631                         i= ibuf->x*y + x;
632
633                         if(((char*)ibuf->userdata)[i] != FILTER_MASK_USED)
634                                 continue;
635
636                         if(ibuf->rect_float) {
637                                 float *rrgbf= ibuf->rect_float + i*4;
638
639                                 if(max-min > 1e-5f) height= (heights[i]-min)/(max-min);
640                                 else height= 0;
641
642                                 rrgbf[0]=rrgbf[1]=rrgbf[2]= height;
643                         } else {
644                                 char *rrgb= (char*)ibuf->rect + i*4;
645
646                                 if(max-min > 1e-5f) height= (heights[i]-min)/(max-min);
647                                 else height= 0;
648
649                                 rrgb[0]=rrgb[1]=rrgb[2]= FTOCHAR(height);
650                         }
651                 }
652         }
653
654         ibuf->userflags= IB_RECT_INVALID;
655 }
656
657 static void free_heights_data(void *bake_data)
658 {
659         MHeightBakeData *height_data= (MHeightBakeData*)bake_data;
660
661         if(height_data->ssdm)
662                 height_data->ssdm->release(height_data->ssdm);
663
664         MEM_freeN(height_data->heights);
665         MEM_freeN(height_data);
666 }
667
668 /* MultiresBake callback for heights baking
669    general idea:
670      - find coord of point with specified UV in hi-res mesh (let's call it p1)
671      - find coord of point and normal with specified UV in lo-res mesh (or subdivided lo-res
672        mesh to make texture smoother) let's call this point p0 and n.
673      - height wound be dot(n, p1-p0) */
674 static void apply_heights_callback(DerivedMesh *lores_dm, DerivedMesh *hires_dm, const void *bake_data,
675                                    const int face_index, const int lvl, const float st[2],
676                                    float UNUSED(tangmat[3][3]), const int x, const int y)
677 {
678         MTFace *mtface= CustomData_get_layer(&lores_dm->faceData, CD_MTFACE);
679         MFace mface;
680         Image *ima= mtface[face_index].tpage;
681         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
682         MHeightBakeData *height_data= (MHeightBakeData*)bake_data;
683         float uv[2], *st0, *st1, *st2, *st3;
684         int pixel= ibuf->x*y + x;
685         float vec[3], p0[3], p1[3], n[3], len;
686
687         lores_dm->getFace(lores_dm, face_index, &mface);
688
689         st0= mtface[face_index].uv[0];
690         st1= mtface[face_index].uv[1];
691         st2= mtface[face_index].uv[2];
692
693         if(mface.v4) {
694                 st3= mtface[face_index].uv[3];
695                 resolve_quad_uv(uv, st, st0, st1, st2, st3);
696         } else
697                 resolve_tri_uv(uv, st, st0, st1, st2);
698
699         CLAMP(uv[0], 0.0f, 1.0f);
700         CLAMP(uv[1], 0.0f, 1.0f);
701
702         get_ccgdm_data(lores_dm, hires_dm, lvl, face_index, uv[0], uv[1], p1, 0);
703
704         if(height_data->ssdm) {
705                 //get_ccgdm_data_ss(lores_dm, height_data->ssdm, lvl, face_index, uv[0], uv[1], p0, n);
706                 get_ccgdm_data(lores_dm, height_data->ssdm, 0, face_index, uv[0], uv[1], p0, n);
707         } else {
708                 MFace mface;
709                 lores_dm->getFace(lores_dm, face_index, &mface);
710
711                 if(mface.v4) {
712                         interp_bilinear_mface(lores_dm, &mface, uv[0], uv[1], 1, p0);
713                         interp_bilinear_mface(lores_dm, &mface, uv[0], uv[1], 0, n);
714                 } else {
715                         interp_barycentric_mface(lores_dm, &mface, uv[0], uv[1], 1, p0);
716                         interp_barycentric_mface(lores_dm, &mface, uv[0], uv[1], 0, n);
717                 }
718         }
719
720         sub_v3_v3v3(vec, p1, p0);
721         //len= len_v3(vec);
722         len= dot_v3v3(n, vec);
723
724         height_data->heights[pixel]= len;
725         if(len<height_data->height_min) height_data->height_min= len;
726         if(len>height_data->height_max) height_data->height_max= len;
727
728         if(ibuf->rect_float) {
729                 float *rrgbf= ibuf->rect_float + pixel*4;
730                 rrgbf[3]= 1.0f;
731
732                 ibuf->userflags= IB_RECT_INVALID;
733         } else {
734                 char *rrgb= (char*)ibuf->rect + pixel*4;
735                 rrgb[3]= 255;
736         }
737 }
738
739 /* MultiresBake callback for normals' baking
740    general idea:
741      - find coord and normal of point with specified UV in hi-res mesh
742      - multiply it by tangmat
743      - vector in color space would be norm(vec) /2 + (0.5, 0.5, 0.5) */
744 static void apply_tangmat_callback(DerivedMesh *lores_dm, DerivedMesh *hires_dm, const void *UNUSED(bake_data),
745                                    const int face_index, const int lvl, const float st[2],
746                                    float tangmat[3][3], const int x, const int y)
747 {
748         MTFace *mtface= CustomData_get_layer(&lores_dm->faceData, CD_MTFACE);
749         MFace mface;
750         Image *ima= mtface[face_index].tpage;
751         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
752         float uv[2], *st0, *st1, *st2, *st3;
753         int pixel= ibuf->x*y + x;
754         float n[3], vec[3], tmp[3]= {0.5, 0.5, 0.5};
755
756         lores_dm->getFace(lores_dm, face_index, &mface);
757
758         st0= mtface[face_index].uv[0];
759         st1= mtface[face_index].uv[1];
760         st2= mtface[face_index].uv[2];
761
762         if(mface.v4) {
763                 st3= mtface[face_index].uv[3];
764                 resolve_quad_uv(uv, st, st0, st1, st2, st3);
765         } else
766                 resolve_tri_uv(uv, st, st0, st1, st2);
767
768         CLAMP(uv[0], 0.0f, 1.0f);
769         CLAMP(uv[1], 0.0f, 1.0f);
770
771         get_ccgdm_data(lores_dm, hires_dm, lvl, face_index, uv[0], uv[1], NULL, n);
772
773         mul_v3_m3v3(vec, tangmat, n);
774         normalize_v3(vec);
775         mul_v3_fl(vec, 0.5);
776         add_v3_v3(vec, tmp);
777
778         if(ibuf->rect_float) {
779                 float *rrgbf= ibuf->rect_float + pixel*4;
780                 rrgbf[0]= vec[0];
781                 rrgbf[1]= vec[1];
782                 rrgbf[2]= vec[2];
783                 rrgbf[3]= 1.0f;
784
785                 ibuf->userflags= IB_RECT_INVALID;
786         } else {
787                 char *rrgb= (char*)ibuf->rect + pixel*4;
788                 rrgb[0]= FTOCHAR(vec[0]);
789                 rrgb[1]= FTOCHAR(vec[1]);
790                 rrgb[2]= FTOCHAR(vec[2]);
791                 rrgb[3]= 255;
792         }
793 }
794
795 static void count_images(MultiresBakeRender *bkr)
796 {
797         int a, totface;
798         DerivedMesh *dm= bkr->lores_dm;
799         MTFace *mtface= CustomData_get_layer(&dm->faceData, CD_MTFACE);
800
801         bkr->image.first= bkr->image.last= NULL;
802         bkr->tot_image= 0;
803
804         totface= dm->getNumFaces(dm);
805
806         for(a= 0; a<totface; a++)
807                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
808
809         for(a= 0; a<totface; a++) {
810                 Image *ima= mtface[a].tpage;
811                 if((ima->id.flag&LIB_DOIT)==0) {
812                         LinkData *data= BLI_genericNodeN(ima);
813                         BLI_addtail(&bkr->image, data);
814                         bkr->tot_image++;
815                         ima->id.flag|= LIB_DOIT;
816                 }
817         }
818
819         for(a= 0; a<totface; a++)
820                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
821 }
822
823 static void bake_images(MultiresBakeRender *bkr)
824 {
825         LinkData *link;
826
827         for(link= bkr->image.first; link; link= link->next) {
828                 Image *ima= (Image*)link->data;
829                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
830
831                 if(ibuf->x>0 && ibuf->y>0) {
832                         ibuf->userdata= MEM_callocN(ibuf->y*ibuf->x, "MultiresBake imbuf mask");
833
834                         switch(bkr->mode) {
835                                 case RE_BAKE_NORMALS:
836                                         do_multires_bake(bkr, ima, apply_tangmat_callback, NULL, NULL, NULL);
837                                         break;
838                                 case RE_BAKE_DISPLACEMENT:
839                                         do_multires_bake(bkr, ima, apply_heights_callback, init_heights_data,
840                                                          apply_heights_data, free_heights_data);
841                                         break;
842                         }
843                 }
844
845                 ima->id.flag|= LIB_DOIT;
846         }
847 }
848
849 static void finish_images(MultiresBakeRender *bkr)
850 {
851         LinkData *link;
852
853         for(link= bkr->image.first; link; link= link->next) {
854                 Image *ima= (Image*)link->data;
855                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
856
857                 if(ibuf->x<=0 || ibuf->y<=0)
858                         continue;
859
860                 RE_bake_ibuf_filter(ibuf, (char *)ibuf->userdata, bkr->bake_filter);
861
862                 ibuf->userflags|= IB_BITMAPDIRTY;
863
864                 if(ibuf->rect_float)
865                         ibuf->userflags|= IB_RECT_INVALID;
866
867                 if(ibuf->mipmap[0]) {
868                         ibuf->userflags|= IB_MIPMAP_INVALID;
869                         imb_freemipmapImBuf(ibuf);
870                 }
871
872                 if(ibuf->userdata) {
873                         MEM_freeN(ibuf->userdata);
874                         ibuf->userdata= NULL;
875                 }
876         }
877 }
878
879 static void multiresbake_start(MultiresBakeRender *bkr)
880 {
881         count_images(bkr);
882         bake_images(bkr);
883         finish_images(bkr);
884 }
885
886 static int multiresbake_check(bContext *C, wmOperator *op)
887 {
888         Scene *scene= CTX_data_scene(C);
889         Object *ob;
890         Mesh *me;
891         MultiresModifierData *mmd;
892         int ok= 1, a;
893
894         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
895                 ob= base->object;
896
897                 if(ob->type != OB_MESH) {
898                         BKE_report(op->reports, RPT_ERROR, "Basking of multires data only works with active object which is a mesh");
899
900                         ok= 0;
901                         break;
902                 }
903
904                 me= (Mesh*)ob->data;
905                 mmd= get_multires_modifier(scene, ob, 0);
906
907                 /* Multi-resolution should be and be last in the stack */
908                 if(ok && mmd) {
909                         ModifierData *md;
910
911                         ok= mmd->totlvl>0;
912
913                         for(md = (ModifierData*)mmd->modifier.next; md && ok; md = md->next) {
914                                 if (modifier_isEnabled(scene, md, eModifierMode_Realtime)) {
915                                         ok= 0;
916                                 }
917                         }
918                 } else ok= 0;
919
920                 if(!ok) {
921                         BKE_report(op->reports, RPT_ERROR, "Multires data baking requires multi-resolution object");
922
923                         break;
924                 }
925
926                 if(!me->mtface) {
927                         BKE_report(op->reports, RPT_ERROR, "Mesh should be unwrapped before multires data baking");
928
929                         ok= 0;
930                 } else {
931                         a= me->totface;
932                         while (ok && a--) {
933                                 Image *ima= me->mtface[a].tpage;
934
935                                 if(!ima) {
936                                         BKE_report(op->reports, RPT_ERROR, "You should have active texture to use multires baker");
937
938                                         ok= 0;
939                                 } else {
940                                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
941
942                                         if(!ibuf) {
943                                                 BKE_report(op->reports, RPT_ERROR, "Baking should happend to image with image buffer");
944
945                                                 ok= 0;
946                                         } else {
947                                                 if(ibuf->rect==NULL && ibuf->rect_float==NULL)
948                                                         ok= 0;
949
950                                                 if(ibuf->rect_float && !(ibuf->channels==0 || ibuf->channels==4))
951                                                         ok= 0;
952
953                                                 if(!ok)
954                                                         BKE_report(op->reports, RPT_ERROR, "Baking to unsupported image type");
955                                         }
956                                 }
957                         }
958                 }
959
960                 if(!ok)
961                         break;
962         }
963         CTX_DATA_END;
964
965         return ok;
966 }
967
968 static DerivedMesh *multiresbake_create_loresdm(Scene *scene, Object *ob, int *lvl)
969 {
970         DerivedMesh *dm;
971         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
972         Mesh *me= (Mesh*)ob->data;
973
974         if(ob->mode==OB_MODE_SCULPT) *lvl= mmd->sculptlvl;
975         else *lvl= mmd->lvl;
976
977         if(*lvl==0) {
978                 DerivedMesh *tmp_dm= CDDM_from_mesh(me, ob);
979                 dm= CDDM_copy(tmp_dm);
980                 tmp_dm->release(tmp_dm);
981         } else {
982                 MultiresModifierData tmp_mmd= *mmd;
983                 DerivedMesh *cddm= CDDM_from_mesh(me, ob);
984
985                 tmp_mmd.lvl= *lvl;
986                 dm= multires_dm_create_from_derived(&tmp_mmd, 1, cddm, ob, 0, 0);
987                 cddm->release(cddm);
988         }
989
990         return dm;
991 }
992
993 static DerivedMesh *multiresbake_create_hiresdm(Scene *scene, Object *ob, int *lvl, int *simple)
994 {
995         Mesh *me= (Mesh*)ob->data;
996         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
997         MultiresModifierData tmp_mmd= *mmd;
998         DerivedMesh *cddm= CDDM_from_mesh(me, ob);
999         DerivedMesh *dm;
1000
1001         *lvl= mmd->totlvl;
1002         *simple= mmd->simple;
1003
1004         tmp_mmd.lvl= mmd->totlvl;
1005         dm= multires_dm_create_from_derived(&tmp_mmd, 1, cddm, ob, 0, 0);
1006         cddm->release(cddm);
1007
1008         return dm;
1009 }
1010
1011 static void clear_images(MTFace *mtface, int totface)
1012 {
1013         int a;
1014         const float vec_alpha[4]= {0.0f, 0.0f, 0.0f, 0.0f};
1015         const float vec_solid[4]= {0.0f, 0.0f, 0.0f, 1.0f};
1016
1017         for(a= 0; a<totface; a++)
1018                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
1019
1020         for(a= 0; a<totface; a++) {
1021                 Image *ima= mtface[a].tpage;
1022
1023                 if((ima->id.flag&LIB_DOIT)==0) {
1024                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1025
1026                         IMB_rectfill(ibuf, (ibuf->depth == 32) ? vec_alpha : vec_solid);
1027                         ima->id.flag|= LIB_DOIT;
1028                 }
1029         }
1030
1031         for(a= 0; a<totface; a++)
1032                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
1033 }
1034
1035 static int multiresbake_image_exec_locked(bContext *C, wmOperator *op)
1036 {
1037         Object *ob;
1038         Scene *scene= CTX_data_scene(C);
1039
1040         if(!multiresbake_check(C, op))
1041                 return OPERATOR_CANCELLED;
1042
1043         if(scene->r.bake_flag&R_BAKE_CLEAR) {  /* clear images */
1044                 CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
1045                         Mesh *me;
1046
1047                         ob= base->object;
1048                         me= (Mesh*)ob->data;
1049
1050                         clear_images(me->mtface, me->totface);
1051                 }
1052                 CTX_DATA_END;
1053         }
1054
1055         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
1056                 MultiresBakeRender bkr= {0};
1057
1058                 ob= base->object;
1059
1060                 /* copy data stored in job descriptor */
1061                 bkr.bake_filter= scene->r.bake_filter;
1062                 bkr.mode= scene->r.bake_mode;
1063                 bkr.use_lores_mesh= scene->r.bake_flag&R_BAKE_LORES_MESH;
1064
1065                 /* create low-resolution DM (to bake to) and hi-resolution DM (to bake from) */
1066                 bkr.lores_dm= multiresbake_create_loresdm(scene, ob, &bkr.lvl);
1067                 bkr.hires_dm= multiresbake_create_hiresdm(scene, ob, &bkr.tot_lvl, &bkr.simple);
1068
1069                 multiresbake_start(&bkr);
1070
1071                 BLI_freelistN(&bkr.image);
1072
1073                 bkr.lores_dm->release(bkr.lores_dm);
1074                 bkr.hires_dm->release(bkr.hires_dm);
1075         }
1076         CTX_DATA_END;
1077
1078         return OPERATOR_FINISHED;
1079 }
1080
1081 /* Multiresbake adopted for job-system executing */
1082 static void init_multiresbake_job(bContext *C, MultiresBakeJob *bkj)
1083 {
1084         Scene *scene= CTX_data_scene(C);
1085         Object *ob;
1086
1087         /* backup scene settings, so their changing in UI would take no effect on baker */
1088         bkj->bake_filter= scene->r.bake_filter;
1089         bkj->mode= scene->r.bake_mode;
1090         bkj->use_lores_mesh= scene->r.bake_flag&R_BAKE_LORES_MESH;
1091         bkj->bake_clear= scene->r.bake_flag&R_BAKE_CLEAR;
1092
1093         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
1094                 MultiresBakerJobData *data;
1095                 ob= base->object;
1096
1097                 data= MEM_callocN(sizeof(MultiresBakerJobData), "multiresBaker derivedMesh_data");
1098                 data->lores_dm = multiresbake_create_loresdm(scene, ob, &data->lvl);
1099                 data->hires_dm = multiresbake_create_hiresdm(scene, ob, &data->tot_lvl, &data->simple);
1100                 BLI_addtail(&bkj->data, data);
1101         }
1102         CTX_DATA_END;
1103 }
1104
1105 static void multiresbake_startjob(void *bkv, short *stop, short *do_update, float *progress)
1106 {
1107         MultiresBakerJobData *data;
1108         MultiresBakeJob *bkj= bkv;
1109         int baked_objects= 0, tot_obj;
1110
1111         tot_obj= BLI_countlist(&bkj->data);
1112
1113         if(bkj->bake_clear) {  /* clear images */
1114                 for(data= bkj->data.first; data; data= data->next) {
1115                         DerivedMesh *dm= data->lores_dm;
1116                         MTFace *mtface= CustomData_get_layer(&dm->faceData, CD_MTFACE);
1117
1118                         clear_images(mtface, dm->getNumFaces(dm));
1119                 }
1120         }
1121
1122         for(data= bkj->data.first; data; data= data->next) {
1123                 MultiresBakeRender bkr= {0};
1124
1125                 /* copy data stored in job descriptor */
1126                 bkr.bake_filter= bkj->bake_filter;
1127                 bkr.mode= bkj->mode;
1128                 bkr.use_lores_mesh= bkj->use_lores_mesh;
1129
1130                 /* create low-resolution DM (to bake to) and hi-resolution DM (to bake from) */
1131                 bkr.lores_dm= data->lores_dm;
1132                 bkr.hires_dm= data->hires_dm;
1133                 bkr.tot_lvl= data->tot_lvl;
1134                 bkr.lvl= data->lvl;
1135                 bkr.simple= data->simple;
1136
1137                 /* needed for proper progress bar */
1138                 bkr.tot_obj= tot_obj;
1139                 bkr.baked_objects= baked_objects;
1140
1141                 bkr.stop= stop;
1142                 bkr.do_update= do_update;
1143                 bkr.progress= progress;
1144
1145                 multiresbake_start(&bkr);
1146
1147                 BLI_freelistN(&bkr.image);
1148
1149                 baked_objects++;
1150         }
1151 }
1152
1153 static void multiresbake_freejob(void *bkv)
1154 {
1155         MultiresBakeJob *bkj= bkv;
1156         MultiresBakerJobData *data, *next;
1157
1158         data= bkj->data.first;
1159         while (data) {
1160                 next= data->next;
1161                 data->lores_dm->release(data->lores_dm);
1162                 data->hires_dm->release(data->hires_dm);
1163                 MEM_freeN(data);
1164                 data= next;
1165         }
1166
1167         MEM_freeN(bkj);
1168 }
1169
1170 static int multiresbake_image_exec(bContext *C, wmOperator *op)
1171 {
1172         Scene *scene= CTX_data_scene(C);
1173         MultiresBakeJob *bkr;
1174         wmJob *steve;
1175
1176         if(!multiresbake_check(C, op))
1177                 return OPERATOR_CANCELLED;
1178
1179         bkr= MEM_callocN(sizeof(MultiresBakeJob), "MultiresBakeJob data");
1180         init_multiresbake_job(C, bkr);
1181
1182         /* setup job */
1183         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Multires Bake", WM_JOB_EXCL_RENDER|WM_JOB_PRIORITY|WM_JOB_PROGRESS);
1184         WM_jobs_customdata(steve, bkr, multiresbake_freejob);
1185         WM_jobs_timer(steve, 0.2, NC_IMAGE, 0); /* TODO - only draw bake image, can we enforce this */
1186         WM_jobs_callbacks(steve, multiresbake_startjob, NULL, NULL, NULL);
1187
1188         G.afbreek= 0;
1189
1190         WM_jobs_start(CTX_wm_manager(C), steve);
1191         WM_cursor_wait(0);
1192
1193         /* add modal handler for ESC */
1194         WM_event_add_modal_handler(C, op);
1195
1196         return OPERATOR_RUNNING_MODAL;
1197 }
1198
1199 /* ****************** render BAKING ********************** */
1200
1201 /* threaded break test */
1202 static int thread_break(void *UNUSED(arg))
1203 {
1204         return G.afbreek;
1205 }
1206
1207 static ScrArea *biggest_image_area(bScreen *screen)
1208 {
1209         ScrArea *sa, *big= NULL;
1210         int size, maxsize= 0;
1211
1212         for(sa= screen->areabase.first; sa; sa= sa->next) {
1213                 if(sa->spacetype==SPACE_IMAGE) {
1214                         size= sa->winx*sa->winy;
1215                         if(sa->winx > 10 && sa->winy > 10 && size > maxsize) {
1216                                 maxsize= size;
1217                                 big= sa;
1218                         }
1219                 }
1220         }
1221         return big;
1222 }
1223
1224
1225 typedef struct BakeRender {
1226         Render *re;
1227         Main *main;
1228         Scene *scene;
1229         struct Object *actob;
1230         int tot, ready;
1231
1232         ReportList *reports;
1233
1234         short *stop;
1235         short *do_update;
1236         float *progress;
1237         
1238         ListBase threads;
1239
1240         /* backup */
1241         short prev_wo_amb_occ;
1242         short prev_r_raytrace;
1243
1244         /* for redrawing */
1245         ScrArea *sa;
1246 } BakeRender;
1247
1248 /* use by exec and invoke */
1249 static int test_bake_internal(bContext *C, ReportList *reports)
1250 {
1251         Scene *scene= CTX_data_scene(C);
1252
1253         if(scene->r.renderer!=R_INTERN) {
1254                 BKE_report(reports, RPT_ERROR, "Bake only supported for Internal Renderer");
1255         } else if((scene->r.bake_flag & R_BAKE_TO_ACTIVE) && CTX_data_active_object(C)==NULL) {
1256                 BKE_report(reports, RPT_ERROR, "No active object");
1257         }
1258         else if(scene->r.bake_mode==RE_BAKE_AO && scene->world==NULL) {
1259                 BKE_report(reports, RPT_ERROR, "No world set up");
1260         }
1261         else {
1262                 return 1;
1263         }
1264
1265         return 0;
1266 }
1267
1268 static void init_bake_internal(BakeRender *bkr, bContext *C)
1269 {
1270         Scene *scene= CTX_data_scene(C);
1271
1272         /* get editmode results */
1273         ED_object_exit_editmode(C, 0);  /* 0 = does not exit editmode */
1274
1275         bkr->sa= biggest_image_area(CTX_wm_screen(C)); /* can be NULL */
1276         bkr->main= CTX_data_main(C);
1277         bkr->scene= scene;
1278         bkr->actob= (scene->r.bake_flag & R_BAKE_TO_ACTIVE) ? OBACT : NULL;
1279         bkr->re= RE_NewRender("_Bake View_");
1280
1281         if(scene->r.bake_mode==RE_BAKE_AO) {
1282                 /* If raytracing or AO is disabled, switch it on temporarily for baking. */
1283                 bkr->prev_wo_amb_occ = (scene->world->mode & WO_AMB_OCC) != 0;
1284                 scene->world->mode |= WO_AMB_OCC;
1285         }
1286         if(scene->r.bake_mode==RE_BAKE_AO || bkr->actob) {
1287                 bkr->prev_r_raytrace = (scene->r.mode & R_RAYTRACE) != 0;
1288                 scene->r.mode |= R_RAYTRACE;
1289         }
1290 }
1291
1292 static void finish_bake_internal(BakeRender *bkr)
1293 {
1294         RE_Database_Free(bkr->re);
1295
1296         /* restore raytrace and AO */
1297         if(bkr->scene->r.bake_mode==RE_BAKE_AO)
1298                 if(bkr->prev_wo_amb_occ == 0)
1299                         bkr->scene->world->mode &= ~WO_AMB_OCC;
1300
1301         if(bkr->scene->r.bake_mode==RE_BAKE_AO || bkr->actob)
1302                 if(bkr->prev_r_raytrace == 0)
1303                         bkr->scene->r.mode &= ~R_RAYTRACE;
1304
1305         if(bkr->tot) {
1306                 Image *ima;
1307                 /* force OpenGL reload and mipmap recalc */
1308                 for(ima= G.main->image.first; ima; ima= ima->id.next) {
1309                         if(ima->ok==IMA_OK_LOADED) {
1310                                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1311                                 if(ibuf) {
1312                                         if(ibuf->userflags & IB_BITMAPDIRTY) {
1313                                                 GPU_free_image(ima);
1314                                                 imb_freemipmapImBuf(ibuf);
1315                                         }
1316
1317                                         /* freed when baking is done, but if its canceled we need to free here */
1318                                         if (ibuf->userdata) {
1319                                                 MEM_freeN(ibuf->userdata);
1320                                                 ibuf->userdata= NULL;
1321                                         }
1322                                 }
1323                         }
1324                 }
1325         }
1326 }
1327
1328 static void *do_bake_render(void *bake_v)
1329 {
1330         BakeRender *bkr= bake_v;
1331
1332         bkr->tot= RE_bake_shade_all_selected(bkr->re, bkr->scene->r.bake_mode, bkr->actob, NULL, bkr->progress);
1333         bkr->ready= 1;
1334
1335         return NULL;
1336 }
1337
1338 static void bake_startjob(void *bkv, short *stop, short *do_update, float *progress)
1339 {
1340         BakeRender *bkr= bkv;
1341         Scene *scene= bkr->scene;
1342         Main *bmain= bkr->main;
1343
1344         bkr->stop= stop;
1345         bkr->do_update= do_update;
1346         bkr->progress= progress;
1347
1348         RE_test_break_cb(bkr->re, NULL, thread_break);
1349         G.afbreek= 0;   /* blender_test_break uses this global */
1350
1351         RE_Database_Baking(bkr->re, bmain, scene, scene->lay, scene->r.bake_mode, bkr->actob);
1352
1353         /* baking itself is threaded, cannot use test_break in threads. we also update optional imagewindow */
1354         bkr->tot= RE_bake_shade_all_selected(bkr->re, scene->r.bake_mode, bkr->actob, bkr->do_update, bkr->progress);
1355 }
1356
1357 static void bake_update(void *bkv)
1358 {
1359         BakeRender *bkr= bkv;
1360
1361         if(bkr->sa && bkr->sa->spacetype==SPACE_IMAGE) { /* incase the user changed while baking */
1362                 SpaceImage *sima= bkr->sa->spacedata.first;
1363                 if(sima)
1364                         sima->image= RE_bake_shade_get_image();
1365         }
1366 }
1367
1368 static void bake_freejob(void *bkv)
1369 {
1370         BakeRender *bkr= bkv;
1371         finish_bake_internal(bkr);
1372
1373         if(bkr->tot==0) BKE_report(bkr->reports, RPT_ERROR, "No objects or images found to bake to");
1374         MEM_freeN(bkr);
1375         G.rendering = 0;
1376 }
1377
1378 /* catch esc */
1379 static int objects_bake_render_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1380 {
1381         /* no running blender, remove handler and pass through */
1382         if(0==WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C)))
1383                 return OPERATOR_FINISHED|OPERATOR_PASS_THROUGH;
1384
1385         /* running render */
1386         switch (event->type) {
1387                 case ESCKEY:
1388                         return OPERATOR_RUNNING_MODAL;
1389                         break;
1390         }
1391         return OPERATOR_PASS_THROUGH;
1392 }
1393
1394 static int is_multires_bake(Scene *scene)
1395 {
1396         if ( ELEM(scene->r.bake_mode, RE_BAKE_NORMALS, RE_BAKE_DISPLACEMENT))
1397                 return scene->r.bake_flag & R_BAKE_MULTIRES;
1398
1399         return 0;
1400 }
1401
1402 static int objects_bake_render_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(_event))
1403 {
1404         Scene *scene= CTX_data_scene(C);
1405         int result= OPERATOR_CANCELLED;
1406
1407         if(is_multires_bake(scene)) {
1408                 result= multiresbake_image_exec(C, op);
1409         } else {
1410                 /* only one render job at a time */
1411                 if(WM_jobs_test(CTX_wm_manager(C), scene))
1412                         return OPERATOR_CANCELLED;
1413
1414                 if(test_bake_internal(C, op->reports)==0) {
1415                         return OPERATOR_CANCELLED;
1416                 }
1417                 else {
1418                         BakeRender *bkr= MEM_callocN(sizeof(BakeRender), "render bake");
1419                         wmJob *steve;
1420
1421                         init_bake_internal(bkr, C);
1422                         bkr->reports= op->reports;
1423
1424                         /* setup job */
1425                         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Texture Bake", WM_JOB_EXCL_RENDER|WM_JOB_PRIORITY|WM_JOB_PROGRESS);
1426                         WM_jobs_customdata(steve, bkr, bake_freejob);
1427                         WM_jobs_timer(steve, 0.2, NC_IMAGE, 0); /* TODO - only draw bake image, can we enforce this */
1428                         WM_jobs_callbacks(steve, bake_startjob, NULL, bake_update, NULL);
1429
1430                         G.afbreek= 0;
1431                         G.rendering = 1;
1432
1433                         WM_jobs_start(CTX_wm_manager(C), steve);
1434
1435                         WM_cursor_wait(0);
1436
1437                         /* add modal handler for ESC */
1438                         WM_event_add_modal_handler(C, op);
1439                 }
1440
1441                 result= OPERATOR_RUNNING_MODAL;
1442         }
1443
1444         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
1445
1446         return result;
1447 }
1448
1449
1450 static int bake_image_exec(bContext *C, wmOperator *op)
1451 {
1452         Main *bmain= CTX_data_main(C);
1453         Scene *scene= CTX_data_scene(C);
1454         int result= OPERATOR_CANCELLED;
1455
1456         if(is_multires_bake(scene)) {
1457                 result= multiresbake_image_exec_locked(C, op);
1458         } else  {
1459                 if(test_bake_internal(C, op->reports)==0) {
1460                         return OPERATOR_CANCELLED;
1461                 }
1462                 else {
1463                         ListBase threads;
1464                         BakeRender bkr= {NULL};
1465
1466                         init_bake_internal(&bkr, C);
1467                         bkr.reports= op->reports;
1468
1469                         RE_test_break_cb(bkr.re, NULL, thread_break);
1470                         G.afbreek= 0;   /* blender_test_break uses this global */
1471
1472                         RE_Database_Baking(bkr.re, bmain, scene, scene->lay, scene->r.bake_mode, (scene->r.bake_flag & R_BAKE_TO_ACTIVE)? OBACT: NULL);
1473
1474                         /* baking itself is threaded, cannot use test_break in threads  */
1475                         BLI_init_threads(&threads, do_bake_render, 1);
1476                         bkr.ready= 0;
1477                         BLI_insert_thread(&threads, &bkr);
1478
1479                         while(bkr.ready==0) {
1480                                 PIL_sleep_ms(50);
1481                                 if(bkr.ready)
1482                                         break;
1483
1484                                 /* used to redraw in 2.4x but this is just for exec in 2.5 */
1485                                 if (!G.background)
1486                                         blender_test_break();
1487                         }
1488                         BLI_end_threads(&threads);
1489
1490                         if(bkr.tot==0) BKE_report(op->reports, RPT_ERROR, "No valid images found to bake to");
1491
1492                         finish_bake_internal(&bkr);
1493
1494                         result= OPERATOR_FINISHED;
1495                 }
1496         }
1497
1498         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
1499
1500         return result;
1501 }
1502
1503 void OBJECT_OT_bake_image(wmOperatorType *ot)
1504 {
1505         /* identifiers */
1506         ot->name= "Bake";
1507         ot->description= "Bake image textures of selected objects";
1508         ot->idname= "OBJECT_OT_bake_image";
1509
1510         /* api callbacks */
1511         ot->exec= bake_image_exec;
1512         ot->invoke= objects_bake_render_invoke;
1513         ot->modal= objects_bake_render_modal;
1514 }