a680230fb324308247ec25872e03b3f3f0ff7098
[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 #include <string.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_scene_types.h"
38 #include "DNA_screen_types.h"
39 #include "DNA_space_types.h"
40 #include "DNA_world_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44
45 #include "BLI_blenlib.h"
46 #include "BLI_threads.h"
47 #include "BLI_utildefines.h"
48 #include "BLI_math.h"
49 #include "BLI_math_geom.h"
50
51 #include "BKE_blender.h"
52 #include "BKE_ccg.h"
53 #include "BKE_screen.h"
54 #include "BKE_context.h"
55 #include "BKE_global.h"
56 #include "BKE_image.h"
57 #include "BKE_main.h"
58 #include "BKE_multires.h"
59 #include "BKE_report.h"
60 #include "BKE_cdderivedmesh.h"
61 #include "BKE_modifier.h"
62 #include "BKE_DerivedMesh.h"
63 #include "BKE_subsurf.h"
64
65 #include "RE_pipeline.h"
66 #include "RE_shader_ext.h"
67 #include "RE_multires_bake.h"
68
69 #include "PIL_time.h"
70
71 #include "IMB_imbuf_types.h"
72 #include "IMB_imbuf.h"
73 #include "IMB_colormanagement.h"
74
75 #include "GPU_draw.h" /* GPU_free_image */
76
77 #include "WM_api.h"
78 #include "WM_types.h"
79
80 #include "ED_object.h"
81
82 #include "object_intern.h"
83
84 /* ****************** multires BAKING ********************** */
85
86 /* holder of per-object data needed for bake job
87  * needed to make job totally thread-safe */
88 typedef struct MultiresBakerJobData {
89         struct MultiresBakerJobData *next, *prev;
90         DerivedMesh *lores_dm, *hires_dm;
91         int simple, lvl, tot_lvl;
92         ListBase images;
93 } MultiresBakerJobData;
94
95 /* data passing to multires-baker job */
96 typedef struct {
97         ListBase data;
98         int bake_clear, bake_filter;
99         short mode, use_lores_mesh;
100         int number_of_rays;
101         float bias;
102         int raytrace_structure;
103         int octree_resolution;
104         int threads;
105 } MultiresBakeJob;
106
107 static int multiresbake_check(bContext *C, wmOperator *op)
108 {
109         Scene *scene = CTX_data_scene(C);
110         Object *ob;
111         Mesh *me;
112         MultiresModifierData *mmd;
113         int ok = 1, a;
114
115         CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
116         {
117                 ob = base->object;
118
119                 if (ob->type != OB_MESH) {
120                         BKE_report(op->reports, RPT_ERROR, "Baking of multires data only works with an active mesh object");
121
122                         ok = 0;
123                         break;
124                 }
125
126                 me = (Mesh *)ob->data;
127                 mmd = get_multires_modifier(scene, ob, 0);
128
129                 /* Multi-resolution should be and be last in the stack */
130                 if (ok && mmd) {
131                         ModifierData *md;
132
133                         ok = mmd->totlvl > 0;
134
135                         for (md = (ModifierData *)mmd->modifier.next; md && ok; md = md->next) {
136                                 if (modifier_isEnabled(scene, md, eModifierMode_Realtime)) {
137                                         ok = 0;
138                                 }
139                         }
140                 }
141                 else ok = 0;
142
143                 if (!ok) {
144                         BKE_report(op->reports, RPT_ERROR, "Multires data baking requires multi-resolution object");
145
146                         break;
147                 }
148
149                 if (mmd->lvl == 0) {
150                         BKE_report(op->reports, RPT_ERROR, "Multires data baking is not supported for preview subdivision level 0");
151
152                         break;
153                 }
154
155                 if (!me->mtpoly) {
156                         BKE_report(op->reports, RPT_ERROR, "Mesh should be unwrapped before multires data baking");
157
158                         ok = 0;
159                 }
160                 else {
161                         a = me->totpoly;
162                         while (ok && a--) {
163                                 Image *ima = me->mtpoly[a].tpage;
164
165                                 if (!ima) {
166                                         BKE_report(op->reports, RPT_ERROR, "You should have active texture to use multires baker");
167
168                                         ok = 0;
169                                 }
170                                 else {
171                                         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
172
173                                         if (!ibuf) {
174                                                 BKE_report(op->reports, RPT_ERROR, "Baking should happen to image with image buffer");
175
176                                                 ok = 0;
177                                         }
178                                         else {
179                                                 if (ibuf->rect == NULL && ibuf->rect_float == NULL)
180                                                         ok = 0;
181
182                                                 if (ibuf->rect_float && !(ibuf->channels == 0 || ibuf->channels == 4))
183                                                         ok = 0;
184
185                                                 if (!ok)
186                                                         BKE_report(op->reports, RPT_ERROR, "Baking to unsupported image type");
187                                         }
188
189                                         BKE_image_release_ibuf(ima, ibuf, NULL);
190                                 }
191                         }
192                 }
193
194                 if (!ok)
195                         break;
196         }
197         CTX_DATA_END;
198
199         return ok;
200 }
201
202 static DerivedMesh *multiresbake_create_loresdm(Scene *scene, Object *ob, int *lvl)
203 {
204         DerivedMesh *dm;
205         MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0);
206         Mesh *me = (Mesh *)ob->data;
207
208         *lvl = mmd->lvl;
209
210         if (*lvl == 0) {
211                 DerivedMesh *tmp_dm = CDDM_from_mesh(me, ob);
212
213                 DM_set_only_copy(tmp_dm, CD_MASK_BAREMESH | CD_MASK_MTFACE);
214
215                 dm = CDDM_copy(tmp_dm);
216                 tmp_dm->release(tmp_dm);
217         }
218         else {
219                 MultiresModifierData tmp_mmd = *mmd;
220                 DerivedMesh *cddm = CDDM_from_mesh(me, ob);
221
222                 DM_set_only_copy(cddm, CD_MASK_BAREMESH | CD_MASK_MTFACE);
223
224                 tmp_mmd.lvl = *lvl;
225                 tmp_mmd.sculptlvl = *lvl;
226                 dm = multires_make_derived_from_derived(cddm, &tmp_mmd, ob, 0);
227                 cddm->release(cddm);
228         }
229
230         return dm;
231 }
232
233 static DerivedMesh *multiresbake_create_hiresdm(Scene *scene, Object *ob, int *lvl, int *simple)
234 {
235         Mesh *me = (Mesh *)ob->data;
236         MultiresModifierData *mmd = get_multires_modifier(scene, ob, 0);
237         MultiresModifierData tmp_mmd = *mmd;
238         DerivedMesh *cddm = CDDM_from_mesh(me, ob);
239         DerivedMesh *dm;
240
241         DM_set_only_copy(cddm, CD_MASK_BAREMESH);
242
243         /* TODO: DM_set_only_copy wouldn't set mask for loop and poly data,
244          *       but we really need BAREMESH only to save lots of memory
245          */
246         CustomData_set_only_copy(&cddm->loopData, CD_MASK_BAREMESH);
247         CustomData_set_only_copy(&cddm->polyData, CD_MASK_BAREMESH);
248
249         *lvl = mmd->totlvl;
250         *simple = mmd->simple;
251
252         tmp_mmd.lvl = mmd->totlvl;
253         tmp_mmd.sculptlvl = mmd->totlvl;
254         dm = multires_make_derived_from_derived(cddm, &tmp_mmd, ob, 0);
255         cddm->release(cddm);
256
257         return dm;
258 }
259
260 typedef enum ClearFlag {
261         CLEAR_NORMAL = 1
262 } ClearFlag;
263
264
265 static void clear_images(MTFace *mtface, int totface, ClearFlag flag)
266 {
267         int a;
268         const float vec_alpha[4] = {0.0f, 0.0f, 0.0f, 0.0f};
269         const float vec_solid[4] = {0.0f, 0.0f, 0.0f, 1.0f};
270         const float nor_alpha[4] = {0.5f, 0.5f, 1.0f, 0.0f};
271         const float nor_solid[4] = {0.5f, 0.5f, 1.0f, 1.0f};
272
273         for (a = 0; a < totface; a++)
274                 mtface[a].tpage->id.flag &= ~LIB_DOIT;
275
276         for (a = 0; a < totface; a++) {
277                 Image *ima = mtface[a].tpage;
278
279                 if ((ima->id.flag & LIB_DOIT) == 0) {
280                         ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
281
282                         if (flag == CLEAR_NORMAL)
283                                 IMB_rectfill(ibuf, (ibuf->planes == R_IMF_PLANES_RGBA) ? nor_alpha : nor_solid);
284                         else
285                                 IMB_rectfill(ibuf, (ibuf->planes == R_IMF_PLANES_RGBA) ? vec_alpha : vec_solid);
286
287                         ima->id.flag |= LIB_DOIT;
288
289                         BKE_image_release_ibuf(ima, ibuf, NULL);
290                 }
291         }
292
293         for (a = 0; a < totface; a++)
294                 mtface[a].tpage->id.flag &= ~LIB_DOIT;
295 }
296
297 static int multiresbake_image_exec_locked(bContext *C, wmOperator *op)
298 {
299         Object *ob;
300         Scene *scene = CTX_data_scene(C);
301         int objects_baked = 0;
302
303         if (!multiresbake_check(C, op))
304                 return OPERATOR_CANCELLED;
305
306         if (scene->r.bake_flag & R_BAKE_CLEAR) {  /* clear images */
307                 CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
308                 {
309                         Mesh *me;
310
311                         ob = base->object;
312                         me = (Mesh *)ob->data;
313
314                         if (scene->r.bake_mode == RE_BAKE_NORMALS && scene->r.bake_normal_space == R_BAKE_SPACE_TANGENT)
315                                 clear_images(me->mtface, me->totface, CLEAR_NORMAL);
316                         else
317                                 clear_images(me->mtface, me->totface, 0);
318                 }
319                 CTX_DATA_END;
320         }
321
322         CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
323         {
324                 MultiresBakeRender bkr = {0};
325
326                 ob = base->object;
327
328                 multires_force_update(ob);
329
330                 /* copy data stored in job descriptor */
331                 bkr.bake_filter = scene->r.bake_filter;
332                 bkr.mode = scene->r.bake_mode;
333                 bkr.use_lores_mesh = scene->r.bake_flag & R_BAKE_LORES_MESH;
334                 bkr.bias = scene->r.bake_biasdist;
335                 bkr.number_of_rays = scene->r.bake_samples;
336                 bkr.raytrace_structure = scene->r.raytrace_structure;
337                 bkr.octree_resolution = scene->r.ocres;
338                 bkr.threads = scene->r.mode & R_FIXED_THREADS ? scene->r.threads : 0;
339
340                 /* create low-resolution DM (to bake to) and hi-resolution DM (to bake from) */
341                 bkr.hires_dm = multiresbake_create_hiresdm(scene, ob, &bkr.tot_lvl, &bkr.simple);
342                 bkr.lores_dm = multiresbake_create_loresdm(scene, ob, &bkr.lvl);
343
344                 RE_multires_bake_images(&bkr);
345
346                 BLI_freelistN(&bkr.image);
347
348                 bkr.lores_dm->release(bkr.lores_dm);
349                 bkr.hires_dm->release(bkr.hires_dm);
350
351                 objects_baked++;
352         }
353         CTX_DATA_END;
354
355         if (!objects_baked)
356                 BKE_report(op->reports, RPT_ERROR, "No objects found to bake from");
357
358         return OPERATOR_FINISHED;
359 }
360
361 /* Multiresbake adopted for job-system executing */
362 static void init_multiresbake_job(bContext *C, MultiresBakeJob *bkj)
363 {
364         Scene *scene = CTX_data_scene(C);
365         Object *ob;
366
367         /* backup scene settings, so their changing in UI would take no effect on baker */
368         bkj->bake_filter = scene->r.bake_filter;
369         bkj->mode = scene->r.bake_mode;
370         bkj->use_lores_mesh = scene->r.bake_flag & R_BAKE_LORES_MESH;
371         bkj->bake_clear = scene->r.bake_flag & R_BAKE_CLEAR;
372         bkj->bias = scene->r.bake_biasdist;
373         bkj->number_of_rays = scene->r.bake_samples;
374         bkj->raytrace_structure = scene->r.raytrace_structure;
375         bkj->octree_resolution = scene->r.ocres;
376         bkj->threads = scene->r.mode & R_FIXED_THREADS ? scene->r.threads : 0;
377
378         CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
379         {
380                 MultiresBakerJobData *data;
381                 int lvl;
382
383                 ob = base->object;
384
385                 multires_force_update(ob);
386
387                 data = MEM_callocN(sizeof(MultiresBakerJobData), "multiresBaker derivedMesh_data");
388
389                 /* create low-resolution DM (to bake to) and hi-resolution DM (to bake from) */
390                 data->hires_dm = multiresbake_create_hiresdm(scene, ob, &data->tot_lvl, &data->simple);
391                 data->lores_dm = multiresbake_create_loresdm(scene, ob, &lvl);
392                 data->lvl = lvl;
393
394                 BLI_addtail(&bkj->data, data);
395         }
396         CTX_DATA_END;
397 }
398
399 static void multiresbake_startjob(void *bkv, short *stop, short *do_update, float *progress)
400 {
401         MultiresBakerJobData *data;
402         MultiresBakeJob *bkj = bkv;
403         int baked_objects = 0, tot_obj;
404
405         tot_obj = BLI_countlist(&bkj->data);
406
407         if (bkj->bake_clear) {  /* clear images */
408                 for (data = bkj->data.first; data; data = data->next) {
409                         DerivedMesh *dm = data->lores_dm;
410                         MTFace *mtface = CustomData_get_layer(&dm->faceData, CD_MTFACE);
411
412                         if (bkj->mode == RE_BAKE_NORMALS)
413                                 clear_images(mtface, dm->getNumTessFaces(dm), CLEAR_NORMAL);
414                         else
415                                 clear_images(mtface, dm->getNumTessFaces(dm), 0);
416                 }
417         }
418
419         for (data = bkj->data.first; data; data = data->next) {
420                 MultiresBakeRender bkr = {0};
421
422                 /* copy data stored in job descriptor */
423                 bkr.bake_filter = bkj->bake_filter;
424                 bkr.mode = bkj->mode;
425                 bkr.use_lores_mesh = bkj->use_lores_mesh;
426
427                 /* create low-resolution DM (to bake to) and hi-resolution DM (to bake from) */
428                 bkr.lores_dm = data->lores_dm;
429                 bkr.hires_dm = data->hires_dm;
430                 bkr.tot_lvl = data->tot_lvl;
431                 bkr.lvl = data->lvl;
432                 bkr.simple = data->simple;
433
434                 /* needed for proper progress bar */
435                 bkr.tot_obj = tot_obj;
436                 bkr.baked_objects = baked_objects;
437
438                 bkr.stop = stop;
439                 bkr.do_update = do_update;
440                 bkr.progress = progress;
441
442                 bkr.bias = bkj->bias;
443                 bkr.number_of_rays = bkj->number_of_rays;
444                 bkr.raytrace_structure = bkj->raytrace_structure;
445                 bkr.octree_resolution = bkj->octree_resolution;
446                 bkr.threads = bkj->threads;
447
448                 RE_multires_bake_images(&bkr);
449
450                 data->images = bkr.image;
451
452                 baked_objects++;
453         }
454 }
455
456 static void multiresbake_freejob(void *bkv)
457 {
458         MultiresBakeJob *bkj = bkv;
459         MultiresBakerJobData *data, *next;
460         LinkData *link;
461
462         data = bkj->data.first;
463         while (data) {
464                 next = data->next;
465                 data->lores_dm->release(data->lores_dm);
466                 data->hires_dm->release(data->hires_dm);
467
468                 /* delete here, since this delete will be called from main thread */
469                 for (link = data->images.first; link; link = link->next) {
470                         Image *ima = (Image *)link->data;
471                         GPU_free_image(ima);
472                 }
473
474                 BLI_freelistN(&data->images);
475
476                 MEM_freeN(data);
477                 data = next;
478         }
479
480         MEM_freeN(bkj);
481 }
482
483 static int multiresbake_image_exec(bContext *C, wmOperator *op)
484 {
485         Scene *scene = CTX_data_scene(C);
486         MultiresBakeJob *bkr;
487         wmJob *wm_job;
488
489         if (!multiresbake_check(C, op))
490                 return OPERATOR_CANCELLED;
491
492         bkr = MEM_callocN(sizeof(MultiresBakeJob), "MultiresBakeJob data");
493         init_multiresbake_job(C, bkr);
494
495         if (!bkr->data.first) {
496                 BKE_report(op->reports, RPT_ERROR, "No objects found to bake from");
497                 return OPERATOR_CANCELLED;
498         }
499
500         /* setup job */
501         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Multires Bake",
502                              WM_JOB_EXCL_RENDER | WM_JOB_PRIORITY | WM_JOB_PROGRESS, WM_JOB_TYPE_OBJECT_BAKE_TEXTURE);
503         WM_jobs_customdata_set(wm_job, bkr, multiresbake_freejob);
504         WM_jobs_timer(wm_job, 0.2, NC_IMAGE, 0); /* TODO - only draw bake image, can we enforce this */
505         WM_jobs_callbacks(wm_job, multiresbake_startjob, NULL, NULL, NULL);
506
507         G.is_break = FALSE;
508
509         WM_jobs_start(CTX_wm_manager(C), wm_job);
510         WM_cursor_wait(0);
511
512         /* add modal handler for ESC */
513         WM_event_add_modal_handler(C, op);
514
515         return OPERATOR_RUNNING_MODAL;
516 }
517
518 /* ****************** render BAKING ********************** */
519
520 /* threaded break test */
521 static int thread_break(void *UNUSED(arg))
522 {
523         return G.is_break;
524 }
525
526 typedef struct BakeRender {
527         Render *re;
528         Main *main;
529         Scene *scene;
530         struct Object *actob;
531         int result, ready;
532
533         ReportList *reports;
534
535         short *stop;
536         short *do_update;
537         float *progress;
538         
539         ListBase threads;
540
541         /* backup */
542         short prev_wo_amb_occ;
543         short prev_r_raytrace;
544
545         /* for redrawing */
546         ScrArea *sa;
547 } BakeRender;
548
549 /* use by exec and invoke */
550 static int test_bake_internal(bContext *C, ReportList *reports)
551 {
552         Scene *scene = CTX_data_scene(C);
553
554         if ((scene->r.bake_flag & R_BAKE_TO_ACTIVE) && CTX_data_active_object(C) == NULL) {
555                 BKE_report(reports, RPT_ERROR, "No active object");
556         }
557         else if (scene->r.bake_mode == RE_BAKE_AO && scene->world == NULL) {
558                 BKE_report(reports, RPT_ERROR, "No world set up");
559         }
560         else {
561                 return 1;
562         }
563
564         return 0;
565 }
566
567 static void init_bake_internal(BakeRender *bkr, bContext *C)
568 {
569         Scene *scene = CTX_data_scene(C);
570         bScreen *sc = CTX_wm_screen(C);
571
572         /* get editmode results */
573         ED_object_exit_editmode(C, 0);  /* 0 = does not exit editmode */
574
575         bkr->sa = sc ? BKE_screen_find_big_area(sc, SPACE_IMAGE, 10) : NULL; /* can be NULL */
576         bkr->main = CTX_data_main(C);
577         bkr->scene = scene;
578         bkr->actob = (scene->r.bake_flag & R_BAKE_TO_ACTIVE) ? OBACT : NULL;
579         bkr->re = RE_NewRender("_Bake View_");
580
581         if (scene->r.bake_mode == RE_BAKE_AO) {
582                 /* If raytracing or AO is disabled, switch it on temporarily for baking. */
583                 bkr->prev_wo_amb_occ = (scene->world->mode & WO_AMB_OCC) != 0;
584                 scene->world->mode |= WO_AMB_OCC;
585         }
586         if (scene->r.bake_mode == RE_BAKE_AO || bkr->actob) {
587                 bkr->prev_r_raytrace = (scene->r.mode & R_RAYTRACE) != 0;
588                 scene->r.mode |= R_RAYTRACE;
589         }
590 }
591
592 static void finish_bake_internal(BakeRender *bkr)
593 {
594         Image *ima;
595
596         RE_Database_Free(bkr->re);
597
598         /* restore raytrace and AO */
599         if (bkr->scene->r.bake_mode == RE_BAKE_AO)
600                 if (bkr->prev_wo_amb_occ == 0)
601                         bkr->scene->world->mode &= ~WO_AMB_OCC;
602
603         if (bkr->scene->r.bake_mode == RE_BAKE_AO || bkr->actob)
604                 if (bkr->prev_r_raytrace == 0)
605                         bkr->scene->r.mode &= ~R_RAYTRACE;
606
607         /* force OpenGL reload and mipmap recalc */
608         for (ima = G.main->image.first; ima; ima = ima->id.next) {
609                 ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
610
611                 /* some of the images could have been changed during bake,
612                  * so recreate mipmaps regardless bake result status
613                  */
614                 if (ima->ok == IMA_OK_LOADED) {
615                         if (ibuf) {
616                                 if (ibuf->userflags & IB_BITMAPDIRTY) {
617                                         GPU_free_image(ima);
618                                         imb_freemipmapImBuf(ibuf);
619                                 }
620
621                                 /* invalidate display buffers for changed images */
622                                 if (ibuf->userflags & IB_BITMAPDIRTY)
623                                         ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
624                         }
625                 }
626
627                 /* freed when baking is done, but if its canceled we need to free here */
628                 if (ibuf) {
629                         if (ibuf->userdata) {
630                                 BakeImBufuserData *userdata = (BakeImBufuserData *) ibuf->userdata;
631                                 if (userdata->mask_buffer)
632                                         MEM_freeN(userdata->mask_buffer);
633                                 if (userdata->displacement_buffer)
634                                         MEM_freeN(userdata->displacement_buffer);
635                                 MEM_freeN(userdata);
636                                 ibuf->userdata = NULL;
637                         }
638                 }
639
640                 BKE_image_release_ibuf(ima, ibuf, NULL);
641         }
642 }
643
644 static void *do_bake_render(void *bake_v)
645 {
646         BakeRender *bkr = bake_v;
647
648         bkr->result = RE_bake_shade_all_selected(bkr->re, bkr->scene->r.bake_mode, bkr->actob, NULL, bkr->progress);
649         bkr->ready = 1;
650
651         return NULL;
652 }
653
654 static void bake_startjob(void *bkv, short *stop, short *do_update, float *progress)
655 {
656         BakeRender *bkr = bkv;
657         Scene *scene = bkr->scene;
658         Main *bmain = bkr->main;
659
660         bkr->stop = stop;
661         bkr->do_update = do_update;
662         bkr->progress = progress;
663
664         RE_test_break_cb(bkr->re, NULL, thread_break);
665         G.is_break = FALSE;   /* blender_test_break uses this global */
666
667         RE_Database_Baking(bkr->re, bmain, scene, scene->lay, scene->r.bake_mode, bkr->actob);
668
669         /* baking itself is threaded, cannot use test_break in threads. we also update optional imagewindow */
670         bkr->result = RE_bake_shade_all_selected(bkr->re, scene->r.bake_mode, bkr->actob, bkr->do_update, bkr->progress);
671 }
672
673 static void bake_update(void *bkv)
674 {
675         BakeRender *bkr = bkv;
676
677         if (bkr->sa && bkr->sa->spacetype == SPACE_IMAGE) { /* in case the user changed while baking */
678                 SpaceImage *sima = bkr->sa->spacedata.first;
679                 if (sima)
680                         sima->image = RE_bake_shade_get_image();
681         }
682 }
683
684 static void bake_freejob(void *bkv)
685 {
686         BakeRender *bkr = bkv;
687         finish_bake_internal(bkr);
688
689         if (bkr->result == BAKE_RESULT_NO_OBJECTS)
690                 BKE_report(bkr->reports, RPT_ERROR, "No objects or images found to bake to");
691         else if (bkr->result == BAKE_RESULT_FEEDBACK_LOOP)
692                 BKE_report(bkr->reports, RPT_WARNING, "Feedback loop detected");
693
694         MEM_freeN(bkr);
695         G.is_rendering = FALSE;
696 }
697
698 /* catch esc */
699 static int objects_bake_render_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
700 {
701         /* no running blender, remove handler and pass through */
702         if (0 == WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C), WM_JOB_TYPE_OBJECT_BAKE_TEXTURE))
703                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
704
705         /* running render */
706         switch (event->type) {
707                 case ESCKEY:
708                         return OPERATOR_RUNNING_MODAL;
709                         break;
710         }
711         return OPERATOR_PASS_THROUGH;
712 }
713
714 static int is_multires_bake(Scene *scene)
715 {
716         if (ELEM3(scene->r.bake_mode, RE_BAKE_NORMALS, RE_BAKE_DISPLACEMENT, RE_BAKE_AO))
717                 return scene->r.bake_flag & R_BAKE_MULTIRES;
718
719         return 0;
720 }
721
722 static int objects_bake_render_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(_event))
723 {
724         Scene *scene = CTX_data_scene(C);
725         int result = OPERATOR_CANCELLED;
726
727         if (is_multires_bake(scene)) {
728                 result = multiresbake_image_exec(C, op);
729         }
730         else {
731                 /* only one render job at a time */
732                 if (WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_OBJECT_BAKE_TEXTURE))
733                         return OPERATOR_CANCELLED;
734
735                 if (test_bake_internal(C, op->reports) == 0) {
736                         return OPERATOR_CANCELLED;
737                 }
738                 else {
739                         BakeRender *bkr = MEM_callocN(sizeof(BakeRender), "render bake");
740                         wmJob *wm_job;
741
742                         init_bake_internal(bkr, C);
743                         bkr->reports = op->reports;
744
745                         /* setup job */
746                         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Texture Bake",
747                                              WM_JOB_EXCL_RENDER | WM_JOB_PRIORITY | WM_JOB_PROGRESS, WM_JOB_TYPE_OBJECT_BAKE_TEXTURE);
748                         WM_jobs_customdata_set(wm_job, bkr, bake_freejob);
749                         WM_jobs_timer(wm_job, 0.2, NC_IMAGE, 0); /* TODO - only draw bake image, can we enforce this */
750                         WM_jobs_callbacks(wm_job, bake_startjob, NULL, bake_update, NULL);
751
752                         G.is_break = FALSE;
753                         G.is_rendering = TRUE;
754
755                         WM_jobs_start(CTX_wm_manager(C), wm_job);
756
757                         WM_cursor_wait(0);
758
759                         /* add modal handler for ESC */
760                         WM_event_add_modal_handler(C, op);
761                 }
762
763                 result = OPERATOR_RUNNING_MODAL;
764         }
765
766         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, scene);
767
768         return result;
769 }
770
771
772 static int bake_image_exec(bContext *C, wmOperator *op)
773 {
774         Main *bmain = CTX_data_main(C);
775         Scene *scene = CTX_data_scene(C);
776         int result = OPERATOR_CANCELLED;
777
778         if (is_multires_bake(scene)) {
779                 result = multiresbake_image_exec_locked(C, op);
780         }
781         else {
782                 if (test_bake_internal(C, op->reports) == 0) {
783                         return OPERATOR_CANCELLED;
784                 }
785                 else {
786                         ListBase threads;
787                         BakeRender bkr = {NULL};
788
789                         init_bake_internal(&bkr, C);
790                         bkr.reports = op->reports;
791
792                         RE_test_break_cb(bkr.re, NULL, thread_break);
793                         G.is_break = FALSE;   /* blender_test_break uses this global */
794
795                         RE_Database_Baking(bkr.re, bmain, scene, scene->lay, scene->r.bake_mode, (scene->r.bake_flag & R_BAKE_TO_ACTIVE) ? OBACT : NULL);
796
797                         /* baking itself is threaded, cannot use test_break in threads  */
798                         BLI_init_threads(&threads, do_bake_render, 1);
799                         bkr.ready = 0;
800                         BLI_insert_thread(&threads, &bkr);
801
802                         while (bkr.ready == 0) {
803                                 PIL_sleep_ms(50);
804                                 if (bkr.ready)
805                                         break;
806
807                                 /* used to redraw in 2.4x but this is just for exec in 2.5 */
808                                 if (!G.background)
809                                         blender_test_break();
810                         }
811                         BLI_end_threads(&threads);
812
813                         if (bkr.result == BAKE_RESULT_NO_OBJECTS)
814                                 BKE_report(op->reports, RPT_ERROR, "No valid images found to bake to");
815                         else if (bkr.result == BAKE_RESULT_FEEDBACK_LOOP)
816                                 BKE_report(op->reports, RPT_ERROR, "Feedback loop detected");
817
818                         finish_bake_internal(&bkr);
819
820                         result = OPERATOR_FINISHED;
821                 }
822         }
823
824         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, scene);
825
826         return result;
827 }
828
829 void OBJECT_OT_bake_image(wmOperatorType *ot)
830 {
831         /* identifiers */
832         ot->name = "Bake";
833         ot->description = "Bake image textures of selected objects";
834         ot->idname = "OBJECT_OT_bake_image";
835
836         /* api callbacks */
837         ot->exec = bake_image_exec;
838         ot->invoke = objects_bake_render_invoke;
839         ot->modal = objects_bake_render_modal;
840 }