Cleanup: comments (long lines) in blenkernel
[blender.git] / source / blender / blenkernel / intern / multires_reshape.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software  Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2018 Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23
24 #include "MEM_guardedalloc.h"
25
26 #include "DNA_mesh_types.h"
27 #include "DNA_meshdata_types.h"
28 #include "DNA_scene_types.h"
29
30 #include "BLI_utildefines.h"
31 #include "BLI_math_vector.h"
32 #include "BLI_task.h"
33
34 #include "BKE_ccg.h"
35 #include "BKE_library.h"
36 #include "BKE_mesh.h"
37 #include "BKE_mesh_runtime.h"
38 #include "BKE_modifier.h"
39 #include "BKE_multires.h"
40 #include "BKE_subdiv.h"
41 #include "BKE_subdiv_ccg.h"
42 #include "BKE_subdiv_eval.h"
43 #include "BKE_subdiv_foreach.h"
44 #include "BKE_subdiv_mesh.h"
45
46 #include "DEG_depsgraph_query.h"
47
48 static void multires_reshape_init_mmd(MultiresModifierData *reshape_mmd,
49                                       const MultiresModifierData *mmd)
50 {
51   *reshape_mmd = *mmd;
52 }
53
54 static void multires_reshape_init_mmd_top_level(MultiresModifierData *reshape_mmd,
55                                                 const MultiresModifierData *mmd)
56 {
57   *reshape_mmd = *mmd;
58   reshape_mmd->lvl = reshape_mmd->totlvl;
59 }
60
61 /* =============================================================================
62  * General reshape implementation, reused by all particular cases.
63  */
64
65 typedef struct MultiresReshapeContext {
66   Subdiv *subdiv;
67   const Mesh *coarse_mesh;
68   MDisps *mdisps;
69   GridPaintMask *grid_paint_mask;
70   int top_grid_size;
71   int top_level;
72   /* Indexed by coarse face index, returns first ptex face index corresponding
73    * to that coarse face. */
74   int *face_ptex_offset;
75 } MultiresReshapeContext;
76
77 static void multires_reshape_allocate_displacement_grid(MDisps *displacement_grid, const int level)
78 {
79   const int grid_size = BKE_subdiv_grid_size_from_level(level);
80   const int grid_area = grid_size * grid_size;
81   float(*disps)[3] = MEM_calloc_arrayN(grid_area, 3 * sizeof(float), "multires disps");
82   if (displacement_grid->disps != NULL) {
83     MEM_freeN(displacement_grid->disps);
84   }
85   displacement_grid->disps = disps;
86   displacement_grid->totdisp = grid_area;
87   displacement_grid->level = level;
88 }
89
90 static void multires_reshape_ensure_displacement_grid(MDisps *displacement_grid, const int level)
91 {
92   if (displacement_grid->disps != NULL && displacement_grid->level == level) {
93     return;
94   }
95   multires_reshape_allocate_displacement_grid(displacement_grid, level);
96 }
97
98 static void multires_reshape_ensure_displacement_grids(Mesh *mesh, const int grid_level)
99 {
100   const int num_grids = mesh->totloop;
101   MDisps *mdisps = CustomData_get_layer(&mesh->ldata, CD_MDISPS);
102   for (int grid_index = 0; grid_index < num_grids; grid_index++) {
103     multires_reshape_ensure_displacement_grid(&mdisps[grid_index], grid_level);
104   }
105 }
106
107 static void multires_reshape_ensure_mask_grids(Mesh *mesh, const int grid_level)
108 {
109   GridPaintMask *grid_paint_masks = CustomData_get_layer(&mesh->ldata, CD_GRID_PAINT_MASK);
110   if (grid_paint_masks == NULL) {
111     return;
112   }
113   const int num_grids = mesh->totloop;
114   const int grid_size = BKE_subdiv_grid_size_from_level(grid_level);
115   const int grid_area = grid_size * grid_size;
116   for (int grid_index = 0; grid_index < num_grids; grid_index++) {
117     GridPaintMask *grid_paint_mask = &grid_paint_masks[grid_index];
118     if (grid_paint_mask->level == grid_level) {
119       continue;
120     }
121     grid_paint_mask->level = grid_level;
122     if (grid_paint_mask->data) {
123       MEM_freeN(grid_paint_mask->data);
124     }
125     grid_paint_mask->data = MEM_calloc_arrayN(grid_area, sizeof(float), "gpm.data");
126   }
127 }
128
129 static void multires_reshape_ensure_grids(Mesh *mesh, const int grid_level)
130 {
131   multires_reshape_ensure_displacement_grids(mesh, grid_level);
132   multires_reshape_ensure_mask_grids(mesh, grid_level);
133 }
134
135 /* Convert normalized coordinate within a grid to a normalized coordinate within
136  * a ptex face. */
137 static void multires_reshape_corner_coord_to_ptex(const MPoly *coarse_poly,
138                                                   const int corner,
139                                                   const float corner_u,
140                                                   const float corner_v,
141                                                   float *r_ptex_face_u,
142                                                   float *r_ptex_face_v)
143 {
144   if (coarse_poly->totloop == 4) {
145     float grid_u, grid_v;
146     BKE_subdiv_ptex_face_uv_to_grid_uv(corner_u, corner_v, &grid_u, &grid_v);
147     BKE_subdiv_rotate_grid_to_quad(corner, grid_u, grid_v, r_ptex_face_u, r_ptex_face_v);
148   }
149   else {
150     *r_ptex_face_u = corner_u;
151     *r_ptex_face_v = corner_v;
152   }
153 }
154
155 /* NOTE: The tangent vectors are measured in ptex face normalized coordinates,
156  * which is different from grid tangent. */
157 static void multires_reshape_sample_surface(Subdiv *subdiv,
158                                             const MPoly *coarse_poly,
159                                             const int corner,
160                                             const float corner_u,
161                                             const float corner_v,
162                                             const int ptex_face_index,
163                                             float r_P[3],
164                                             float r_dPdu[3],
165                                             float r_dPdv[3])
166 {
167   float ptex_face_u, ptex_face_v;
168   multires_reshape_corner_coord_to_ptex(
169       coarse_poly, corner, corner_u, corner_v, &ptex_face_u, &ptex_face_v);
170   BKE_subdiv_eval_limit_point_and_derivatives(
171       subdiv, ptex_face_index, ptex_face_u, ptex_face_v, r_P, r_dPdu, r_dPdv);
172 }
173
174 static void multires_reshape_tangent_matrix_for_corner(const MPoly *coarse_poly,
175                                                        const int coarse_corner,
176                                                        const float dPdu[3],
177                                                        const float dPdv[3],
178                                                        float r_tangent_matrix[3][3])
179 {
180   /* For a quad faces we would need to flip the tangent, since they will use
181    * use different coordinates within displacement grid comparent to ptex
182    * face. */
183   const bool is_quad = (coarse_poly->totloop == 4);
184   const int tangent_corner = is_quad ? coarse_corner : 0;
185   BKE_multires_construct_tangent_matrix(r_tangent_matrix, dPdu, dPdv, tangent_corner);
186 }
187
188 static void multires_reshape_vertex_from_final_data(MultiresReshapeContext *ctx,
189                                                     const int ptex_face_index,
190                                                     const float corner_u,
191                                                     const float corner_v,
192                                                     const int coarse_poly_index,
193                                                     const int coarse_corner,
194                                                     const float final_P[3],
195                                                     const float final_mask)
196 {
197   Subdiv *subdiv = ctx->subdiv;
198   const int grid_size = ctx->top_grid_size;
199   const Mesh *coarse_mesh = ctx->coarse_mesh;
200   const MPoly *coarse_mpoly = coarse_mesh->mpoly;
201   const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
202   const int loop_index = coarse_poly->loopstart + coarse_corner;
203   /* Evaluate limit surface. */
204   float P[3], dPdu[3], dPdv[3];
205   multires_reshape_sample_surface(
206       subdiv, coarse_poly, coarse_corner, corner_u, corner_v, ptex_face_index, P, dPdu, dPdv);
207   /* Construct tangent matrix which matches orientation of the current
208    * displacement grid. */
209   float tangent_matrix[3][3], inv_tangent_matrix[3][3];
210   multires_reshape_tangent_matrix_for_corner(
211       coarse_poly, coarse_corner, dPdu, dPdv, tangent_matrix);
212   invert_m3_m3(inv_tangent_matrix, tangent_matrix);
213   /* Convert object coordinate to a tangent space of displacement grid. */
214   float D[3];
215   sub_v3_v3v3(D, final_P, P);
216   float tangent_D[3];
217   mul_v3_m3v3(tangent_D, inv_tangent_matrix, D);
218   /* Calculate index of element within the grid. */
219   float grid_u, grid_v;
220   BKE_subdiv_ptex_face_uv_to_grid_uv(corner_u, corner_v, &grid_u, &grid_v);
221   const int grid_x = (grid_u * (grid_size - 1) + 0.5f);
222   const int grid_y = (grid_v * (grid_size - 1) + 0.5f);
223   const int index = grid_y * grid_size + grid_x;
224   /* Write tangent displacement. */
225   MDisps *displacement_grid = &ctx->mdisps[loop_index];
226   copy_v3_v3(displacement_grid->disps[index], tangent_D);
227   /* Write mask grid. */
228   if (ctx->grid_paint_mask != NULL) {
229     GridPaintMask *grid_paint_mask = &ctx->grid_paint_mask[loop_index];
230     BLI_assert(grid_paint_mask->level == displacement_grid->level);
231     grid_paint_mask->data[index] = final_mask;
232   }
233 }
234
235 /* =============================================================================
236  * Helpers to propagate displacement to higher levels.
237  */
238
239 typedef struct MultiresPropagateData {
240   /* Number of displacement grids. */
241   int num_grids;
242   /* Resolution level up to which displacement is known. */
243   int reshape_level;
244   /* Resolution up to which propagation is happening, affecting all the
245    * levels in [reshape_level + 1, top_level]. */
246   int top_level;
247   /* Grid sizes at the corresponding levels. */
248   int reshape_grid_size;
249   int top_grid_size;
250   /* Keys to access CCG at different levels. */
251   CCGKey reshape_level_key;
252   CCGKey top_level_key;
253   /* Original grid data, before any updates for reshape.
254    * Contains data at the reshape_level resolution level. */
255   CCGElem **orig_grids_data;
256   /* Custom data layers from a coarse mesh. */
257   MDisps *mdisps;
258   GridPaintMask *grid_paint_mask;
259 } MultiresPropagateData;
260
261 static CCGElem **allocate_grids(CCGKey *key, int num_grids)
262 {
263   CCGElem **grids = MEM_calloc_arrayN(num_grids, sizeof(CCGElem *), "reshape grids*");
264   for (int grid_index = 0; grid_index < num_grids; grid_index++) {
265     grids[grid_index] = MEM_calloc_arrayN(
266         key->elem_size, key->grid_area, "reshape orig_grids_data elems");
267   }
268   return grids;
269 }
270
271 static void free_grids(CCGElem **grids, int num_grids)
272 {
273   if (grids == NULL) {
274     return;
275   }
276   for (int grid_index = 0; grid_index < num_grids; grid_index++) {
277     MEM_freeN(grids[grid_index]);
278   }
279   MEM_freeN(grids);
280 }
281
282 /* Initialize element sizes and offsets. */
283 static void multires_reshape_init_key_layers(CCGKey *key, const MultiresPropagateData *data)
284 {
285   key->elem_size = 3 * sizeof(float);
286   if (data->grid_paint_mask != NULL) {
287     key->mask_offset = 3 * sizeof(float);
288     key->elem_size += sizeof(float);
289     key->has_mask = true;
290   }
291   else {
292     key->mask_offset = -1;
293     key->has_mask = false;
294   }
295   /* We never have normals in original grids. */
296   key->normal_offset = -1;
297   key->has_normals = false;
298 }
299
300 /* Initialize key used to access reshape grids at given level. */
301 static void multires_reshape_init_level_key(CCGKey *key,
302                                             const MultiresPropagateData *data,
303                                             const int level)
304 {
305   key->level = level;
306   /* Init layers. */
307   multires_reshape_init_key_layers(key, data);
308   /* By default, only 3 floats for coordinate, */
309   key->grid_size = BKE_subdiv_grid_size_from_level(key->level);
310   key->grid_area = key->grid_size * key->grid_size;
311   key->grid_bytes = key->elem_size * key->grid_area;
312 }
313
314 static void multires_reshape_store_original_grids(MultiresPropagateData *data)
315 {
316   const int num_grids = data->num_grids;
317   /* Original data to be backed up. */
318   const MDisps *mdisps = data->mdisps;
319   const GridPaintMask *grid_paint_mask = data->grid_paint_mask;
320   /* Allocate grids for backup. */
321   CCGKey *orig_key = &data->reshape_level_key;
322   CCGElem **orig_grids_data = allocate_grids(orig_key, num_grids);
323   /* Fill in grids. */
324   const int orig_grid_size = data->reshape_grid_size;
325   const int top_grid_size = data->top_grid_size;
326   const int skip = (top_grid_size - 1) / (orig_grid_size - 1);
327   for (int grid_index = 0; grid_index < num_grids; grid_index++) {
328     CCGElem *orig_grid = orig_grids_data[grid_index];
329     for (int y = 0; y < orig_grid_size; y++) {
330       const int top_y = y * skip;
331       for (int x = 0; x < orig_grid_size; x++) {
332         const int top_x = x * skip;
333         const int top_index = top_y * top_grid_size + top_x;
334         memcpy(CCG_grid_elem_co(orig_key, orig_grid, x, y),
335                mdisps[grid_index].disps[top_index],
336                sizeof(float) * 3);
337         if (orig_key->has_mask) {
338           *CCG_grid_elem_mask(
339               orig_key, orig_grid, x, y) = grid_paint_mask[grid_index].data[top_index];
340         }
341       }
342     }
343   }
344   /* Store in the context. */
345   data->orig_grids_data = orig_grids_data;
346 }
347
348 static void multires_reshape_propagate_prepare(MultiresPropagateData *data,
349                                                Mesh *coarse_mesh,
350                                                const int reshape_level,
351                                                const int top_level)
352 {
353   BLI_assert(reshape_level <= top_level);
354   memset(data, 0, sizeof(*data));
355   data->num_grids = coarse_mesh->totloop;
356   data->reshape_level = reshape_level;
357   data->top_level = top_level;
358   if (reshape_level == top_level) {
359     /* Nothing to do, reshape will happen on the whole grid content. */
360     return;
361   }
362   data->mdisps = CustomData_get_layer(&coarse_mesh->ldata, CD_MDISPS);
363   data->grid_paint_mask = CustomData_get_layer(&coarse_mesh->ldata, CD_GRID_PAINT_MASK);
364   data->top_grid_size = BKE_subdiv_grid_size_from_level(top_level);
365   data->reshape_grid_size = BKE_subdiv_grid_size_from_level(reshape_level);
366   /* Initialize keys to access CCG at different levels. */
367   multires_reshape_init_level_key(&data->reshape_level_key, data, data->reshape_level);
368   multires_reshape_init_level_key(&data->top_level_key, data, data->top_level);
369   /* Make a copy of grids before reshaping, so we can calculate deltas
370    * later on. */
371   multires_reshape_store_original_grids(data);
372 }
373
374 static void multires_reshape_propagate_prepare_from_mmd(MultiresPropagateData *data,
375                                                         struct Depsgraph *depsgraph,
376                                                         Object *object,
377                                                         const MultiresModifierData *mmd,
378                                                         const int top_level,
379                                                         const bool use_render_params)
380 {
381   /* TODO(sergey): Find mode reliable way of getting current level. */
382   Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
383   Mesh *mesh = object->data;
384   const int level = multires_get_level(scene_eval, object, mmd, use_render_params, true);
385   multires_reshape_propagate_prepare(data, mesh, level, top_level);
386 }
387
388 /* Calculate delta of changed reshape level data layers. Delta goes to a
389  * grids at top level (meaning, the result grids are only partially filled
390  * in). */
391 static void multires_reshape_calculate_delta(MultiresPropagateData *data,
392                                              CCGElem **delta_grids_data)
393 {
394   const int num_grids = data->num_grids;
395   /* At this point those custom data layers has updated data for the
396    * level we are propagating from. */
397   const MDisps *mdisps = data->mdisps;
398   const GridPaintMask *grid_paint_mask = data->grid_paint_mask;
399   CCGKey *reshape_key = &data->reshape_level_key;
400   CCGKey *delta_level_key = &data->top_level_key;
401   /* Calculate delta. */
402   const int top_grid_size = data->top_grid_size;
403   const int reshape_grid_size = data->reshape_grid_size;
404   const int delta_grid_size = data->top_grid_size;
405   const int skip = (top_grid_size - 1) / (reshape_grid_size - 1);
406   for (int grid_index = 0; grid_index < num_grids; grid_index++) {
407     /*const*/ CCGElem *orig_grid = data->orig_grids_data[grid_index];
408     CCGElem *delta_grid = delta_grids_data[grid_index];
409     for (int y = 0; y < reshape_grid_size; y++) {
410       const int top_y = y * skip;
411       for (int x = 0; x < reshape_grid_size; x++) {
412         const int top_x = x * skip;
413         const int top_index = top_y * delta_grid_size + top_x;
414         sub_v3_v3v3(CCG_grid_elem_co(delta_level_key, delta_grid, top_x, top_y),
415                     mdisps[grid_index].disps[top_index],
416                     CCG_grid_elem_co(reshape_key, orig_grid, x, y));
417         if (delta_level_key->has_mask) {
418           const float old_mask_value = *CCG_grid_elem_mask(reshape_key, orig_grid, x, y);
419           const float new_mask_value = grid_paint_mask[grid_index].data[top_index];
420           *CCG_grid_elem_mask(delta_level_key, delta_grid, top_x, top_y) = new_mask_value -
421                                                                            old_mask_value;
422         }
423       }
424     }
425   }
426 }
427
428 /* Makes it so delta is propagated onto all the higher levels, but is also
429  * that this delta is smoothed in a way that it does not cause artifacts on
430  * boundaries. */
431
432 typedef struct MultiresPropagateCornerData {
433   float coord_delta[3];
434   float mask_delta;
435 } MultiresPropagateCornerData;
436
437 BLI_INLINE void multires_reshape_propagate_init_patch_corners(
438     MultiresPropagateData *data,
439     CCGElem *delta_grid,
440     const int patch_x,
441     const int patch_y,
442     MultiresPropagateCornerData r_corners[4])
443 {
444   CCGKey *delta_level_key = &data->top_level_key;
445   const int orig_grid_size = data->reshape_grid_size;
446   const int top_grid_size = data->top_grid_size;
447   const int skip = (top_grid_size - 1) / (orig_grid_size - 1);
448   const int x = patch_x * skip;
449   const int y = patch_y * skip;
450   /* Store coordinate deltas. */
451   copy_v3_v3(r_corners[0].coord_delta, CCG_grid_elem_co(delta_level_key, delta_grid, x, y));
452   copy_v3_v3(r_corners[1].coord_delta, CCG_grid_elem_co(delta_level_key, delta_grid, x + skip, y));
453   copy_v3_v3(r_corners[2].coord_delta, CCG_grid_elem_co(delta_level_key, delta_grid, x, y + skip));
454   copy_v3_v3(r_corners[3].coord_delta,
455              CCG_grid_elem_co(delta_level_key, delta_grid, x + skip, y + skip));
456   if (delta_level_key->has_mask) {
457     r_corners[0].mask_delta = *CCG_grid_elem_mask(delta_level_key, delta_grid, x, y);
458     r_corners[1].mask_delta = *CCG_grid_elem_mask(delta_level_key, delta_grid, x + skip, y);
459     r_corners[2].mask_delta = *CCG_grid_elem_mask(delta_level_key, delta_grid, x, y + skip);
460     r_corners[3].mask_delta = *CCG_grid_elem_mask(delta_level_key, delta_grid, x + skip, y + skip);
461   }
462 }
463
464 BLI_INLINE void multires_reshape_propagate_interpolate_coord(
465     float delta[3], const MultiresPropagateCornerData corners[4], const float weights[4])
466 {
467   interp_v3_v3v3v3v3(delta,
468                      corners[0].coord_delta,
469                      corners[1].coord_delta,
470                      corners[2].coord_delta,
471                      corners[3].coord_delta,
472                      weights);
473 }
474
475 BLI_INLINE float multires_reshape_propagate_interpolate_mask(
476     const MultiresPropagateCornerData corners[4], const float weights[4])
477 {
478   return corners[0].mask_delta * weights[0] + corners[1].mask_delta * weights[1] +
479          corners[2].mask_delta * weights[2] + corners[3].mask_delta * weights[3];
480 }
481
482 BLI_INLINE void multires_reshape_propagate_and_smooth_delta_grid_patch(MultiresPropagateData *data,
483                                                                        CCGElem *delta_grid,
484                                                                        const int patch_x,
485                                                                        const int patch_y)
486 {
487   CCGKey *delta_level_key = &data->top_level_key;
488   const int orig_grid_size = data->reshape_grid_size;
489   const int top_grid_size = data->top_grid_size;
490   const int skip = (top_grid_size - 1) / (orig_grid_size - 1);
491   const float skip_inv = 1.0f / (float)skip;
492   MultiresPropagateCornerData corners[4];
493   multires_reshape_propagate_init_patch_corners(data, delta_grid, patch_x, patch_y, corners);
494   const int start_x = patch_x * skip;
495   const int start_y = patch_y * skip;
496   for (int y = 0; y <= skip; y++) {
497     const float v = (float)y * skip_inv;
498     const int final_y = start_y + y;
499     for (int x = 0; x <= skip; x++) {
500       const float u = (float)x * skip_inv;
501       const int final_x = start_x + x;
502       const float linear_weights[4] = {
503           (1.0f - u) * (1.0f - v), u * (1.0f - v), (1.0f - u) * v, u * v};
504       multires_reshape_propagate_interpolate_coord(
505           CCG_grid_elem_co(delta_level_key, delta_grid, final_x, final_y),
506           corners,
507           linear_weights);
508       if (delta_level_key->has_mask) {
509         float *mask = CCG_grid_elem_mask(delta_level_key, delta_grid, final_x, final_y);
510         *mask = multires_reshape_propagate_interpolate_mask(corners, linear_weights);
511       }
512     }
513   }
514 }
515
516 BLI_INLINE void multires_reshape_propagate_and_smooth_delta_grid(MultiresPropagateData *data,
517                                                                  CCGElem *delta_grid)
518 {
519   const int orig_grid_size = data->reshape_grid_size;
520   for (int patch_y = 0; patch_y < orig_grid_size - 1; patch_y++) {
521     for (int patch_x = 0; patch_x < orig_grid_size - 1; patch_x++) {
522       multires_reshape_propagate_and_smooth_delta_grid_patch(data, delta_grid, patch_x, patch_y);
523     }
524   }
525 }
526
527 /* Entry point to propagate+smooth. */
528 static void multires_reshape_propagate_and_smooth_delta(MultiresPropagateData *data,
529                                                         CCGElem **delta_grids_data)
530 {
531   const int num_grids = data->num_grids;
532   for (int grid_index = 0; grid_index < num_grids; grid_index++) {
533     CCGElem *delta_grid = delta_grids_data[grid_index];
534     multires_reshape_propagate_and_smooth_delta_grid(data, delta_grid);
535   }
536 }
537
538 /* Apply smoothed deltas on the actual data layers. */
539 static void multires_reshape_propagate_apply_delta(MultiresPropagateData *data,
540                                                    CCGElem **delta_grids_data)
541 {
542   const int num_grids = data->num_grids;
543   /* At this point those custom data layers has updated data for the
544    * level we are propagating from. */
545   MDisps *mdisps = data->mdisps;
546   GridPaintMask *grid_paint_mask = data->grid_paint_mask;
547   CCGKey *orig_key = &data->reshape_level_key;
548   CCGKey *delta_level_key = &data->top_level_key;
549   CCGElem **orig_grids_data = data->orig_grids_data;
550   const int orig_grid_size = data->reshape_grid_size;
551   const int top_grid_size = data->top_grid_size;
552   const int skip = (top_grid_size - 1) / (orig_grid_size - 1);
553   /* Restore grid values at the reshape level. Those values are to be changed
554    * to the accommodate for the smooth delta. */
555   for (int grid_index = 0; grid_index < num_grids; grid_index++) {
556     CCGElem *orig_grid = orig_grids_data[grid_index];
557     for (int y = 0; y < orig_grid_size; y++) {
558       const int top_y = y * skip;
559       for (int x = 0; x < orig_grid_size; x++) {
560         const int top_x = x * skip;
561         const int top_index = top_y * top_grid_size + top_x;
562         copy_v3_v3(mdisps[grid_index].disps[top_index],
563                    CCG_grid_elem_co(orig_key, orig_grid, x, y));
564         if (grid_paint_mask != NULL) {
565           grid_paint_mask[grid_index].data[top_index] = *CCG_grid_elem_mask(
566               orig_key, orig_grid, x, y);
567         }
568       }
569     }
570   }
571   /* Add smoothed delta to all the levels. */
572   for (int grid_index = 0; grid_index < num_grids; grid_index++) {
573     CCGElem *delta_grid = delta_grids_data[grid_index];
574     for (int y = 0; y < top_grid_size; y++) {
575       for (int x = 0; x < top_grid_size; x++) {
576         const int top_index = y * top_grid_size + x;
577         add_v3_v3(mdisps[grid_index].disps[top_index],
578                   CCG_grid_elem_co(delta_level_key, delta_grid, x, y));
579         if (delta_level_key->has_mask) {
580           grid_paint_mask[grid_index].data[top_index] += *CCG_grid_elem_mask(
581               delta_level_key, delta_grid, x, y);
582         }
583       }
584     }
585   }
586 }
587
588 static void multires_reshape_propagate(MultiresPropagateData *data)
589 {
590   if (data->reshape_level == data->top_level) {
591     return;
592   }
593   const int num_grids = data->num_grids;
594   /* Calculate delta made at the reshape level. */
595   CCGKey *delta_level_key = &data->top_level_key;
596   CCGElem **delta_grids_data = allocate_grids(delta_level_key, num_grids);
597   multires_reshape_calculate_delta(data, delta_grids_data);
598   /* Propagate deltas to the higher levels. */
599   multires_reshape_propagate_and_smooth_delta(data, delta_grids_data);
600   /* Finally, apply smoothed deltas. */
601   multires_reshape_propagate_apply_delta(data, delta_grids_data);
602   /* Cleanup. */
603   free_grids(delta_grids_data, num_grids);
604 }
605
606 static void multires_reshape_propagate_free(MultiresPropagateData *data)
607 {
608   free_grids(data->orig_grids_data, data->num_grids);
609 }
610
611 /* =============================================================================
612  * Reshape from deformed vertex coordinates.
613  */
614
615 typedef struct MultiresReshapeFromDeformedVertsContext {
616   MultiresReshapeContext reshape_ctx;
617   const float (*deformed_verts)[3];
618   int num_deformed_verts;
619 } MultiresReshapeFromDeformedVertsContext;
620
621 static bool multires_reshape_topology_info(const SubdivForeachContext *foreach_context,
622                                            const int num_vertices,
623                                            const int UNUSED(num_edges),
624                                            const int UNUSED(num_loops),
625                                            const int UNUSED(num_polygons))
626 {
627   MultiresReshapeFromDeformedVertsContext *ctx = foreach_context->user_data;
628   if (num_vertices != ctx->num_deformed_verts) {
629     return false;
630   }
631   return true;
632 }
633
634 /* Will run reshaping for all grid elements which are adjacent to the given
635  * one. This is the way to ensure continuity of displacement stored in the
636  * grids across the inner boundaries of the grids. */
637 static void multires_reshape_neighour_boundary_vertices(MultiresReshapeContext *ctx,
638                                                         const int UNUSED(ptex_face_index),
639                                                         const float corner_u,
640                                                         const float corner_v,
641                                                         const int coarse_poly_index,
642                                                         const int coarse_corner,
643                                                         const float final_P[3],
644                                                         const float final_mask)
645 {
646   const Mesh *coarse_mesh = ctx->coarse_mesh;
647   const MPoly *coarse_mpoly = coarse_mesh->mpoly;
648   const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
649   const int num_corners = coarse_poly->totloop;
650   const int start_ptex_face_index = ctx->face_ptex_offset[coarse_poly_index];
651   const bool is_quad = (coarse_poly->totloop == 4);
652   if (corner_u == 1.0f && corner_v == 1.0f) {
653     for (int current_corner = 0; current_corner < num_corners; ++current_corner) {
654       if (current_corner == coarse_corner) {
655         continue;
656       }
657       const int current_ptex_face_index = is_quad ? start_ptex_face_index :
658                                                     start_ptex_face_index + current_corner;
659       multires_reshape_vertex_from_final_data(ctx,
660                                               current_ptex_face_index,
661                                               1.0f,
662                                               1.0f,
663                                               coarse_poly_index,
664                                               current_corner,
665                                               final_P,
666                                               final_mask);
667     }
668   }
669   else if (corner_u == 1.0f) {
670     const float next_corner_index = (coarse_corner + 1) % num_corners;
671     const float next_corner_u = corner_v;
672     const float next_corner_v = 1.0f;
673     const int next_ptex_face_index = is_quad ? start_ptex_face_index :
674                                                start_ptex_face_index + next_corner_index;
675     multires_reshape_vertex_from_final_data(ctx,
676                                             next_ptex_face_index,
677                                             next_corner_u,
678                                             next_corner_v,
679                                             coarse_poly_index,
680                                             next_corner_index,
681                                             final_P,
682                                             final_mask);
683   }
684   else if (corner_v == 1.0f) {
685     const float prev_corner_index = (coarse_corner + num_corners - 1) % num_corners;
686     const float prev_corner_u = 1.0f;
687     const float prev_corner_v = corner_u;
688     const int prev_ptex_face_index = is_quad ? start_ptex_face_index :
689                                                start_ptex_face_index + prev_corner_index;
690     multires_reshape_vertex_from_final_data(ctx,
691                                             prev_ptex_face_index,
692                                             prev_corner_u,
693                                             prev_corner_v,
694                                             coarse_poly_index,
695                                             prev_corner_index,
696                                             final_P,
697                                             final_mask);
698   }
699 }
700
701 static void multires_reshape_vertex(MultiresReshapeFromDeformedVertsContext *ctx,
702                                     const int ptex_face_index,
703                                     const float u,
704                                     const float v,
705                                     const int coarse_poly_index,
706                                     const int coarse_corner,
707                                     const int subdiv_vertex_index)
708 {
709   const float *final_P = ctx->deformed_verts[subdiv_vertex_index];
710   const Mesh *coarse_mesh = ctx->reshape_ctx.coarse_mesh;
711   const MPoly *coarse_mpoly = coarse_mesh->mpoly;
712   const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
713   const bool is_quad = (coarse_poly->totloop == 4);
714   float corner_u, corner_v;
715   int actual_coarse_corner;
716   if (is_quad) {
717     actual_coarse_corner = BKE_subdiv_rotate_quad_to_corner(u, v, &corner_u, &corner_v);
718   }
719   else {
720     actual_coarse_corner = coarse_corner;
721     corner_u = u;
722     corner_v = v;
723   }
724   multires_reshape_vertex_from_final_data(&ctx->reshape_ctx,
725                                           ptex_face_index,
726                                           corner_u,
727                                           corner_v,
728                                           coarse_poly_index,
729                                           actual_coarse_corner,
730                                           final_P,
731                                           0.0f);
732   multires_reshape_neighour_boundary_vertices(&ctx->reshape_ctx,
733                                               ptex_face_index,
734                                               corner_u,
735                                               corner_v,
736                                               coarse_poly_index,
737                                               actual_coarse_corner,
738                                               final_P,
739                                               0.0f);
740 }
741
742 static void multires_reshape_vertex_inner(const SubdivForeachContext *foreach_context,
743                                           void *UNUSED(tls_v),
744                                           const int ptex_face_index,
745                                           const float u,
746                                           const float v,
747                                           const int coarse_poly_index,
748                                           const int coarse_corner,
749                                           const int subdiv_vertex_index)
750 {
751   MultiresReshapeFromDeformedVertsContext *ctx = foreach_context->user_data;
752   multires_reshape_vertex(
753       ctx, ptex_face_index, u, v, coarse_poly_index, coarse_corner, subdiv_vertex_index);
754 }
755
756 static void multires_reshape_vertex_every_corner(
757     const struct SubdivForeachContext *foreach_context,
758     void *UNUSED(tls_v),
759     const int ptex_face_index,
760     const float u,
761     const float v,
762     const int UNUSED(coarse_vertex_index),
763     const int coarse_poly_index,
764     const int coarse_corner,
765     const int subdiv_vertex_index)
766 {
767   MultiresReshapeFromDeformedVertsContext *ctx = foreach_context->user_data;
768   multires_reshape_vertex(
769       ctx, ptex_face_index, u, v, coarse_poly_index, coarse_corner, subdiv_vertex_index);
770 }
771
772 static void multires_reshape_vertex_every_edge(const struct SubdivForeachContext *foreach_context,
773                                                void *UNUSED(tls_v),
774                                                const int ptex_face_index,
775                                                const float u,
776                                                const float v,
777                                                const int UNUSED(coarse_edge_index),
778                                                const int coarse_poly_index,
779                                                const int coarse_corner,
780                                                const int subdiv_vertex_index)
781 {
782   MultiresReshapeFromDeformedVertsContext *ctx = foreach_context->user_data;
783   multires_reshape_vertex(
784       ctx, ptex_face_index, u, v, coarse_poly_index, coarse_corner, subdiv_vertex_index);
785 }
786
787 static Subdiv *multires_create_subdiv_for_reshape(struct Depsgraph *depsgraph,
788                                                   /*const*/ Object *object,
789                                                   const MultiresModifierData *mmd)
790 {
791   Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
792   Object *object_eval = DEG_get_evaluated_object(depsgraph, object);
793   Mesh *deformed_mesh = mesh_get_eval_deform(
794       depsgraph, scene_eval, object_eval, &CD_MASK_BAREMESH);
795   SubdivSettings subdiv_settings;
796   BKE_multires_subdiv_settings_init(&subdiv_settings, mmd);
797   Subdiv *subdiv = BKE_subdiv_new_from_mesh(&subdiv_settings, deformed_mesh);
798   if (!BKE_subdiv_eval_update_from_mesh(subdiv, deformed_mesh)) {
799     BKE_subdiv_free(subdiv);
800     return NULL;
801   }
802   return subdiv;
803 }
804
805 static bool multires_reshape_from_vertcos(struct Depsgraph *depsgraph,
806                                           Object *object,
807                                           const MultiresModifierData *mmd,
808                                           const float (*deformed_verts)[3],
809                                           const int num_deformed_verts,
810                                           const bool use_render_params)
811 {
812   Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
813   Mesh *coarse_mesh = object->data;
814   MDisps *mdisps = CustomData_get_layer(&coarse_mesh->ldata, CD_MDISPS);
815   /* Pick maximum between multires level and dispalcement level.
816    * This is because mesh can be used by objects with multires at different
817    * levels.
818    *
819    * TODO(sergey): At this point it should be possible to always use
820    * mdisps->level. */
821   const int top_level = max_ii(mmd->totlvl, mdisps->level);
822   /* Make sure displacement grids are ready. */
823   multires_reshape_ensure_grids(coarse_mesh, top_level);
824   /* Initialize subdivision surface. */
825   Subdiv *subdiv = multires_create_subdiv_for_reshape(depsgraph, object, mmd);
826   if (subdiv == NULL) {
827     return false;
828   }
829   /* Construct context. */
830   MultiresReshapeFromDeformedVertsContext reshape_deformed_verts_ctx = {
831       .reshape_ctx =
832           {
833               .subdiv = subdiv,
834               .coarse_mesh = coarse_mesh,
835               .mdisps = mdisps,
836               .grid_paint_mask = NULL,
837               .top_grid_size = BKE_subdiv_grid_size_from_level(top_level),
838               .top_level = top_level,
839               .face_ptex_offset = BKE_subdiv_face_ptex_offset_get(subdiv),
840           },
841       .deformed_verts = deformed_verts,
842       .num_deformed_verts = num_deformed_verts,
843   };
844   SubdivForeachContext foreach_context = {
845       .topology_info = multires_reshape_topology_info,
846       .vertex_inner = multires_reshape_vertex_inner,
847       .vertex_every_edge = multires_reshape_vertex_every_edge,
848       .vertex_every_corner = multires_reshape_vertex_every_corner,
849       .user_data = &reshape_deformed_verts_ctx,
850   };
851   /* Initialize mesh rasterization settings. */
852   SubdivToMeshSettings mesh_settings;
853   BKE_multires_subdiv_mesh_settings_init(
854       &mesh_settings, scene_eval, object, mmd, use_render_params, true);
855   /* Initialize propagation to higher levels. */
856   MultiresPropagateData propagate_data;
857   multires_reshape_propagate_prepare_from_mmd(
858       &propagate_data, depsgraph, object, mmd, top_level, use_render_params);
859   /* Run all the callbacks. */
860   BKE_subdiv_foreach_subdiv_geometry(subdiv, &foreach_context, &mesh_settings, coarse_mesh);
861   BKE_subdiv_free(subdiv);
862   /* Update higher levels if needed. */
863   multires_reshape_propagate(&propagate_data);
864   multires_reshape_propagate_free(&propagate_data);
865   return true;
866 }
867
868 /* =============================================================================
869  * Reshape from object.
870  */
871
872 /* Returns truth on success, false otherwise.
873  *
874  * This function might fail in cases like source and destination not having
875  * matched amount of vertices. */
876 bool multiresModifier_reshapeFromObject(struct Depsgraph *depsgraph,
877                                         MultiresModifierData *mmd,
878                                         Object *dst,
879                                         Object *src)
880 {
881   /* Would be cool to support this eventually, but it is very tricky to match
882    * vertices order even for meshes, when mixing meshes and other objects it's
883    * even more tricky. */
884   if (src->type != OB_MESH) {
885     return false;
886   }
887   MultiresModifierData reshape_mmd;
888   multires_reshape_init_mmd(&reshape_mmd, mmd);
889   /* Get evaluated vertices locations to reshape to. */
890   Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
891   Object *src_eval = DEG_get_evaluated_object(depsgraph, src);
892   Mesh *src_mesh_eval = mesh_get_eval_final(depsgraph, scene_eval, src_eval, &CD_MASK_BAREMESH);
893   int num_deformed_verts;
894   float(*deformed_verts)[3] = BKE_mesh_vertexCos_get(src_mesh_eval, &num_deformed_verts);
895   bool result = multires_reshape_from_vertcos(
896       depsgraph, dst, &reshape_mmd, deformed_verts, num_deformed_verts, false);
897   MEM_freeN(deformed_verts);
898   return result;
899 }
900
901 /* =============================================================================
902  * Reshape from modifier.
903  */
904
905 bool multiresModifier_reshapeFromDeformModifier(struct Depsgraph *depsgraph,
906                                                 MultiresModifierData *mmd,
907                                                 Object *object,
908                                                 ModifierData *md)
909 {
910   MultiresModifierData highest_mmd;
911   /* It is possible that the current subdivision level of multires is lower
912    * that it's maximum possible one (i.e., viewport is set to a lower level
913    * for the performance purposes). But even then, we want all the multires
914    * levels to be reshaped. Most accurate way to do so is to ignore all
915    * simplifications and calculate deformation modifier for the highest
916    * possible multires level.
917    * Alternative would be propagate displacement from current level to a
918    * higher ones, but that is likely to cause artifacts. */
919   multires_reshape_init_mmd_top_level(&highest_mmd, mmd);
920   Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
921   /* Perform sanity checks and early output. */
922   if (multires_get_level(scene_eval, object, &highest_mmd, false, true) == 0) {
923     return false;
924   }
925   /* Create mesh for the multires, ignoring any further modifiers (leading
926    * deformation modifiers will be applied though). */
927   Mesh *multires_mesh = BKE_multires_create_mesh(depsgraph, scene_eval, &highest_mmd, object);
928   int num_deformed_verts;
929   float(*deformed_verts)[3] = BKE_mesh_vertexCos_get(multires_mesh, &num_deformed_verts);
930   /* Apply deformation modifier on the multires, */
931   const ModifierEvalContext modifier_ctx = {
932       .depsgraph = depsgraph,
933       .object = object,
934       .flag = MOD_APPLY_USECACHE | MOD_APPLY_IGNORE_SIMPLIFY,
935   };
936   modwrap_deformVerts(md, &modifier_ctx, multires_mesh, deformed_verts, multires_mesh->totvert);
937   BKE_id_free(NULL, multires_mesh);
938   /* Reshaping */
939   bool result = multires_reshape_from_vertcos(
940       depsgraph, object, &highest_mmd, deformed_verts, num_deformed_verts, false);
941   /* Cleanup */
942   MEM_freeN(deformed_verts);
943   return result;
944 }
945
946 /* =============================================================================
947  * Reshape from grids.
948  */
949
950 typedef struct ReshapeFromCCGTaskData {
951   MultiresReshapeContext reshape_ctx;
952   const CCGKey *key;
953   /*const*/ CCGElem **grids;
954 } ReshapeFromCCGTaskData;
955
956 static void reshape_from_ccg_task(void *__restrict userdata,
957                                   const int coarse_poly_index,
958                                   const ParallelRangeTLS *__restrict UNUSED(tls))
959 {
960   ReshapeFromCCGTaskData *data = userdata;
961   const CCGKey *key = data->key;
962   /*const*/ CCGElem **grids = data->grids;
963   const Mesh *coarse_mesh = data->reshape_ctx.coarse_mesh;
964   const MPoly *coarse_mpoly = coarse_mesh->mpoly;
965   const MPoly *coarse_poly = &coarse_mpoly[coarse_poly_index];
966   const int key_grid_size = key->grid_size;
967   const int key_grid_size_1 = key_grid_size - 1;
968   const int resolution = key_grid_size;
969   const float resolution_1_inv = 1.0f / (float)(resolution - 1);
970   const int start_ptex_face_index = data->reshape_ctx.face_ptex_offset[coarse_poly_index];
971   const bool is_quad = (coarse_poly->totloop == 4);
972   for (int corner = 0; corner < coarse_poly->totloop; corner++) {
973     for (int y = 0; y < resolution; y++) {
974       const float corner_v = y * resolution_1_inv;
975       for (int x = 0; x < resolution; x++) {
976         const float corner_u = x * resolution_1_inv;
977         /* Quad faces consists of a single ptex face. */
978         const int ptex_face_index = is_quad ? start_ptex_face_index :
979                                               start_ptex_face_index + corner;
980         float grid_u, grid_v;
981         BKE_subdiv_ptex_face_uv_to_grid_uv(corner_u, corner_v, &grid_u, &grid_v);
982         /*const*/ CCGElem *grid = grids[coarse_poly->loopstart + corner];
983         /*const*/ CCGElem *grid_element = CCG_grid_elem(
984             key, grid, key_grid_size_1 * grid_u, key_grid_size_1 * grid_v);
985         const float *final_P = CCG_elem_co(key, grid_element);
986         float final_mask = 0.0f;
987         if (key->has_mask) {
988           final_mask = *CCG_elem_mask(key, grid_element);
989         }
990         multires_reshape_vertex_from_final_data(&data->reshape_ctx,
991                                                 ptex_face_index,
992                                                 corner_u,
993                                                 corner_v,
994                                                 coarse_poly_index,
995                                                 corner,
996                                                 final_P,
997                                                 final_mask);
998       }
999     }
1000   }
1001 }
1002
1003 bool multiresModifier_reshapeFromCCG(const int tot_level, Mesh *coarse_mesh, SubdivCCG *subdiv_ccg)
1004 {
1005   CCGKey key;
1006   BKE_subdiv_ccg_key_top_level(&key, subdiv_ccg);
1007   /* Sanity checks. */
1008   if (coarse_mesh->totloop != subdiv_ccg->num_grids) {
1009     /* Grids are supposed to eb created for each face-cornder (aka loop). */
1010     return false;
1011   }
1012   MDisps *mdisps = CustomData_get_layer(&coarse_mesh->ldata, CD_MDISPS);
1013   if (mdisps == NULL) {
1014     /* Multires displacement has been removed before current changes were
1015      * applies to all the levels. */
1016     return false;
1017   }
1018   GridPaintMask *grid_paint_mask = CustomData_get_layer(&coarse_mesh->ldata, CD_GRID_PAINT_MASK);
1019   Subdiv *subdiv = subdiv_ccg->subdiv;
1020   /* Pick maximum between multires level and dispalcement level.
1021    * This is because mesh can be used by objects with multires at different
1022    * levels.
1023    *
1024    * TODO(sergey): At this point it should be possible to always use
1025    * mdisps->level. */
1026   const int top_level = max_ii(tot_level, mdisps->level);
1027   /* Make sure displacement grids are ready. */
1028   multires_reshape_ensure_grids(coarse_mesh, top_level);
1029   /* Construct context. */
1030   ReshapeFromCCGTaskData data = {
1031       .reshape_ctx =
1032           {
1033               .subdiv = subdiv,
1034               .coarse_mesh = coarse_mesh,
1035               .mdisps = mdisps,
1036               .grid_paint_mask = grid_paint_mask,
1037               .top_grid_size = BKE_subdiv_grid_size_from_level(top_level),
1038               .top_level = top_level,
1039               .face_ptex_offset = BKE_subdiv_face_ptex_offset_get(subdiv),
1040           },
1041       .key = &key,
1042       .grids = subdiv_ccg->grids,
1043   };
1044   /* Initialize propagation to higher levels. */
1045   MultiresPropagateData propagate_data;
1046   multires_reshape_propagate_prepare(&propagate_data, coarse_mesh, key.level, top_level);
1047   /* Threaded grids iteration. */
1048   ParallelRangeSettings parallel_range_settings;
1049   BLI_parallel_range_settings_defaults(&parallel_range_settings);
1050   BLI_task_parallel_range(
1051       0, coarse_mesh->totpoly, &data, reshape_from_ccg_task, &parallel_range_settings);
1052   /* Update higher levels if needed. */
1053   multires_reshape_propagate(&propagate_data);
1054   multires_reshape_propagate_free(&propagate_data);
1055   return true;
1056 }