Blender V4.5
multires_bake.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2012 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <cstring>
10
11#include "MEM_guardedalloc.h"
12
13#include "DNA_modifier_types.h"
14#include "DNA_scene_types.h"
15
16#include "BLI_listbase.h"
17#include "BLI_math_color.h"
18#include "BLI_math_geom.h"
19#include "BLI_math_matrix.h"
20#include "BLI_threads.h"
21
22#include "BKE_attribute.hh"
23#include "BKE_ccg.hh"
24#include "BKE_customdata.hh"
25#include "BKE_global.hh"
26#include "BKE_image.hh"
27#include "BKE_lib_id.hh"
28#include "BKE_mesh.hh"
30#include "BKE_mesh_tangent.hh"
31#include "BKE_multires.hh"
32#include "BKE_subsurf.hh"
33
34#include "DEG_depsgraph.hh"
35
36#include "RE_multires_bake.h"
37#include "RE_pipeline.h"
38#include "RE_texture_margin.h"
39
40#include "IMB_imbuf.hh"
41#include "IMB_imbuf_types.hh"
42
43using MPassKnownData = void (*)(blender::Span<blender::float3> vert_positions,
46 blender::Span<int> corner_verts,
48 blender::Span<int> tri_faces,
50 DerivedMesh *hires_dm,
51 void *thread_data,
52 void *bake_data,
53 ImBuf *ibuf,
54 const int face_index,
55 const int lvl,
56 const float st[2],
57 float tangmat[3][3],
58 const int x,
59 const int y);
60
61using MInitBakeData = void *(*)(MultiresBakeRender *bkr, ImBuf *ibuf);
62using MFreeBakeData = void (*)(void *bake_data);
63
67
99
100using MFlushPixel = void (*)(const MResolvePixelData *data, const int x, const int y);
101
109
115
119
124
126 const int tri_num,
127 const int vert_index,
128 float r_normal[3])
129{
130 const int face_index = data->tri_faces[tri_num];
131 const bool smoothnormal = !(data->sharp_faces && data->sharp_faces[face_index]);
132
133 if (smoothnormal) {
134 const int vi = data->corner_verts[data->corner_tris[tri_num][vert_index]];
135 copy_v3_v3(r_normal, data->vert_normals[vi]);
136 }
137 else {
138 copy_v3_v3(r_normal, data->face_normals[face_index]);
139 }
140}
141
142static void init_bake_rast(MBakeRast *bake_rast,
143 const ImBuf *ibuf,
144 const MResolvePixelData *data,
146 bool *do_update)
147{
148 BakeImBufuserData *userdata = (BakeImBufuserData *)ibuf->userdata;
149
150 memset(bake_rast, 0, sizeof(MBakeRast));
151
152 bake_rast->texels = userdata->mask_buffer;
153 bake_rast->w = ibuf->x;
154 bake_rast->h = ibuf->y;
155 bake_rast->data = data;
156 bake_rast->flush_pixel = flush_pixel;
157 bake_rast->do_update = do_update;
158}
159
160static void flush_pixel(const MResolvePixelData *data, const int x, const int y)
161{
162 const float st[2] = {(x + 0.5f) / data->w + data->uv_offset[0],
163 (y + 0.5f) / data->h + data->uv_offset[1]};
164 const float *st0, *st1, *st2;
165 const float *tang0, *tang1, *tang2;
166 float no0[3], no1[3], no2[3];
167 float fUV[2], from_tang[3][3], to_tang[3][3];
168 float u, v, w, sign;
169 int r;
170
171 st0 = data->uv_map[data->corner_tris[data->tri_index][0]];
172 st1 = data->uv_map[data->corner_tris[data->tri_index][1]];
173 st2 = data->uv_map[data->corner_tris[data->tri_index][2]];
174
175 multiresbake_get_normal(data, data->tri_index, 0, no0); /* can optimize these 3 into one call */
176 multiresbake_get_normal(data, data->tri_index, 1, no1);
177 multiresbake_get_normal(data, data->tri_index, 2, no2);
178
179 resolve_tri_uv_v2(fUV, st, st0, st1, st2);
180
181 u = fUV[0];
182 v = fUV[1];
183 w = 1 - u - v;
184
185 if (data->pvtangent) {
186 tang0 = data->pvtangent + data->corner_tris[data->tri_index][0] * 4;
187 tang1 = data->pvtangent + data->corner_tris[data->tri_index][1] * 4;
188 tang2 = data->pvtangent + data->corner_tris[data->tri_index][2] * 4;
189
190 /* the sign is the same at all face vertices for any non degenerate face.
191 * Just in case we clamp the interpolated value though. */
192 sign = (tang0[3] * u + tang1[3] * v + tang2[3] * w) < 0 ? (-1.0f) : 1.0f;
193
194 /* this sequence of math is designed specifically as is with great care
195 * to be compatible with our shader. Please don't change without good reason. */
196 for (r = 0; r < 3; r++) {
197 from_tang[0][r] = tang0[r] * u + tang1[r] * v + tang2[r] * w;
198 from_tang[2][r] = no0[r] * u + no1[r] * v + no2[r] * w;
199 }
200
201 cross_v3_v3v3(from_tang[1], from_tang[2], from_tang[0]); /* `B = sign * cross(N, T)` */
202 mul_v3_fl(from_tang[1], sign);
203 invert_m3_m3(to_tang, from_tang);
204 }
205 else {
206 zero_m3(to_tang);
207 }
208
209 data->pass_data(data->vert_positions,
210 data->vert_normals,
211 data->faces,
212 data->corner_verts,
213 data->corner_tris,
214 data->tri_faces,
215 data->uv_map,
216 data->hires_dm,
217 data->thread_data,
218 data->bake_data,
219 data->ibuf,
220 data->tri_index,
221 data->lvl,
222 st,
223 to_tang,
224 x,
225 y);
226}
227
228static void set_rast_triangle(const MBakeRast *bake_rast, const int x, const int y)
229{
230 const int w = bake_rast->w;
231 const int h = bake_rast->h;
232
233 if (x >= 0 && x < w && y >= 0 && y < h) {
234 if ((bake_rast->texels[y * w + x]) == 0) {
235 bake_rast->texels[y * w + x] = FILTER_MASK_USED;
236 flush_pixel(bake_rast->data, x, y);
237 if (bake_rast->do_update) {
238 *bake_rast->do_update = true;
239 }
240 }
241 }
242}
243
244static void rasterize_half(const MBakeRast *bake_rast,
245 const float s0_s,
246 const float t0_s,
247 const float s1_s,
248 const float t1_s,
249 const float s0_l,
250 const float t0_l,
251 const float s1_l,
252 const float t1_l,
253 const int y0_in,
254 const int y1_in,
255 const int is_mid_right)
256{
257 const int s_stable = fabsf(t1_s - t0_s) > FLT_EPSILON ? 1 : 0;
258 const int l_stable = fabsf(t1_l - t0_l) > FLT_EPSILON ? 1 : 0;
259 const int w = bake_rast->w;
260 const int h = bake_rast->h;
261 int y, y0, y1;
262
263 if (y1_in <= 0 || y0_in >= h) {
264 return;
265 }
266
267 y0 = y0_in < 0 ? 0 : y0_in;
268 y1 = y1_in >= h ? h : y1_in;
269
270 for (y = y0; y < y1; y++) {
271 /*-b(x-x0) + a(y-y0) = 0 */
272 int iXl, iXr, x;
273 float x_l = s_stable != 0 ? (s0_s + (((s1_s - s0_s) * (y - t0_s)) / (t1_s - t0_s))) : s0_s;
274 float x_r = l_stable != 0 ? (s0_l + (((s1_l - s0_l) * (y - t0_l)) / (t1_l - t0_l))) : s0_l;
275
276 if (is_mid_right != 0) {
277 std::swap(x_l, x_r);
278 }
279
280 iXl = int(ceilf(x_l));
281 iXr = int(ceilf(x_r));
282
283 if (iXr > 0 && iXl < w) {
284 iXl = iXl < 0 ? 0 : iXl;
285 iXr = iXr >= w ? w : iXr;
286
287 for (x = iXl; x < iXr; x++) {
288 set_rast_triangle(bake_rast, x, y);
289 }
290 }
291 }
292}
293
294static void bake_rasterize(const MBakeRast *bake_rast,
295 const float st0_in[2],
296 const float st1_in[2],
297 const float st2_in[2])
298{
299 const int w = bake_rast->w;
300 const int h = bake_rast->h;
301 float slo = st0_in[0] * w - 0.5f;
302 float tlo = st0_in[1] * h - 0.5f;
303 float smi = st1_in[0] * w - 0.5f;
304 float tmi = st1_in[1] * h - 0.5f;
305 float shi = st2_in[0] * w - 0.5f;
306 float thi = st2_in[1] * h - 0.5f;
307 int is_mid_right = 0, ylo, yhi, yhi_beg;
308
309 /* skip degenerates */
310 if ((slo == smi && tlo == tmi) || (slo == shi && tlo == thi) || (smi == shi && tmi == thi)) {
311 return;
312 }
313
314 /* sort by T */
315 if (tlo > tmi && tlo > thi) {
316 std::swap(shi, slo);
317 std::swap(thi, tlo);
318 }
319 else if (tmi > thi) {
320 std::swap(shi, smi);
321 std::swap(thi, tmi);
322 }
323
324 if (tlo > tmi) {
325 std::swap(slo, smi);
326 std::swap(tlo, tmi);
327 }
328
329 /* check if mid point is to the left or to the right of the lo-hi edge */
330 is_mid_right = (-(shi - slo) * (tmi - thi) + (thi - tlo) * (smi - shi)) > 0 ? 1 : 0;
331 ylo = int(ceilf(tlo));
332 yhi_beg = int(ceilf(tmi));
333 yhi = int(ceilf(thi));
334
335 // if (fTmi>ceilf(fTlo))
336 rasterize_half(bake_rast, slo, tlo, smi, tmi, slo, tlo, shi, thi, ylo, yhi_beg, is_mid_right);
337 rasterize_half(bake_rast, smi, tmi, shi, thi, slo, tlo, shi, thi, yhi_beg, yhi, is_mid_right);
338}
339
341{
342 if (!bkr->stop) {
343 /* this means baker is executed outside from job system */
344 return 0;
345 }
346
347 return *bkr->stop || G.is_break;
348}
349
350/* **** Threading routines **** */
351
357
359 /* this data is actually shared between all the threads */
365
366 /* thread-specific data */
369
370 /* displacement-specific data */
372};
373
375{
376 int face = -1;
377
378 /* TODO: it could worth making it so thread will handle neighbor faces
379 * for better memory cache utilization
380 */
381
382 BLI_spin_lock(&queue->spin);
383 if (queue->cur_tri < queue->tot_tri) {
384 face = queue->cur_tri;
385 queue->cur_tri++;
386 }
387 BLI_spin_unlock(&queue->spin);
388
389 return face;
390}
391
392static void *do_multires_bake_thread(void *data_v)
393{
394 MultiresBakeThread *handle = (MultiresBakeThread *)data_v;
395 MResolvePixelData *data = &handle->data;
396 MBakeRast *bake_rast = &handle->bake_rast;
397 MultiresBakeRender *bkr = handle->bkr;
398 int tri_index;
399
400 while ((tri_index = multires_bake_queue_next_tri(handle->queue)) >= 0) {
401 const blender::int3 &tri = data->corner_tris[tri_index];
402 const int face_i = data->tri_faces[tri_index];
403 const short mat_nr = data->material_indices == nullptr ? 0 : data->material_indices[face_i];
404
405 if (multiresbake_test_break(bkr)) {
406 break;
407 }
408
409 Image *tri_image = mat_nr < bkr->ob_image.len ? bkr->ob_image.array[mat_nr] : nullptr;
410 if (tri_image != handle->image) {
411 continue;
412 }
413
414 data->tri_index = tri_index;
415
416 float uv[3][2];
417 sub_v2_v2v2(uv[0], data->uv_map[tri[0]], data->uv_offset);
418 sub_v2_v2v2(uv[1], data->uv_map[tri[1]], data->uv_offset);
419 sub_v2_v2v2(uv[2], data->uv_map[tri[2]], data->uv_offset);
420
421 bake_rasterize(bake_rast, uv[0], uv[1], uv[2]);
422
423 /* tag image buffer for refresh */
424 if (data->ibuf->float_buffer.data) {
425 data->ibuf->userflags |= IB_RECT_INVALID;
426 }
427
428 data->ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
429
430 /* update progress */
431 BLI_spin_lock(&handle->queue->spin);
432 bkr->baked_faces++;
433
434 if (bkr->do_update) {
435 *bkr->do_update = true;
436 }
437
438 if (bkr->progress) {
439 *bkr->progress = (float(bkr->baked_objects) +
440 float(bkr->baked_faces) / handle->num_total_faces) /
441 bkr->tot_obj;
442 }
443 BLI_spin_unlock(&handle->queue->spin);
444 }
445
446 return nullptr;
447}
448
449/* some of arrays inside ccgdm are lazy-initialized, which will generally
450 * require lock around accessing such data
451 * this function will ensure all arrays are allocated before threading started
452 */
454{
455 CCGElem **grid_data;
456 CCGKey key;
457 int grid_size;
458 const int *grid_offset;
459
460 grid_size = dm->getGridSize(dm);
461 grid_data = dm->getGridData(dm);
462 grid_offset = dm->getGridOffset(dm);
463 dm->getGridKey(dm, &key);
464
465 (void)grid_size;
466 (void)grid_data;
467 (void)grid_offset;
468}
469
471 Image *ima,
473 ImBuf *ibuf,
474 bool require_tangent,
475 MPassKnownData passKnownData,
476 MInitBakeData initBakeData,
477 MFreeBakeData freeBakeData,
479{
480 using namespace blender;
481 DerivedMesh *dm = bkr->lores_dm;
482 const int lvl = bkr->lvl;
483 if (dm->getNumPolys(dm) == 0) {
484 return;
485 }
486
487 MultiresBakeQueue queue;
488
489 const Span<float2> uv_map(
490 reinterpret_cast<const float2 *>(dm->getLoopDataArray(dm, CD_PROP_FLOAT2)),
491 dm->getNumLoops(dm));
492
493 float *pvtangent = nullptr;
494
495 ListBase threads;
496 int i, tot_thread = bkr->threads > 0 ? bkr->threads : BLI_system_thread_count();
497
498 void *bake_data = nullptr;
499
500 Mesh *temp_mesh = BKE_mesh_new_nomain(
501 dm->getNumVerts(dm), dm->getNumEdges(dm), dm->getNumPolys(dm), dm->getNumLoops(dm));
502 temp_mesh->vert_positions_for_write().copy_from(
503 {reinterpret_cast<const float3 *>(dm->getVertArray(dm)), temp_mesh->verts_num});
504 temp_mesh->edges_for_write().copy_from(
505 {reinterpret_cast<const int2 *>(dm->getEdgeArray(dm)), temp_mesh->edges_num});
506 temp_mesh->face_offsets_for_write().copy_from({dm->getPolyArray(dm), temp_mesh->faces_num + 1});
507 temp_mesh->corner_verts_for_write().copy_from(
508 {dm->getCornerVertArray(dm), temp_mesh->corners_num});
509 temp_mesh->corner_edges_for_write().copy_from(
510 {dm->getCornerEdgeArray(dm), temp_mesh->corners_num});
511
512 const Span<float3> positions = temp_mesh->vert_positions();
513 const OffsetIndices faces = temp_mesh->faces();
514 const Span<int> corner_verts = temp_mesh->corner_verts();
515 const Span<float3> vert_normals = temp_mesh->vert_normals();
516 const Span<float3> face_normals = temp_mesh->face_normals();
517 const Span<int3> corner_tris = temp_mesh->corner_tris();
518 const Span<int> tri_faces = temp_mesh->corner_tri_faces();
519
520 if (require_tangent) {
522 const bool *sharp_edges = static_cast<const bool *>(
524 const bool *sharp_faces = static_cast<const bool *>(
526
527 /* Copy sharp faces and edges, for corner normals domain and tangents
528 * to be computed correctly. */
529 if (sharp_edges != nullptr) {
530 bke::MutableAttributeAccessor attributes = temp_mesh->attributes_for_write();
531 attributes.add<bool>("sharp_edge",
534 Span<bool>(sharp_edges, temp_mesh->edges_num))));
535 }
536 if (sharp_faces != nullptr) {
537 bke::MutableAttributeAccessor attributes = temp_mesh->attributes_for_write();
538 attributes.add<bool>("sharp_face",
541 Span<bool>(sharp_faces, temp_mesh->faces_num))));
542 }
543
544 const float3 *orco = static_cast<const float3 *>(dm->getVertDataArray(dm, CD_ORCO));
545
546 const Span<float3> corner_normals = temp_mesh->corner_normals();
548 faces,
549 Span(dm->getCornerVertArray(dm), faces.total_size()),
550 corner_tris,
551 tri_faces,
552 sharp_faces ? Span(sharp_faces, faces.size()) : Span<bool>(),
553 &dm->loopData,
554 true,
555 nullptr,
556 0,
557 vert_normals,
558 face_normals,
559 corner_normals,
560 orco ? Span(orco, positions.size()) : Span<float3>(),
561 /* result */
562 &dm->loopData,
563 dm->getNumLoops(dm),
564 &dm->tangent_mask);
565 }
566
567 pvtangent = static_cast<float *>(DM_get_loop_data_layer(dm, CD_TANGENT));
568 }
569
570 /* all threads shares the same custom bake data */
571 if (initBakeData) {
572 bake_data = initBakeData(bkr, ibuf);
573 }
574
575 if (tot_thread > 1) {
576 BLI_threadpool_init(&threads, do_multires_bake_thread, tot_thread);
577 }
578
580
582
583 /* faces queue */
584 queue.cur_tri = 0;
585 queue.tot_tri = corner_tris.size();
586 BLI_spin_init(&queue.spin);
587
588 /* fill in threads handles */
589 for (i = 0; i < tot_thread; i++) {
590 MultiresBakeThread *handle = &handles[i];
591
592 handle->bkr = bkr;
593 handle->image = ima;
594 handle->num_total_faces = queue.tot_tri * BLI_listbase_count(&ima->tiles);
595 handle->queue = &queue;
596
597 handle->data.vert_positions = positions;
598 handle->data.faces = faces;
599 handle->data.corner_verts = corner_verts;
600 handle->data.corner_tris = corner_tris;
601 handle->data.tri_faces = tri_faces;
602 handle->data.vert_normals = vert_normals;
603 handle->data.face_normals = face_normals;
604 handle->data.material_indices = static_cast<const int *>(
605 CustomData_get_layer_named(&dm->polyData, CD_PROP_INT32, "material_index"));
606 handle->data.sharp_faces = static_cast<const bool *>(
608 handle->data.uv_map = uv_map;
609 BKE_image_get_tile_uv(ima, tile->tile_number, handle->data.uv_offset);
610 handle->data.pvtangent = pvtangent;
611 handle->data.w = ibuf->x;
612 handle->data.h = ibuf->y;
613 handle->data.hires_dm = bkr->hires_dm;
614 handle->data.lvl = lvl;
615 handle->data.pass_data = passKnownData;
616 handle->data.thread_data = handle;
617 handle->data.bake_data = bake_data;
618 handle->data.ibuf = ibuf;
619
620 handle->height_min = FLT_MAX;
621 handle->height_max = -FLT_MAX;
622
623 init_bake_rast(&handle->bake_rast, ibuf, &handle->data, flush_pixel, bkr->do_update);
624
625 if (tot_thread > 1) {
626 BLI_threadpool_insert(&threads, handle);
627 }
628 }
629
630 /* run threads */
631 if (tot_thread > 1) {
632 BLI_threadpool_end(&threads);
633 }
634 else {
636 }
637
638 for (i = 0; i < tot_thread; i++) {
639 result->height_min = min_ff(result->height_min, handles[i].height_min);
640 result->height_max = max_ff(result->height_max, handles[i].height_max);
641 }
642
643 BLI_spin_end(&queue.spin);
644
645 /* finalize baking */
646 if (freeBakeData) {
647 freeBakeData(bake_data);
648 }
649
650 BKE_id_free(nullptr, temp_mesh);
651}
652
653/* mode = 0: interpolate normals,
654 * mode = 1: interpolate coord */
656 const CCGKey &key, CCGElem *grid, float crn_x, float crn_y, int mode, float res[3])
657{
658 int x0, x1, y0, y1;
659 float u, v;
660 float data[4][3];
661
662 x0 = int(crn_x);
663 x1 = x0 >= (key.grid_size - 1) ? (key.grid_size - 1) : (x0 + 1);
664
665 y0 = int(crn_y);
666 y1 = y0 >= (key.grid_size - 1) ? (key.grid_size - 1) : (y0 + 1);
667
668 u = crn_x - x0;
669 v = crn_y - y0;
670
671 if (mode == 0) {
672 copy_v3_v3(data[0], CCG_grid_elem_no(key, grid, x0, y0));
673 copy_v3_v3(data[1], CCG_grid_elem_no(key, grid, x1, y0));
674 copy_v3_v3(data[2], CCG_grid_elem_no(key, grid, x1, y1));
675 copy_v3_v3(data[3], CCG_grid_elem_no(key, grid, x0, y1));
676 }
677 else {
678 copy_v3_v3(data[0], CCG_grid_elem_co(key, grid, x0, y0));
679 copy_v3_v3(data[1], CCG_grid_elem_co(key, grid, x1, y0));
680 copy_v3_v3(data[2], CCG_grid_elem_co(key, grid, x1, y1));
681 copy_v3_v3(data[3], CCG_grid_elem_co(key, grid, x0, y1));
682 }
683
685}
686
687static void get_ccgdm_data(const blender::OffsetIndices<int> lores_polys,
688 DerivedMesh *hidm,
689 const int *index_mp_to_orig,
690 const int lvl,
691 const int face_index,
692 const float u,
693 const float v,
694 float co[3],
695 float n[3])
696{
697 CCGElem **grid_data;
698 CCGKey key;
699 float crn_x, crn_y;
700 int grid_size, S, face_side;
701 int *grid_offset, g_index;
702
703 grid_size = hidm->getGridSize(hidm);
704 grid_data = hidm->getGridData(hidm);
705 grid_offset = hidm->getGridOffset(hidm);
706 hidm->getGridKey(hidm, &key);
707
708 if (lvl == 0) {
709 face_side = (grid_size << 1) - 1;
710
711 g_index = grid_offset[face_index];
712 S = mdisp_rot_face_to_crn(lores_polys[face_index].size(),
713 face_side,
714 u * (face_side - 1),
715 v * (face_side - 1),
716 &crn_x,
717 &crn_y);
718 }
719 else {
720 /* number of faces per grid side */
721 int polys_per_grid_side = (1 << (lvl - 1));
722 /* get the original cage face index */
723 int cage_face_index = index_mp_to_orig ? index_mp_to_orig[face_index] : face_index;
724 /* local offset in total cage face grids
725 * `(1 << (2 * lvl))` is number of all faces for one cage face */
726 int loc_cage_poly_ofs = face_index % (1 << (2 * lvl));
727 /* local offset in the vertex grid itself */
728 int cell_index = loc_cage_poly_ofs % (polys_per_grid_side * polys_per_grid_side);
729 int cell_side = (grid_size - 1) / polys_per_grid_side;
730 /* row and column based on grid side */
731 int row = cell_index / polys_per_grid_side;
732 int col = cell_index % polys_per_grid_side;
733
734 /* S is the vertex whose grid we are examining */
735 S = face_index / (1 << (2 * (lvl - 1))) - grid_offset[cage_face_index];
736 /* get offset of grid data for original cage face */
737 g_index = grid_offset[cage_face_index];
738
739 crn_y = (row * cell_side) + u * cell_side;
740 crn_x = (col * cell_side) + v * cell_side;
741 }
742
743 CLAMP(crn_x, 0.0f, grid_size);
744 CLAMP(crn_y, 0.0f, grid_size);
745
746 if (n != nullptr) {
747 interp_bilinear_grid(key, grid_data[g_index + S], crn_x, crn_y, 0, n);
748 }
749
750 if (co != nullptr) {
751 interp_bilinear_grid(key, grid_data[g_index + S], crn_x, crn_y, 1, co);
752 }
753}
754
755/* mode = 0: interpolate normals,
756 * mode = 1: interpolate coord */
757
759 const blender::Span<blender::float3> vert_normals,
760 const blender::Span<int> corner_verts,
761 const blender::IndexRange face,
762 const float u,
763 const float v,
764 const int mode,
765 float res[3])
766{
767 float data[4][3];
768
769 if (mode == 0) {
770 copy_v3_v3(data[0], vert_normals[corner_verts[face[0]]]);
771 copy_v3_v3(data[1], vert_normals[corner_verts[face[1]]]);
772 copy_v3_v3(data[2], vert_normals[corner_verts[face[2]]]);
773 copy_v3_v3(data[3], vert_normals[corner_verts[face[3]]]);
774 }
775 else {
776 copy_v3_v3(data[0], vert_positions[corner_verts[face[0]]]);
777 copy_v3_v3(data[1], vert_positions[corner_verts[face[1]]]);
778 copy_v3_v3(data[2], vert_positions[corner_verts[face[2]]]);
779 copy_v3_v3(data[3], vert_positions[corner_verts[face[3]]]);
780 }
781
783}
784
786 const blender::Span<blender::float3> vert_normals,
787 const blender::Span<int> corner_verts,
788 const blender::int3 &corner_tri,
789 const float u,
790 const float v,
791 const int mode,
792 float res[3])
793{
794 float data[3][3];
795
796 if (mode == 0) {
797 copy_v3_v3(data[0], vert_normals[corner_verts[corner_tri[0]]]);
798 copy_v3_v3(data[1], vert_normals[corner_verts[corner_tri[1]]]);
799 copy_v3_v3(data[2], vert_normals[corner_verts[corner_tri[2]]]);
800 }
801 else {
802 copy_v3_v3(data[0], vert_positions[corner_verts[corner_tri[0]]]);
803 copy_v3_v3(data[1], vert_positions[corner_verts[corner_tri[1]]]);
804 copy_v3_v3(data[2], vert_positions[corner_verts[corner_tri[2]]]);
805 }
806
808}
809
810/* **************** Displacement Baker **************** */
811
813{
814 MHeightBakeData *height_data;
815 DerivedMesh *lodm = bkr->lores_dm;
816 BakeImBufuserData *userdata = static_cast<BakeImBufuserData *>(ibuf->userdata);
817
818 if (userdata->displacement_buffer == nullptr) {
820 "MultiresBake heights");
821 }
822
823 height_data = MEM_callocN<MHeightBakeData>("MultiresBake heightData");
824
825 height_data->heights = userdata->displacement_buffer;
826
827 if (!bkr->use_lores_mesh) {
828 SubsurfModifierData smd = {{nullptr}};
829 int ss_lvl = bkr->tot_lvl - bkr->lvl;
830
831 CLAMP(ss_lvl, 0, 6);
832
833 if (ss_lvl > 0) {
834 smd.levels = smd.renderLevels = ss_lvl;
836 smd.quality = 3;
837
839 bkr->lores_dm, &smd, bkr->scene, nullptr, SubsurfFlags(0));
840 init_ccgdm_arrays(height_data->ssdm);
841 }
842 }
843
844 height_data->orig_index_mp_to_orig = static_cast<const int *>(
845 lodm->getPolyDataArray(lodm, CD_ORIGINDEX));
846
847 return (void *)height_data;
848}
849
850static void free_heights_data(void *bake_data)
851{
852 MHeightBakeData *height_data = (MHeightBakeData *)bake_data;
853
854 if (height_data->ssdm) {
855 height_data->ssdm->release(height_data->ssdm);
856 }
857
858 MEM_freeN(height_data);
859}
860
861/* MultiresBake callback for heights baking
862 * general idea:
863 * - find coord of point with specified UV in hi-res mesh (let's call it p1)
864 * - find coord of point and normal with specified UV in lo-res mesh (or subdivided lo-res
865 * mesh to make texture smoother) let's call this point p0 and n.
866 * - height wound be dot(n, p1-p0) */
868 const blender::Span<blender::float3> vert_normals,
870 const blender::Span<int> corner_verts,
871 const blender::Span<blender::int3> corner_tris,
872 const blender::Span<int> tri_faces,
874 DerivedMesh *hires_dm,
875 void *thread_data_v,
876 void *bake_data,
877 ImBuf *ibuf,
878 const int tri_index,
879 const int lvl,
880 const float st[2],
881 float /*tangmat*/[3][3],
882 const int x,
883 const int y)
884{
885 const blender::int3 &tri = corner_tris[tri_index];
886 const int face_i = tri_faces[tri_index];
887 const blender::IndexRange face = faces[face_i];
888 MHeightBakeData *height_data = (MHeightBakeData *)bake_data;
889 MultiresBakeThread *thread_data = (MultiresBakeThread *)thread_data_v;
890 float uv[2];
891 const float *st0, *st1, *st2, *st3;
892 int pixel = ibuf->x * y + x;
893 float vec[3], p0[3], p1[3], n[3], len;
894
895 /* ideally we would work on triangles only, however, we rely on quads to get orthogonal
896 * coordinates for use in grid space (triangle barycentric is not orthogonal) */
897 if (face.size() == 4) {
898 st0 = uv_map[face[0]];
899 st1 = uv_map[face[1]];
900 st2 = uv_map[face[2]];
901 st3 = uv_map[face[3]];
902 resolve_quad_uv_v2(uv, st, st0, st1, st2, st3);
903 }
904 else {
905 st0 = uv_map[tri[0]];
906 st1 = uv_map[tri[1]];
907 st2 = uv_map[tri[2]];
908 resolve_tri_uv_v2(uv, st, st0, st1, st2);
909 }
910
911 clamp_v2(uv, 0.0f, 1.0f);
912
914 faces, hires_dm, height_data->orig_index_mp_to_orig, lvl, face_i, uv[0], uv[1], p1, nullptr);
915
916 if (height_data->ssdm) {
918 height_data->ssdm,
919 height_data->orig_index_mp_to_orig,
920 0,
921 face_i,
922 uv[0],
923 uv[1],
924 p0,
925 n);
926 }
927 else {
928 if (face.size() == 4) {
929 interp_bilinear_mpoly(vert_positions, vert_normals, corner_verts, face, uv[0], uv[1], 1, p0);
930 interp_bilinear_mpoly(vert_positions, vert_normals, corner_verts, face, uv[0], uv[1], 0, n);
931 }
932 else {
934 vert_positions, vert_normals, corner_verts, tri, uv[0], uv[1], 1, p0);
936 vert_positions, vert_normals, corner_verts, tri, uv[0], uv[1], 0, n);
937 }
938 }
939
940 sub_v3_v3v3(vec, p1, p0);
941 len = dot_v3v3(n, vec);
942
943 height_data->heights[pixel] = len;
944
945 thread_data->height_min = min_ff(thread_data->height_min, len);
946 thread_data->height_max = max_ff(thread_data->height_max, len);
947
948 if (ibuf->float_buffer.data) {
949 float *rrgbf = ibuf->float_buffer.data + pixel * 4;
950 rrgbf[0] = rrgbf[1] = rrgbf[2] = len;
951 rrgbf[3] = 1.0f;
952 }
953 else {
954 uchar *rrgb = ibuf->byte_buffer.data + pixel * 4;
955 rrgb[0] = rrgb[1] = rrgb[2] = unit_float_to_uchar_clamp(len);
956 rrgb[3] = 255;
957 }
958}
959
960/* **************** Normal Maps Baker **************** */
961
962static void *init_normal_data(MultiresBakeRender *bkr, ImBuf * /*ibuf*/)
963{
964 MNormalBakeData *normal_data;
965 DerivedMesh *lodm = bkr->lores_dm;
966
967 normal_data = MEM_callocN<MNormalBakeData>("MultiresBake normalData");
968
969 normal_data->orig_index_mp_to_orig = static_cast<const int *>(
970 lodm->getPolyDataArray(lodm, CD_ORIGINDEX));
971
972 return (void *)normal_data;
973}
974
975static void free_normal_data(void *bake_data)
976{
977 MNormalBakeData *normal_data = (MNormalBakeData *)bake_data;
978
979 MEM_freeN(normal_data);
980}
981
990static void apply_tangmat_callback(const blender::Span<blender::float3> /*vert_positions*/,
991 const blender::Span<blender::float3> /*vert_normals*/,
993 const blender::Span<int> /*corner_verts*/,
994 const blender::Span<blender::int3> corner_tris,
995 const blender::Span<int> tri_faces,
997 DerivedMesh *hires_dm,
998 void * /*thread_data*/,
999 void *bake_data,
1000 ImBuf *ibuf,
1001 const int tri_index,
1002 const int lvl,
1003 const float st[2],
1004 float tangmat[3][3],
1005 const int x,
1006 const int y)
1007{
1008 const blender::int3 &tri = corner_tris[tri_index];
1009 const int face_i = tri_faces[tri_index];
1010 const blender::IndexRange face = faces[face_i];
1011 MNormalBakeData *normal_data = (MNormalBakeData *)bake_data;
1012 float uv[2];
1013 const float *st0, *st1, *st2, *st3;
1014 int pixel = ibuf->x * y + x;
1015 float n[3], vec[3], tmp[3] = {0.5, 0.5, 0.5};
1016
1017 /* ideally we would work on triangles only, however, we rely on quads to get orthogonal
1018 * coordinates for use in grid space (triangle barycentric is not orthogonal) */
1019 if (face.size() == 4) {
1020 st0 = uv_map[face[0]];
1021 st1 = uv_map[face[1]];
1022 st2 = uv_map[face[2]];
1023 st3 = uv_map[face[3]];
1024 resolve_quad_uv_v2(uv, st, st0, st1, st2, st3);
1025 }
1026 else {
1027 st0 = uv_map[tri[0]];
1028 st1 = uv_map[tri[1]];
1029 st2 = uv_map[tri[2]];
1030 resolve_tri_uv_v2(uv, st, st0, st1, st2);
1031 }
1032
1033 clamp_v2(uv, 0.0f, 1.0f);
1034
1036 faces, hires_dm, normal_data->orig_index_mp_to_orig, lvl, face_i, uv[0], uv[1], nullptr, n);
1037
1038 mul_v3_m3v3(vec, tangmat, n);
1039 normalize_v3_length(vec, 0.5);
1040 add_v3_v3(vec, tmp);
1041
1042 if (ibuf->float_buffer.data) {
1043 float *rrgbf = ibuf->float_buffer.data + pixel * 4;
1044 rrgbf[0] = vec[0];
1045 rrgbf[1] = vec[1];
1046 rrgbf[2] = vec[2];
1047 rrgbf[3] = 1.0f;
1048 }
1049 else {
1050 uchar *rrgb = ibuf->byte_buffer.data + pixel * 4;
1051 rgb_float_to_uchar(rrgb, vec);
1052 rrgb[3] = 255;
1053 }
1054}
1055
1056/* TODO: restore ambient occlusion baking support, using BLI BVH? */
1057#if 0
1058/* **************** Ambient Occlusion Baker **************** */
1059
1060/* Must be a power of two. */
1061# define MAX_NUMBER_OF_AO_RAYS 1024
1062
1063static ushort ao_random_table_1[MAX_NUMBER_OF_AO_RAYS];
1064static ushort ao_random_table_2[MAX_NUMBER_OF_AO_RAYS];
1065
1066static void init_ao_random()
1067{
1068 int i;
1069
1070 for (i = 0; i < MAX_NUMBER_OF_AO_RAYS; i++) {
1071 ao_random_table_1[i] = rand() & 0xffff;
1072 ao_random_table_2[i] = rand() & 0xffff;
1073 }
1074}
1075
1076static ushort get_ao_random1(const int i)
1077{
1078 return ao_random_table_1[i & (MAX_NUMBER_OF_AO_RAYS - 1)];
1079}
1080
1081static ushort get_ao_random2(const int i)
1082{
1083 return ao_random_table_2[i & (MAX_NUMBER_OF_AO_RAYS - 1)];
1084}
1085
1086static void build_permutation_table(ushort permutation[],
1087 ushort temp_permutation[],
1088 const int number_of_rays,
1089 const int is_first_perm_table)
1090{
1091 int i, k;
1092
1093 for (i = 0; i < number_of_rays; i++) {
1094 temp_permutation[i] = i;
1095 }
1096
1097 for (i = 0; i < number_of_rays; i++) {
1098 const uint nr_entries_left = number_of_rays - i;
1099 ushort rnd = is_first_perm_table != false ? get_ao_random1(i) : get_ao_random2(i);
1100 const ushort entry = rnd % nr_entries_left;
1101
1102 /* pull entry */
1103 permutation[i] = temp_permutation[entry];
1104
1105 /* delete entry */
1106 for (k = entry; k < nr_entries_left - 1; k++) {
1107 temp_permutation[k] = temp_permutation[k + 1];
1108 }
1109 }
1110
1111 /* verify permutation table
1112 * every entry must appear exactly once
1113 */
1114# if 0
1115 for (i = 0; i < number_of_rays; i++)
1116 temp_permutation[i] = 0;
1117 for (i = 0; i < number_of_rays; i++)
1118 ++temp_permutation[permutation[i]];
1119 for (i = 0; i < number_of_rays; i++)
1120 BLI_assert(temp_permutation[i] == 1);
1121# endif
1122}
1123
1124static void create_ao_raytree(MultiresBakeRender *bkr, MAOBakeData *ao_data)
1125{
1126 DerivedMesh *hidm = bkr->hires_dm;
1127 RayObject *raytree;
1128 RayFace *face;
1129 CCGElem **grid_data;
1130 CCGKey key;
1131 int grids_num, grid_size /*, face_side */, faces_num;
1132 int i;
1133
1134 grids_num = hidm->getNumGrids(hidm);
1135 grid_size = hidm->getGridSize(hidm);
1136 grid_data = hidm->getGridData(hidm);
1137 hidm->getGridKey(hidm, &key);
1138
1139 // face_side = (grid_size << 1) - 1; /* UNUSED */
1140 faces_num = grids_num * (grid_size - 1) * (grid_size - 1);
1141
1142 raytree = ao_data->raytree = RE_rayobject_create(
1143 bkr->raytrace_structure, faces_num, bkr->octree_resolution);
1144 face = ao_data->rayfaces = MEM_calloc_arrayN<RayFace>(faces_num,
1145 "ObjectRen faces");
1146
1147 for (i = 0; i < grids_num; i++) {
1148 int x, y;
1149 for (x = 0; x < grid_size - 1; x++) {
1150 for (y = 0; y < grid_size - 1; y++) {
1151 float co[4][3];
1152
1153 copy_v3_v3(co[0], CCG_grid_elem_co(&key, grid_data[i], x, y));
1154 copy_v3_v3(co[1], CCG_grid_elem_co(&key, grid_data[i], x, y + 1));
1155 copy_v3_v3(co[2], CCG_grid_elem_co(&key, grid_data[i], x + 1, y + 1));
1156 copy_v3_v3(co[3], CCG_grid_elem_co(&key, grid_data[i], x + 1, y));
1157
1158 RE_rayface_from_coords(face, ao_data, face, co[0], co[1], co[2], co[3]);
1159 RE_rayobject_add(raytree, RE_rayobject_unalignRayFace(face));
1160
1161 face++;
1162 }
1163 }
1164 }
1165
1166 RE_rayobject_done(raytree);
1167}
1168
1169static void *init_ao_data(MultiresBakeRender *bkr, ImBuf * /*ibuf*/)
1170{
1171 MAOBakeData *ao_data;
1172 DerivedMesh *lodm = bkr->lores_dm;
1173 ushort *temp_permutation_table;
1174
1175 init_ao_random();
1176
1177 ao_data = MEM_callocN<MAOBakeData>("MultiresBake aoData");
1178
1179 ao_data->number_of_rays = bkr->number_of_rays;
1180 ao_data->bias = bkr->bias;
1181
1182 ao_data->orig_index_mp_to_orig = lodm->getPolyDataArray(lodm, CD_ORIGINDEX);
1183
1184 create_ao_raytree(bkr, ao_data);
1185
1186 /* initialize permutation tables */
1187 ao_data->permutation_table_1 = MEM_calloc_arrayN<ushort>(bkr->number_of_rays, "multires AO baker perm1");
1188 ao_data->permutation_table_2 = MEM_calloc_arrayN<ushort>(bkr->number_of_rays, "multires AO baker perm2");
1189 temp_permutation_table = MEM_calloc_arrayN<ushort>(bkr->number_of_rays, "multires AO baker temp perm");
1190
1191 build_permutation_table(
1192 ao_data->permutation_table_1, temp_permutation_table, bkr->number_of_rays, 1);
1193 build_permutation_table(
1194 ao_data->permutation_table_2, temp_permutation_table, bkr->number_of_rays, 0);
1195
1196 MEM_freeN(temp_permutation_table);
1197
1198 return (void *)ao_data;
1199}
1200
1201static void free_ao_data(void *bake_data)
1202{
1203 MAOBakeData *ao_data = (MAOBakeData *)bake_data;
1204
1205 RE_rayobject_free(ao_data->raytree);
1206 MEM_freeN(ao_data->rayfaces);
1207
1208 MEM_freeN(ao_data->permutation_table_1);
1209 MEM_freeN(ao_data->permutation_table_2);
1210
1211 MEM_freeN(ao_data);
1212}
1213
1214/* builds an X and a Y axis from the given Z axis */
1215static void build_coordinate_frame(float axisX[3], float axisY[3], const float axisZ[3])
1216{
1217 const float faX = fabsf(axisZ[0]);
1218 const float faY = fabsf(axisZ[1]);
1219 const float faZ = fabsf(axisZ[2]);
1220
1221 if (faX <= faY && faX <= faZ) {
1222 const float len = sqrtf(axisZ[1] * axisZ[1] + axisZ[2] * axisZ[2]);
1223 axisY[0] = 0;
1224 axisY[1] = axisZ[2] / len;
1225 axisY[2] = -axisZ[1] / len;
1226 cross_v3_v3v3(axisX, axisY, axisZ);
1227 }
1228 else if (faY <= faZ) {
1229 const float len = sqrtf(axisZ[0] * axisZ[0] + axisZ[2] * axisZ[2]);
1230 axisX[0] = axisZ[2] / len;
1231 axisX[1] = 0;
1232 axisX[2] = -axisZ[0] / len;
1233 cross_v3_v3v3(axisY, axisZ, axisX);
1234 }
1235 else {
1236 const float len = sqrtf(axisZ[0] * axisZ[0] + axisZ[1] * axisZ[1]);
1237 axisX[0] = axisZ[1] / len;
1238 axisX[1] = -axisZ[0] / len;
1239 axisX[2] = 0;
1240 cross_v3_v3v3(axisY, axisZ, axisX);
1241 }
1242}
1243
1244/* return false if nothing was hit and true otherwise */
1245static int trace_ao_ray(MAOBakeData *ao_data, float ray_start[3], float ray_direction[3])
1246{
1247 Isect isect = {{0}};
1248
1249 isect.dist = RE_RAYTRACE_MAXDIST;
1250 copy_v3_v3(isect.start, ray_start);
1251 copy_v3_v3(isect.dir, ray_direction);
1252 isect.lay = -1;
1253
1254 normalize_v3(isect.dir);
1255
1256 return RE_rayobject_raycast(ao_data->raytree, &isect);
1257}
1258
1259static void apply_ao_callback(DerivedMesh *lores_dm,
1260 DerivedMesh *hires_dm,
1261 void * /*thread_data*/,
1262 void *bake_data,
1263 ImBuf *ibuf,
1264 const int tri_index,
1265 const int lvl,
1266 const float st[2],
1267 float /*tangmat[3][3]*/,
1268 const int x,
1269 const int y)
1270{
1271 const blender::int3 &tri = lores_dm->getcorner_triArray(lores_dm) + tri_index;
1272 float(*mloopuv)[2] = lores_dm->getLoopDataArray(lores_dm, CD_PROP_FLOAT2);
1273 MAOBakeData *ao_data = (MAOBakeData *)bake_data;
1274
1275 int i, k, perm_ofs;
1276 float pos[3], nrm[3];
1277 float cen[3];
1278 float axisX[3], axisY[3], axisZ[3];
1279 float shadow = 0;
1280 float value;
1281 int pixel = ibuf->x * y + x;
1282 float uv[2], *st0, *st1, *st2, *st3;
1283
1284 /* ideally we would work on triangles only, however, we rely on quads to get orthogonal
1285 * coordinates for use in grid space (triangle barycentric is not orthogonal) */
1286 if (face.size() == 4) {
1287 st0 = mloopuv[face[0]];
1288 st1 = mloopuv[face[1]];
1289 st2 = mloopuv[face[2]];
1290 st3 = mloopuv[face[3]];
1291 resolve_quad_uv_v2(uv, st, st0, st1, st2, st3);
1292 }
1293 else {
1294 st0 = mloopuv[tri[0]];
1295 st1 = mloopuv[tri[1]];
1296 st2 = mloopuv[tri[2]];
1297 resolve_tri_uv_v2(uv, st, st0, st1, st2);
1298 }
1299
1300 clamp_v2(uv, 0.0f, 1.0f);
1301
1303 lores_dm, hires_dm, ao_data->orig_index_mp_to_orig, lvl, tri, uv[0], uv[1], pos, nrm);
1304
1305 /* offset ray origin by user bias along normal */
1306 for (i = 0; i < 3; i++) {
1307 cen[i] = pos[i] + ao_data->bias * nrm[i];
1308 }
1309
1310 /* build tangent frame */
1311 for (i = 0; i < 3; i++) {
1312 axisZ[i] = nrm[i];
1313 }
1314
1315 build_coordinate_frame(axisX, axisY, axisZ);
1316
1317 /* static noise */
1318 perm_ofs = (get_ao_random2(get_ao_random1(x) + y)) & (MAX_NUMBER_OF_AO_RAYS - 1);
1319
1320 /* importance sample shadow rays (cosine weighted) */
1321 for (i = 0; i < ao_data->number_of_rays; i++) {
1322 int hit_something;
1323
1324 /* use N-Rooks to distribute our N ray samples across
1325 * a multi-dimensional domain (2D)
1326 */
1327 const ushort I = ao_data->permutation_table_1[(i + perm_ofs) % ao_data->number_of_rays];
1328 const ushort J = ao_data->permutation_table_2[i];
1329
1330 const float JitPh = (get_ao_random2(I + perm_ofs) & (MAX_NUMBER_OF_AO_RAYS - 1)) /
1331 float(MAX_NUMBER_OF_AO_RAYS);
1332 const float JitTh = (get_ao_random1(J + perm_ofs) & (MAX_NUMBER_OF_AO_RAYS - 1)) /
1333 float(MAX_NUMBER_OF_AO_RAYS);
1334 const float SiSqPhi = (I + JitPh) / ao_data->number_of_rays;
1335 const float Theta = float(2 * M_PI) * ((J + JitTh) / ao_data->number_of_rays);
1336
1337 /* this gives results identical to the so-called cosine
1338 * weighted distribution relative to the north pole.
1339 */
1340 float SiPhi = sqrtf(SiSqPhi);
1341 float CoPhi = SiSqPhi < 1.0f ? sqrtf(1.0f - SiSqPhi) : 0;
1342 float CoThe = cosf(Theta);
1343 float SiThe = sinf(Theta);
1344
1345 const float dx = CoThe * CoPhi;
1346 const float dy = SiThe * CoPhi;
1347 const float dz = SiPhi;
1348
1349 /* transform ray direction out of tangent frame */
1350 float dv[3];
1351 for (k = 0; k < 3; k++) {
1352 dv[k] = axisX[k] * dx + axisY[k] * dy + axisZ[k] * dz;
1353 }
1354
1355 hit_something = trace_ao_ray(ao_data, cen, dv);
1356
1357 if (hit_something != 0) {
1358 shadow += 1;
1359 }
1360 }
1361
1362 value = 1.0f - (shadow / ao_data->number_of_rays);
1363
1364 if (ibuf->rect_float) {
1365 float *rrgbf = ibuf->rect_float + pixel * 4;
1366 rrgbf[0] = rrgbf[1] = rrgbf[2] = value;
1367 rrgbf[3] = 1.0f;
1368 }
1369 else {
1370 uchar *rrgb = (uchar *)ibuf->rect + pixel * 4;
1371 rrgb[0] = rrgb[1] = rrgb[2] = unit_float_to_uchar_clamp(value);
1372 rrgb[3] = 255;
1373 }
1374}
1375#endif
1376
1377/* ******$***************** Post processing ************************* */
1378
1379static void bake_ibuf_filter(ImBuf *ibuf,
1380 char *mask,
1381 const int margin,
1382 const char margin_type,
1383 DerivedMesh *dm,
1384 const float uv_offset[2])
1385{
1386 /* must check before filtering */
1387 const bool is_new_alpha = (ibuf->planes != R_IMF_PLANES_RGBA) && BKE_imbuf_alpha_test(ibuf);
1388
1389 if (margin) {
1390 switch (margin_type) {
1392 RE_generate_texturemargin_adjacentfaces_dm(ibuf, mask, margin, dm, uv_offset);
1393 break;
1394 default:
1395 /* fall through */
1396 case R_BAKE_EXTEND:
1397 IMB_filter_extend(ibuf, mask, margin);
1398 break;
1399 }
1400 }
1401
1402 /* if the bake results in new alpha then change the image setting */
1403 if (is_new_alpha) {
1404 ibuf->planes = R_IMF_PLANES_RGBA;
1405 }
1406 else {
1407 if (margin && ibuf->planes != R_IMF_PLANES_RGBA) {
1408 /* clear alpha added by filtering */
1409 IMB_rectfill_alpha(ibuf, 1.0f);
1410 }
1411 }
1412}
1413
1415 const float *displacement,
1416 const char *mask,
1417 float displacement_min,
1418 float displacement_max)
1419{
1420 const float *current_displacement = displacement;
1421 const char *current_mask = mask;
1422 float max_distance;
1423
1424 max_distance = max_ff(fabsf(displacement_min), fabsf(displacement_max));
1425
1426 const size_t ibuf_pixel_count = IMB_get_pixel_count(ibuf);
1427 for (size_t i = 0; i < ibuf_pixel_count; i++) {
1428 if (*current_mask == FILTER_MASK_USED) {
1429 float normalized_displacement;
1430
1431 if (max_distance > 1e-5f) {
1432 normalized_displacement = (*current_displacement + max_distance) / (max_distance * 2);
1433 }
1434 else {
1435 normalized_displacement = 0.5f;
1436 }
1437
1438 if (ibuf->float_buffer.data) {
1439 /* currently baking happens to RGBA only */
1440 float *fp = ibuf->float_buffer.data + i * 4;
1441 fp[0] = fp[1] = fp[2] = normalized_displacement;
1442 fp[3] = 1.0f;
1443 }
1444
1445 if (ibuf->byte_buffer.data) {
1446 uchar *cp = ibuf->byte_buffer.data + 4 * i;
1447 cp[0] = cp[1] = cp[2] = unit_float_to_uchar_clamp(normalized_displacement);
1448 cp[3] = 255;
1449 }
1450 }
1451
1452 current_displacement++;
1453 current_mask++;
1454 }
1455}
1456
1457/* **************** Common functions public API relates on **************** */
1458
1460{
1462 bkr->tot_image = 0;
1463
1464 for (int i = 0; i < bkr->ob_image.len; i++) {
1465 Image *ima = bkr->ob_image.array[i];
1466 if (ima) {
1467 ima->id.tag &= ~ID_TAG_DOIT;
1468 }
1469 }
1470
1471 for (int i = 0; i < bkr->ob_image.len; i++) {
1472 Image *ima = bkr->ob_image.array[i];
1473 if (ima) {
1474 if ((ima->id.tag & ID_TAG_DOIT) == 0) {
1476 BLI_addtail(&bkr->image, data);
1477 bkr->tot_image++;
1478 ima->id.tag |= ID_TAG_DOIT;
1479 }
1480 }
1481 }
1482
1483 for (int i = 0; i < bkr->ob_image.len; i++) {
1484 Image *ima = bkr->ob_image.array[i];
1485 if (ima) {
1486 ima->id.tag &= ~ID_TAG_DOIT;
1487 }
1488 }
1489}
1490
1492{
1493 /* construct bake result */
1494 result->height_min = FLT_MAX;
1495 result->height_max = -FLT_MAX;
1496
1497 LISTBASE_FOREACH (LinkData *, link, &bkr->image) {
1498 Image *ima = (Image *)link->data;
1499
1500 LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
1501 ImageUser iuser;
1502 BKE_imageuser_default(&iuser);
1503 iuser.tile = tile->tile_number;
1504
1505 ImBuf *ibuf = BKE_image_acquire_ibuf(ima, &iuser, nullptr);
1506
1507 if (ibuf->x > 0 && ibuf->y > 0) {
1508 BakeImBufuserData *userdata = MEM_callocN<BakeImBufuserData>("MultiresBake userdata");
1509 userdata->mask_buffer = MEM_calloc_arrayN<char>(size_t(ibuf->y) * size_t(ibuf->x),
1510 "MultiresBake imbuf mask");
1511 ibuf->userdata = userdata;
1512
1513 switch (bkr->mode) {
1514 case RE_BAKE_NORMALS:
1515 do_multires_bake(bkr,
1516 ima,
1517 tile,
1518 ibuf,
1519 true,
1523 result);
1524 break;
1526 do_multires_bake(bkr,
1527 ima,
1528 tile,
1529 ibuf,
1530 false,
1534 result);
1535 break;
1536 /* TODO: restore ambient occlusion baking support. */
1537#if 0
1538 case RE_BAKE_AO:
1539 do_multires_bake(bkr,
1540 ima,
1541 tile,
1542 ibuf,
1543 false,
1544 apply_ao_callback,
1545 init_ao_data,
1546 free_ao_data,
1547 result);
1548 break;
1549#endif
1550 }
1551 }
1552
1553 BKE_image_release_ibuf(ima, ibuf, nullptr);
1554 }
1555
1556 ima->id.tag |= ID_TAG_DOIT;
1557 }
1558}
1559
1561{
1562 bool use_displacement_buffer = bkr->mode == RE_BAKE_DISPLACEMENT;
1563
1564 LISTBASE_FOREACH (LinkData *, link, &bkr->image) {
1565 Image *ima = (Image *)link->data;
1566
1567 LISTBASE_FOREACH (ImageTile *, tile, &ima->tiles) {
1568 ImageUser iuser;
1569 BKE_imageuser_default(&iuser);
1570 iuser.tile = tile->tile_number;
1571
1572 ImBuf *ibuf = BKE_image_acquire_ibuf(ima, &iuser, nullptr);
1573 BakeImBufuserData *userdata = (BakeImBufuserData *)ibuf->userdata;
1574
1575 if (ibuf->x <= 0 || ibuf->y <= 0) {
1576 continue;
1577 }
1578
1579 if (use_displacement_buffer) {
1581 userdata->displacement_buffer,
1582 userdata->mask_buffer,
1583 result->height_min,
1584 result->height_max);
1585 }
1586
1587 float uv_offset[2];
1588 BKE_image_get_tile_uv(ima, tile->tile_number, uv_offset);
1589
1590 bake_ibuf_filter(ibuf,
1591 userdata->mask_buffer,
1592 bkr->bake_margin,
1593 bkr->bake_margin_type,
1594 bkr->lores_dm,
1595 uv_offset);
1596
1598 BKE_image_mark_dirty(ima, ibuf);
1599
1600 if (ibuf->float_buffer.data) {
1601 ibuf->userflags |= IB_RECT_INVALID;
1602 }
1603
1604 if (ibuf->mipmap[0]) {
1606 IMB_free_mipmaps(ibuf);
1607 }
1608
1609 if (ibuf->userdata) {
1610 if (userdata->displacement_buffer) {
1611 MEM_freeN(userdata->displacement_buffer);
1612 }
1613
1614 MEM_freeN(userdata->mask_buffer);
1615 MEM_freeN(userdata);
1616 ibuf->userdata = nullptr;
1617 }
1618
1619 BKE_image_release_ibuf(ima, ibuf, nullptr);
1620 DEG_id_tag_update(&ima->id, 0);
1621 }
1622 }
1623}
1624
1626{
1628
1629 count_images(bkr);
1630 bake_images(bkr, &result);
1631 finish_images(bkr, &result);
1632}
blender::float3 & CCG_grid_elem_no(const CCGKey &key, CCGElem *elem, int x, int y)
Definition BKE_ccg.hh:93
blender::float3 & CCG_grid_elem_co(const CCGKey &key, CCGElem *elem, int x, int y)
Definition BKE_ccg.hh:88
CustomData interface, see also DNA_customdata_types.h.
const void * CustomData_get_layer_named(const CustomData *data, eCustomDataType type, blender::StringRef name)
int CustomData_get_layer_index(const CustomData *data, eCustomDataType type)
ImBuf * BKE_image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock)
void BKE_image_mark_dirty(Image *image, ImBuf *ibuf)
void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
void BKE_image_get_tile_uv(const Image *ima, const int tile_number, float r_uv[2])
bool BKE_imbuf_alpha_test(ImBuf *ibuf)
void BKE_imageuser_default(ImageUser *iuser)
void BKE_id_free(Main *bmain, void *idv)
Mesh * BKE_mesh_new_nomain(int verts_num, int edges_num, int faces_num, int corners_num)
void * DM_get_loop_data_layer(DerivedMesh *dm, eCustomDataType type)
void BKE_mesh_calc_loop_tangent_ex(blender::Span< blender::float3 > vert_positions, blender::OffsetIndices< int > faces, blender::Span< int > corner_verts, blender::Span< blender::int3 > corner_tris, blender::Span< int > corner_tri_faces, blender::Span< bool > sharp_faces, const CustomData *loopdata, bool calc_active_tangent, const char(*tangent_names)[MAX_CUSTOMDATA_LAYER_NAME], int tangent_names_len, blender::Span< blender::float3 > vert_normals, blender::Span< blender::float3 > face_normals, blender::Span< blender::float3 > corner_normals, blender::Span< blender::float3 > vert_orco, CustomData *loopdata_out, uint loopdata_out_len, short *tangent_mask_curr_p)
int mdisp_rot_face_to_crn(int face_size, int face_side, float u, float v, float *x, float *y)
Definition multires.cc:1503
SubsurfFlags
DerivedMesh * subsurf_make_derived_from_derived(DerivedMesh *dm, SubsurfModifierData *smd, const Scene *scene, float(*vertCos)[3], SubsurfFlags flags)
#define BLI_assert(a)
Definition BLI_assert.h:46
LinkData * BLI_genericNodeN(void *data)
Definition listbase.cc:922
#define LISTBASE_FOREACH(type, var, list)
BLI_INLINE void BLI_listbase_clear(ListBase *lb)
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:111
int BLI_listbase_count(const ListBase *listbase) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:524
MINLINE float max_ff(float a, float b)
MINLINE float min_ff(float a, float b)
void rgb_float_to_uchar(unsigned char r_col[3], const float col_f[3])
#define M_PI
void resolve_tri_uv_v2(float r_uv[2], const float st[2], const float st0[2], const float st1[2], const float st2[2])
void resolve_quad_uv_v2(float r_uv[2], const float st[2], const float st0[2], const float st1[2], const float st2[2], const float st3[2])
void interp_barycentric_tri_v3(float data[3][3], float u, float v, float res[3])
void interp_bilinear_quad_v3(float data[4][3], float u, float v, float res[3])
bool invert_m3_m3(float inverse[3][3], const float mat[3][3])
void zero_m3(float m[3][3])
void mul_v3_m3v3(float r[3], const float M[3][3], const float a[3])
MINLINE void sub_v3_v3v3(float r[3], const float a[3], const float b[3])
MINLINE void mul_v3_fl(float r[3], float f)
MINLINE void copy_v3_v3(float r[3], const float a[3])
MINLINE float dot_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT
MINLINE void cross_v3_v3v3(float r[3], const float a[3], const float b[3])
MINLINE void clamp_v2(float vec[2], float min, float max)
MINLINE void sub_v2_v2v2(float r[2], const float a[2], const float b[2])
MINLINE void add_v3_v3(float r[3], const float a[3])
MINLINE float normalize_v3_length(float n[3], float unit_length)
MINLINE float normalize_v3(float n[3])
unsigned char uchar
unsigned int uint
unsigned short ushort
pthread_spinlock_t SpinLock
void BLI_threadpool_init(struct ListBase *threadbase, void *(*do_thread)(void *), int tot)
Definition threads.cc:121
int BLI_system_thread_count(void)
Definition threads.cc:253
void BLI_threadpool_end(struct ListBase *threadbase)
Definition threads.cc:234
void BLI_spin_init(SpinLock *spin)
Definition threads.cc:391
void BLI_spin_unlock(SpinLock *spin)
Definition threads.cc:430
void BLI_spin_lock(SpinLock *spin)
Definition threads.cc:405
void BLI_threadpool_insert(struct ListBase *threadbase, void *callerdata)
Definition threads.cc:184
void BLI_spin_end(SpinLock *spin)
Definition threads.cc:445
#define CLAMP(a, b, c)
void DEG_id_tag_update(ID *id, unsigned int flags)
@ ID_TAG_DOIT
Definition DNA_ID.h:944
@ CD_PROP_INT32
@ CD_PROP_FLOAT2
@ SUBSURF_UV_SMOOTH_PRESERVE_BOUNDARIES
@ R_BAKE_ADJACENT_FACES
@ R_BAKE_EXTEND
@ R_IMF_PLANES_RGBA
void IMB_rectfill_alpha(ImBuf *ibuf, float value)
Definition rectop.cc:1195
#define FILTER_MASK_USED
Definition IMB_imbuf.hh:297
size_t IMB_get_pixel_count(const ImBuf *ibuf)
Get the length of the data of the given image buffer in pixels.
void IMB_free_mipmaps(ImBuf *ibuf)
void IMB_filter_extend(ImBuf *ibuf, char *mask, int filter)
Definition filter.cc:317
@ IB_RECT_INVALID
@ IB_MIPMAP_INVALID
@ IB_DISPLAY_BUFFER_INVALID
Read Guarded memory(de)allocation.
#define RE_BAKE_AO
#define RE_BAKE_NORMALS
#define RE_BAKE_DISPLACEMENT
bool do_update
Definition WM_types.hh:1008
BMesh const char void * data
ATTR_WARN_UNUSED_RESULT const BMVert * v
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
Definition btDbvt.cpp:52
SIMD_FORCE_INLINE const btScalar & w() const
Return the w value.
Definition btQuadWord.h:119
constexpr int64_t size() const
Definition BLI_span.hh:252
static VArray ForSpan(Span< T > values)
constexpr int64_t size() const
bool add(const StringRef attribute_id, const AttrDomain domain, const eCustomDataType data_type, const AttributeInit &initializer)
#define sinf(x)
#define cosf(x)
#define ceilf(x)
#define fabsf(x)
#define sqrtf(x)
uint pos
uint col
constexpr T sign(T) RET
const ccl_global KernelWorkTile * tile
void * MEM_calloc_arrayN(size_t len, size_t size, const char *str)
Definition mallocn.cc:123
void * MEM_callocN(size_t len, const char *str)
Definition mallocn.cc:118
void MEM_freeN(void *vmemh)
Definition mallocn.cc:113
MINLINE unsigned char unit_float_to_uchar_clamp(float val)
ccl_device_inline float2 mask(const MaskType mask, const float2 a)
static char faces[256]
#define G(x, y, z)
static void apply_heights_callback(const blender::Span< blender::float3 > vert_positions, const blender::Span< blender::float3 > vert_normals, const blender::OffsetIndices< int > faces, const blender::Span< int > corner_verts, const blender::Span< blender::int3 > corner_tris, const blender::Span< int > tri_faces, const blender::Span< blender::float2 > uv_map, DerivedMesh *hires_dm, void *thread_data_v, void *bake_data, ImBuf *ibuf, const int tri_index, const int lvl, const float st[2], float[3][3], const int x, const int y)
static void * init_normal_data(MultiresBakeRender *bkr, ImBuf *)
static void * init_heights_data(MultiresBakeRender *bkr, ImBuf *ibuf)
static int multiresbake_test_break(MultiresBakeRender *bkr)
void(*)(void *bake_data) MFreeBakeData
static void rasterize_half(const MBakeRast *bake_rast, const float s0_s, const float t0_s, const float s1_s, const float t1_s, const float s0_l, const float t0_l, const float s1_l, const float t1_l, const int y0_in, const int y1_in, const int is_mid_right)
static void bake_ibuf_normalize_displacement(ImBuf *ibuf, const float *displacement, const char *mask, float displacement_min, float displacement_max)
static void bake_images(MultiresBakeRender *bkr, MultiresBakeResult *result)
static void count_images(MultiresBakeRender *bkr)
static void interp_bilinear_mpoly(const blender::Span< blender::float3 > vert_positions, const blender::Span< blender::float3 > vert_normals, const blender::Span< int > corner_verts, const blender::IndexRange face, const float u, const float v, const int mode, float res[3])
static void finish_images(MultiresBakeRender *bkr, MultiresBakeResult *result)
static void multiresbake_get_normal(const MResolvePixelData *data, const int tri_num, const int vert_index, float r_normal[3])
static void init_ccgdm_arrays(DerivedMesh *dm)
static void set_rast_triangle(const MBakeRast *bake_rast, const int x, const int y)
static void get_ccgdm_data(const blender::OffsetIndices< int > lores_polys, DerivedMesh *hidm, const int *index_mp_to_orig, const int lvl, const int face_index, const float u, const float v, float co[3], float n[3])
void *(*)(MultiresBakeRender *bkr, ImBuf *ibuf) MInitBakeData
void(*)(const MResolvePixelData *data, const int x, const int y) MFlushPixel
static void * do_multires_bake_thread(void *data_v)
void(*)(blender::Span< blender::float3 > vert_positions, blender::Span< blender::float3 > vert_normals, blender::OffsetIndices< int > faces, blender::Span< int > corner_verts, blender::Span< blender::int3 > corner_tris, blender::Span< int > tri_faces, blender::Span< blender::float2 > uv_map, DerivedMesh *hires_dm, void *thread_data, void *bake_data, ImBuf *ibuf, const int face_index, const int lvl, const float st[2], float tangmat[3][3], const int x, const int y) MPassKnownData
static void free_normal_data(void *bake_data)
static void bake_rasterize(const MBakeRast *bake_rast, const float st0_in[2], const float st1_in[2], const float st2_in[2])
void RE_multires_bake_images(MultiresBakeRender *bkr)
static int multires_bake_queue_next_tri(MultiresBakeQueue *queue)
static void flush_pixel(const MResolvePixelData *data, const int x, const int y)
static void init_bake_rast(MBakeRast *bake_rast, const ImBuf *ibuf, const MResolvePixelData *data, MFlushPixel flush_pixel, bool *do_update)
static void interp_barycentric_corner_tri(const blender::Span< blender::float3 > vert_positions, const blender::Span< blender::float3 > vert_normals, const blender::Span< int > corner_verts, const blender::int3 &corner_tri, const float u, const float v, const int mode, float res[3])
static void bake_ibuf_filter(ImBuf *ibuf, char *mask, const int margin, const char margin_type, DerivedMesh *dm, const float uv_offset[2])
static void free_heights_data(void *bake_data)
static void do_multires_bake(MultiresBakeRender *bkr, Image *ima, ImageTile *tile, ImBuf *ibuf, bool require_tangent, MPassKnownData passKnownData, MInitBakeData initBakeData, MFreeBakeData freeBakeData, MultiresBakeResult *result)
static void interp_bilinear_grid(const CCGKey &key, CCGElem *grid, float crn_x, float crn_y, int mode, float res[3])
static void apply_tangmat_callback(const blender::Span< blender::float3 >, const blender::Span< blender::float3 >, const blender::OffsetIndices< int > faces, const blender::Span< int >, const blender::Span< blender::int3 > corner_tris, const blender::Span< int > tri_faces, const blender::Span< blender::float2 > uv_map, DerivedMesh *hires_dm, void *, void *bake_data, ImBuf *ibuf, const int tri_index, const int lvl, const float st[2], float tangmat[3][3], const int x, const int y)
VecBase< int32_t, 3 > int3
#define I
#define FLT_MAX
Definition stdcycles.h:14
int grid_size
Definition BKE_ccg.hh:33
int(* getGridSize)(DerivedMesh *dm)
int *(* getPolyArray)(DerivedMesh *dm)
int(* getNumVerts)(DerivedMesh *dm)
int *(* getCornerVertArray)(DerivedMesh *dm)
void *(* getPolyDataArray)(DerivedMesh *dm, eCustomDataType type)
int(* getNumPolys)(DerivedMesh *dm)
int(* getNumEdges)(DerivedMesh *dm)
void *(* getVertDataArray)(DerivedMesh *dm, eCustomDataType type)
int(* getNumGrids)(DerivedMesh *dm)
float *(* getVertArray)(DerivedMesh *dm)
int *(* getGridOffset)(DerivedMesh *dm)
void *(* getLoopDataArray)(DerivedMesh *dm, eCustomDataType type)
blender::int2 *(* getEdgeArray)(DerivedMesh *dm)
CCGElem **(* getGridData)(DerivedMesh *dm)
int *(* getCornerEdgeArray)(DerivedMesh *dm)
void(* release)(DerivedMesh *dm)
void(* getGridKey)(DerivedMesh *dm, CCGKey *key)
int(* getNumLoops)(DerivedMesh *dm)
int tag
Definition DNA_ID.h:424
void * userdata
ImBufFloatBuffer float_buffer
ImBufByteBuffer byte_buffer
unsigned char planes
ImBuf * mipmap[IMB_MIPMAP_LEVELS]
ListBase tiles
bool * do_update
MFlushPixel flush_pixel
const MResolvePixelData * data
DerivedMesh * ssdm
const int * orig_index_mp_to_orig
const int * orig_index_mp_to_orig
const int * material_indices
blender::Span< blender::float3 > vert_positions
blender::Span< blender::float3 > face_normals
blender::OffsetIndices< int > faces
blender::Span< blender::float2 > uv_map
blender::Span< blender::float3 > vert_normals
DerivedMesh * hires_dm
blender::Span< int > tri_faces
MPassKnownData pass_data
const bool * sharp_faces
blender::Span< blender::int3 > corner_tris
blender::Span< int > corner_verts
int corners_num
int edges_num
int faces_num
int verts_num
DerivedMesh * hires_dm
DerivedMesh * lores_dm
struct MultiresBakeRender::@002076177115351153010115240140303264177135230212 ob_image
MultiresBakeQueue * queue
MResolvePixelData data
MultiresBakeRender * bkr
i
Definition text_draw.cc:230
void RE_generate_texturemargin_adjacentfaces_dm(ImBuf *ibuf, char *mask, const int margin, DerivedMesh *dm, const float uv_offset[2])
uint len
ParamHandle ** handles