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