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) 2020 Blender Foundation.
17  * All rights reserved.
18  */
19 
20 /** \file
21  * \ingroup edsculpt
22  */
23 
24 #include "MEM_guardedalloc.h"
25 
26 #include "BLI_blenlib.h"
27 #include "BLI_math.h"
28 #include "BLI_task.h"
29 
30 #include "DNA_brush_types.h"
31 #include "DNA_mesh_types.h"
32 #include "DNA_meshdata_types.h"
33 #include "DNA_object_types.h"
34 
35 #include "BKE_brush.h"
36 #include "BKE_ccg.h"
37 #include "BKE_colortools.h"
38 #include "BKE_context.h"
39 #include "BKE_mesh.h"
40 #include "BKE_multires.h"
41 #include "BKE_node.h"
42 #include "BKE_object.h"
43 #include "BKE_paint.h"
44 #include "BKE_pbvh.h"
45 #include "BKE_scene.h"
46 
47 #include "paint_intern.h"
48 #include "sculpt_intern.h"
49 
50 #include "bmesh.h"
51 
52 #include <math.h>
53 #include <stdlib.h>
54 
pose_solve_ik_chain(SculptPoseIKChain * ik_chain,const float initial_target[3],const bool use_anchor)55 static void pose_solve_ik_chain(SculptPoseIKChain *ik_chain,
56                                 const float initial_target[3],
57                                 const bool use_anchor)
58 {
59   SculptPoseIKChainSegment *segments = ik_chain->segments;
60   int tot_segments = ik_chain->tot_segments;
61 
62   float target[3];
63 
64   /* Set the initial target. */
65   copy_v3_v3(target, initial_target);
66 
67   /* Solve the positions and rotations of all segments in the chain. */
68   for (int i = 0; i < tot_segments; i++) {
69     float initial_orientation[3];
70     float current_orientation[3];
71     float current_head_position[3];
72     float current_origin_position[3];
73 
74     /* Calculate the rotation to orientate the segment to the target from its initial state. */
75     sub_v3_v3v3(current_orientation, target, segments[i].orig);
76     normalize_v3(current_orientation);
77     sub_v3_v3v3(initial_orientation, segments[i].initial_head, segments[i].initial_orig);
78     normalize_v3(initial_orientation);
79     rotation_between_vecs_to_quat(segments[i].rot, initial_orientation, current_orientation);
80 
81     /* Rotate the segment by calculating a new head position. */
82     madd_v3_v3v3fl(current_head_position, segments[i].orig, current_orientation, segments[i].len);
83 
84     /* Move the origin of the segment towards the target. */
85     sub_v3_v3v3(current_origin_position, target, current_head_position);
86 
87     /* Store the new head and origin positions to the segment. */
88     copy_v3_v3(segments[i].head, current_head_position);
89     add_v3_v3(segments[i].orig, current_origin_position);
90 
91     /* Use the origin of this segment as target for the next segment in the chain. */
92     copy_v3_v3(target, segments[i].orig);
93   }
94 
95   /* Move back the whole chain to preserve the anchor point. */
96   if (use_anchor) {
97     float anchor_diff[3];
98     sub_v3_v3v3(
99         anchor_diff, segments[tot_segments - 1].initial_orig, segments[tot_segments - 1].orig);
100 
101     for (int i = 0; i < tot_segments; i++) {
102       add_v3_v3(segments[i].orig, anchor_diff);
103       add_v3_v3(segments[i].head, anchor_diff);
104     }
105   }
106 }
107 
pose_solve_roll_chain(SculptPoseIKChain * ik_chain,const Brush * brush,const float roll)108 static void pose_solve_roll_chain(SculptPoseIKChain *ik_chain,
109                                   const Brush *brush,
110                                   const float roll)
111 {
112   SculptPoseIKChainSegment *segments = ik_chain->segments;
113   int tot_segments = ik_chain->tot_segments;
114 
115   for (int i = 0; i < tot_segments; i++) {
116     float initial_orientation[3];
117     float initial_rotation[4];
118     float current_rotation[4];
119 
120     sub_v3_v3v3(initial_orientation, segments[i].initial_head, segments[i].initial_orig);
121     normalize_v3(initial_orientation);
122 
123     /* Calculate the current roll angle using the brush curve. */
124     float current_roll = roll * BKE_brush_curve_strength(brush, i, tot_segments);
125 
126     axis_angle_normalized_to_quat(initial_rotation, initial_orientation, 0.0f);
127     axis_angle_normalized_to_quat(current_rotation, initial_orientation, current_roll);
128 
129     /* Store the difference of the rotations in the segment rotation. */
130     rotation_between_quats_to_quat(segments[i].rot, current_rotation, initial_rotation);
131   }
132 }
133 
pose_solve_translate_chain(SculptPoseIKChain * ik_chain,const float delta[3])134 static void pose_solve_translate_chain(SculptPoseIKChain *ik_chain, const float delta[3])
135 {
136   SculptPoseIKChainSegment *segments = ik_chain->segments;
137   const int tot_segments = ik_chain->tot_segments;
138 
139   for (int i = 0; i < tot_segments; i++) {
140     /* Move the origin and head of each segment by delta. */
141     add_v3_v3v3(segments[i].head, segments[i].initial_head, delta);
142     add_v3_v3v3(segments[i].orig, segments[i].initial_orig, delta);
143 
144     /* Reset the segment rotation. */
145     unit_qt(segments[i].rot);
146   }
147 }
148 
pose_solve_scale_chain(SculptPoseIKChain * ik_chain,const float scale[3])149 static void pose_solve_scale_chain(SculptPoseIKChain *ik_chain, const float scale[3])
150 {
151   SculptPoseIKChainSegment *segments = ik_chain->segments;
152   const int tot_segments = ik_chain->tot_segments;
153 
154   for (int i = 0; i < tot_segments; i++) {
155     /* Assign the scale to each segment. */
156     copy_v3_v3(segments[i].scale, scale);
157   }
158 }
159 
do_pose_brush_task_cb_ex(void * __restrict userdata,const int n,const TaskParallelTLS * __restrict UNUSED (tls))160 static void do_pose_brush_task_cb_ex(void *__restrict userdata,
161                                      const int n,
162                                      const TaskParallelTLS *__restrict UNUSED(tls))
163 {
164   SculptThreadedTaskData *data = userdata;
165   SculptSession *ss = data->ob->sculpt;
166   SculptPoseIKChain *ik_chain = ss->cache->pose_ik_chain;
167   SculptPoseIKChainSegment *segments = ik_chain->segments;
168   const Brush *brush = data->brush;
169 
170   PBVHVertexIter vd;
171   float disp[3], new_co[3];
172   float final_pos[3];
173 
174   SculptOrigVertData orig_data;
175   SCULPT_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
176 
177   BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
178   {
179     SCULPT_orig_vert_data_update(&orig_data, &vd);
180 
181     float total_disp[3];
182     zero_v3(total_disp);
183 
184     ePaintSymmetryAreas symm_area = SCULPT_get_vertex_symm_area(orig_data.co);
185 
186     /* Calculate the displacement of each vertex for all the segments in the chain. */
187     for (int ik = 0; ik < ik_chain->tot_segments; ik++) {
188       copy_v3_v3(new_co, orig_data.co);
189 
190       /* Get the transform matrix for the vertex symmetry area to calculate a displacement in the
191        * vertex. */
192       mul_m4_v3(segments[ik].pivot_mat_inv[(int)symm_area], new_co);
193       mul_m4_v3(segments[ik].trans_mat[(int)symm_area], new_co);
194       mul_m4_v3(segments[ik].pivot_mat[(int)symm_area], new_co);
195 
196       /* Apply the segment weight of the vertex to the displacement. */
197       sub_v3_v3v3(disp, new_co, orig_data.co);
198       mul_v3_fl(disp, segments[ik].weights[vd.index]);
199 
200       /* Apply the vertex mask to the displacement. */
201       float mask = vd.mask ? *vd.mask : 0.0f;
202       mul_v3_fl(disp, 1.0f - mask);
203 
204       /* Accumulate the displacement. */
205       add_v3_v3(total_disp, disp);
206     }
207 
208     /* Apply the accumulated displacement to the vertex. */
209     add_v3_v3v3(final_pos, orig_data.co, total_disp);
210 
211     float *target_co = SCULPT_brush_deform_target_vertex_co_get(ss, brush->deform_target, &vd);
212     copy_v3_v3(target_co, final_pos);
213 
214     if (vd.mvert) {
215       vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
216     }
217   }
218   BKE_pbvh_vertex_iter_end;
219 }
220 
221 typedef struct PoseGrowFactorTLSData {
222   float pos_avg[3];
223   int pos_count;
224 } PoseGrowFactorTLSData;
225 
pose_brush_grow_factor_task_cb_ex(void * __restrict userdata,const int n,const TaskParallelTLS * __restrict tls)226 static void pose_brush_grow_factor_task_cb_ex(void *__restrict userdata,
227                                               const int n,
228                                               const TaskParallelTLS *__restrict tls)
229 {
230   SculptThreadedTaskData *data = userdata;
231   PoseGrowFactorTLSData *gftd = tls->userdata_chunk;
232   SculptSession *ss = data->ob->sculpt;
233   const char symm = SCULPT_mesh_symmetry_xyz_get(data->ob);
234   PBVHVertexIter vd;
235   BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
236   {
237     SculptVertexNeighborIter ni;
238     float max = 0.0f;
239 
240     /* Grow the factor. */
241     SCULPT_VERTEX_NEIGHBORS_ITER_BEGIN (ss, vd.index, ni) {
242       float vmask_f = data->prev_mask[ni.index];
243       max = MAX2(vmask_f, max);
244     }
245     SCULPT_VERTEX_NEIGHBORS_ITER_END(ni);
246 
247     /* Keep the count of the vertices that where added to the factors in this grow iteration. */
248     if (max > data->prev_mask[vd.index]) {
249       data->pose_factor[vd.index] = max;
250       if (SCULPT_check_vertex_pivot_symmetry(vd.co, data->pose_initial_co, symm)) {
251         add_v3_v3(gftd->pos_avg, vd.co);
252         gftd->pos_count++;
253       }
254     }
255   }
256 
257   BKE_pbvh_vertex_iter_end;
258 }
259 
pose_brush_grow_factor_reduce(const void * __restrict UNUSED (userdata),void * __restrict chunk_join,void * __restrict chunk)260 static void pose_brush_grow_factor_reduce(const void *__restrict UNUSED(userdata),
261                                           void *__restrict chunk_join,
262                                           void *__restrict chunk)
263 {
264   PoseGrowFactorTLSData *join = chunk_join;
265   PoseGrowFactorTLSData *gftd = chunk;
266   add_v3_v3(join->pos_avg, gftd->pos_avg);
267   join->pos_count += gftd->pos_count;
268 }
269 
270 /* Grow the factor until its boundary is near to the offset pose origin or outside the target
271  * distance. */
sculpt_pose_grow_pose_factor(Sculpt * sd,Object * ob,SculptSession * ss,float pose_origin[3],float pose_target[3],float max_len,float * r_pose_origin,float * pose_factor)272 static void sculpt_pose_grow_pose_factor(Sculpt *sd,
273                                          Object *ob,
274                                          SculptSession *ss,
275                                          float pose_origin[3],
276                                          float pose_target[3],
277                                          float max_len,
278                                          float *r_pose_origin,
279                                          float *pose_factor)
280 {
281   PBVHNode **nodes;
282   PBVH *pbvh = ob->sculpt->pbvh;
283   int totnode;
284 
285   BKE_pbvh_search_gather(pbvh, NULL, NULL, &nodes, &totnode);
286   SculptThreadedTaskData data = {
287       .sd = sd,
288       .ob = ob,
289       .nodes = nodes,
290       .totnode = totnode,
291       .pose_factor = pose_factor,
292   };
293 
294   data.pose_initial_co = pose_target;
295   TaskParallelSettings settings;
296   PoseGrowFactorTLSData gftd;
297   gftd.pos_count = 0;
298   zero_v3(gftd.pos_avg);
299   BKE_pbvh_parallel_range_settings(&settings, true, totnode);
300   settings.func_reduce = pose_brush_grow_factor_reduce;
301   settings.userdata_chunk = &gftd;
302   settings.userdata_chunk_size = sizeof(PoseGrowFactorTLSData);
303 
304   bool grow_next_iteration = true;
305   float prev_len = FLT_MAX;
306   data.prev_mask = MEM_mallocN(SCULPT_vertex_count_get(ss) * sizeof(float), "prev mask");
307   while (grow_next_iteration) {
308     zero_v3(gftd.pos_avg);
309     gftd.pos_count = 0;
310     memcpy(data.prev_mask, pose_factor, SCULPT_vertex_count_get(ss) * sizeof(float));
311     BLI_task_parallel_range(0, totnode, &data, pose_brush_grow_factor_task_cb_ex, &settings);
312 
313     if (gftd.pos_count != 0) {
314       mul_v3_fl(gftd.pos_avg, 1.0f / (float)gftd.pos_count);
315       if (pose_origin) {
316         /* Test with pose origin. Used when growing the factors to compensate the Origin Offset. */
317         /* Stop when the factor's avg_pos starts moving away from the origin instead of getting
318          * closer to it. */
319         float len = len_v3v3(gftd.pos_avg, pose_origin);
320         if (len < prev_len) {
321           prev_len = len;
322           grow_next_iteration = true;
323         }
324         else {
325           grow_next_iteration = false;
326           memcpy(pose_factor, data.prev_mask, SCULPT_vertex_count_get(ss) * sizeof(float));
327         }
328       }
329       else {
330         /* Test with length. Used to calculate the origin positions of the IK chain. */
331         /* Stops when the factors have grown enough to generate a new segment origin. */
332         float len = len_v3v3(gftd.pos_avg, pose_target);
333         if (len < max_len) {
334           prev_len = len;
335           grow_next_iteration = true;
336         }
337         else {
338           grow_next_iteration = false;
339           if (r_pose_origin) {
340             copy_v3_v3(r_pose_origin, gftd.pos_avg);
341           }
342           memcpy(pose_factor, data.prev_mask, SCULPT_vertex_count_get(ss) * sizeof(float));
343         }
344       }
345     }
346     else {
347       if (r_pose_origin) {
348         copy_v3_v3(r_pose_origin, pose_target);
349       }
350       grow_next_iteration = false;
351     }
352   }
353   MEM_freeN(data.prev_mask);
354 
355   MEM_SAFE_FREE(nodes);
356 }
357 
sculpt_pose_brush_is_vertex_inside_brush_radius(const float vertex[3],const float br_co[3],float radius,char symm)358 static bool sculpt_pose_brush_is_vertex_inside_brush_radius(const float vertex[3],
359                                                             const float br_co[3],
360                                                             float radius,
361                                                             char symm)
362 {
363   for (char i = 0; i <= symm; ++i) {
364     if (SCULPT_is_symmetry_iteration_valid(i, symm)) {
365       float location[3];
366       flip_v3_v3(location, br_co, (char)i);
367       if (len_v3v3(location, vertex) < radius) {
368         return true;
369       }
370     }
371   }
372   return false;
373 }
374 
375 typedef struct PoseFloodFillData {
376   float pose_initial_co[3];
377   float radius;
378   int symm;
379 
380   float *pose_factor;
381   float pose_origin[3];
382   int tot_co;
383 
384   int current_face_set;
385   int next_face_set;
386   int prev_face_set;
387   int next_vertex;
388 
389   bool next_face_set_found;
390 
391   /* Store the visited face sets to avoid going back when calculating the chain. */
392   GSet *visited_face_sets;
393 
394   /* In face sets origin mode, each vertex can only be assigned to one face set. */
395   BLI_bitmap *is_weighted;
396 
397   bool is_first_iteration;
398 
399   /* In topology mode this stores the furthest point from the stroke origin for cases when a pose
400    * origin based on the brush radius can't be set. */
401   float fallback_floodfill_origin[3];
402 
403   /* Fallback origin. If we can't find any face set to continue, use the position of all vertices
404    * that have the current face set. */
405   float fallback_origin[3];
406   int fallback_count;
407 
408   /* Face Set FK mode. */
409   int *floodfill_it;
410   float *fk_weights;
411   int initial_face_set;
412   int masked_face_set_it;
413   int masked_face_set;
414   int target_face_set;
415 } PoseFloodFillData;
416 
pose_topology_floodfill_cb(SculptSession * ss,int UNUSED (from_v),int to_v,bool is_duplicate,void * userdata)417 static bool pose_topology_floodfill_cb(
418     SculptSession *ss, int UNUSED(from_v), int to_v, bool is_duplicate, void *userdata)
419 {
420   PoseFloodFillData *data = userdata;
421   const float *co = SCULPT_vertex_co_get(ss, to_v);
422 
423   if (data->pose_factor) {
424     data->pose_factor[to_v] = 1.0f;
425   }
426 
427   if (len_squared_v3v3(data->pose_initial_co, data->fallback_floodfill_origin) <
428       len_squared_v3v3(data->pose_initial_co, co)) {
429     copy_v3_v3(data->fallback_floodfill_origin, co);
430   }
431 
432   if (sculpt_pose_brush_is_vertex_inside_brush_radius(
433           co, data->pose_initial_co, data->radius, data->symm)) {
434     return true;
435   }
436   if (SCULPT_check_vertex_pivot_symmetry(co, data->pose_initial_co, data->symm)) {
437     if (!is_duplicate) {
438       add_v3_v3(data->pose_origin, co);
439       data->tot_co++;
440     }
441   }
442 
443   return false;
444 }
445 
pose_face_sets_floodfill_cb(SculptSession * ss,int UNUSED (from_v),int to_v,bool is_duplicate,void * userdata)446 static bool pose_face_sets_floodfill_cb(
447     SculptSession *ss, int UNUSED(from_v), int to_v, bool is_duplicate, void *userdata)
448 {
449   PoseFloodFillData *data = userdata;
450 
451   const int index = to_v;
452   bool visit_next = false;
453 
454   const float *co = SCULPT_vertex_co_get(ss, index);
455   const bool symmetry_check = SCULPT_check_vertex_pivot_symmetry(
456                                   co, data->pose_initial_co, data->symm) &&
457                               !is_duplicate;
458 
459   /* First iteration. Continue expanding using topology until a vertex is outside the brush radius
460    * to determine the first face set. */
461   if (data->current_face_set == SCULPT_FACE_SET_NONE) {
462 
463     data->pose_factor[index] = 1.0f;
464     BLI_BITMAP_ENABLE(data->is_weighted, index);
465 
466     if (sculpt_pose_brush_is_vertex_inside_brush_radius(
467             co, data->pose_initial_co, data->radius, data->symm)) {
468       const int visited_face_set = SCULPT_vertex_face_set_get(ss, index);
469       BLI_gset_add(data->visited_face_sets, POINTER_FROM_INT(visited_face_set));
470     }
471     else if (symmetry_check) {
472       data->current_face_set = SCULPT_vertex_face_set_get(ss, index);
473       BLI_gset_add(data->visited_face_sets, POINTER_FROM_INT(data->current_face_set));
474     }
475     return true;
476   }
477 
478   /* We already have a current face set, so we can start checking the face sets of the vertices. */
479   /* In the first iteration we need to check all face sets we already visited as the flood fill may
480    * still not be finished in some of them. */
481   bool is_vertex_valid = false;
482   if (data->is_first_iteration) {
483     GSetIterator gs_iter;
484     GSET_ITER (gs_iter, data->visited_face_sets) {
485       const int visited_face_set = POINTER_AS_INT(BLI_gsetIterator_getKey(&gs_iter));
486       is_vertex_valid |= SCULPT_vertex_has_face_set(ss, index, visited_face_set);
487     }
488   }
489   else {
490     is_vertex_valid = SCULPT_vertex_has_face_set(ss, index, data->current_face_set);
491   }
492 
493   if (is_vertex_valid) {
494 
495     if (!BLI_BITMAP_TEST(data->is_weighted, index)) {
496       data->pose_factor[index] = 1.0f;
497       BLI_BITMAP_ENABLE(data->is_weighted, index);
498       visit_next = true;
499     }
500 
501     /* Fallback origin accumulation. */
502     if (symmetry_check) {
503       add_v3_v3(data->fallback_origin, SCULPT_vertex_co_get(ss, index));
504       data->fallback_count++;
505     }
506 
507     if (symmetry_check && !SCULPT_vertex_has_unique_face_set(ss, index)) {
508 
509       /* We only add coordinates for calculating the origin when it is possible to go from this
510        * vertex to another vertex in a valid face set for the next iteration. */
511       bool count_as_boundary = false;
512 
513       SculptVertexNeighborIter ni;
514       SCULPT_VERTEX_NEIGHBORS_ITER_BEGIN (ss, index, ni) {
515         int next_face_set_candidate = SCULPT_vertex_face_set_get(ss, ni.index);
516 
517         /* Check if we can get a valid face set for the next iteration from this neighbor. */
518         if (SCULPT_vertex_has_unique_face_set(ss, ni.index) &&
519             !BLI_gset_haskey(data->visited_face_sets, POINTER_FROM_INT(next_face_set_candidate))) {
520           if (!data->next_face_set_found) {
521             data->next_face_set = next_face_set_candidate;
522             data->next_vertex = ni.index;
523             data->next_face_set_found = true;
524           }
525           count_as_boundary = true;
526         }
527       }
528       SCULPT_VERTEX_NEIGHBORS_ITER_END(ni);
529 
530       /* Origin accumulation. */
531       if (count_as_boundary) {
532         add_v3_v3(data->pose_origin, SCULPT_vertex_co_get(ss, index));
533         data->tot_co++;
534       }
535     }
536   }
537   return visit_next;
538 }
539 
540 /* Public functions. */
541 
542 /**
543  * Calculate the pose origin and (Optionally the pose factor)
544  * that is used when using the pose brush.
545  *
546  * \param r_pose_origin: Must be a valid pointer.
547  * \param r_pose_factor: Optional, when set to NULL it won't be calculated.
548  */
SCULPT_pose_calc_pose_data(Sculpt * sd,Object * ob,SculptSession * ss,float initial_location[3],float radius,float pose_offset,float * r_pose_origin,float * r_pose_factor)549 void SCULPT_pose_calc_pose_data(Sculpt *sd,
550                                 Object *ob,
551                                 SculptSession *ss,
552                                 float initial_location[3],
553                                 float radius,
554                                 float pose_offset,
555                                 float *r_pose_origin,
556                                 float *r_pose_factor)
557 {
558   SCULPT_vertex_random_access_ensure(ss);
559 
560   /* Calculate the pose rotation point based on the boundaries of the brush factor. */
561   SculptFloodFill flood;
562   SCULPT_floodfill_init(ss, &flood);
563   SCULPT_floodfill_add_active(sd, ob, ss, &flood, (r_pose_factor) ? radius : 0.0f);
564 
565   PoseFloodFillData fdata = {
566       .radius = radius,
567       .symm = SCULPT_mesh_symmetry_xyz_get(ob),
568       .pose_factor = r_pose_factor,
569       .tot_co = 0,
570   };
571   zero_v3(fdata.pose_origin);
572   copy_v3_v3(fdata.pose_initial_co, initial_location);
573   copy_v3_v3(fdata.fallback_floodfill_origin, initial_location);
574   SCULPT_floodfill_execute(ss, &flood, pose_topology_floodfill_cb, &fdata);
575   SCULPT_floodfill_free(&flood);
576 
577   if (fdata.tot_co > 0) {
578     mul_v3_fl(fdata.pose_origin, 1.0f / (float)fdata.tot_co);
579   }
580   else {
581     copy_v3_v3(fdata.pose_origin, fdata.fallback_floodfill_origin);
582   }
583 
584   /* Offset the pose origin. */
585   float pose_d[3];
586   sub_v3_v3v3(pose_d, fdata.pose_origin, fdata.pose_initial_co);
587   normalize_v3(pose_d);
588   madd_v3_v3fl(fdata.pose_origin, pose_d, radius * pose_offset);
589   copy_v3_v3(r_pose_origin, fdata.pose_origin);
590 
591   /* Do the initial grow of the factors to get the first segment of the chain with Origin Offset.
592    */
593   if (pose_offset != 0.0f && r_pose_factor) {
594     sculpt_pose_grow_pose_factor(
595         sd, ob, ss, fdata.pose_origin, fdata.pose_origin, 0, NULL, r_pose_factor);
596   }
597 }
598 
pose_brush_init_task_cb_ex(void * __restrict userdata,const int n,const TaskParallelTLS * __restrict UNUSED (tls))599 static void pose_brush_init_task_cb_ex(void *__restrict userdata,
600                                        const int n,
601                                        const TaskParallelTLS *__restrict UNUSED(tls))
602 {
603   SculptThreadedTaskData *data = userdata;
604   SculptSession *ss = data->ob->sculpt;
605   PBVHVertexIter vd;
606   BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
607   {
608     SculptVertexNeighborIter ni;
609     float avg = 0.0f;
610     int total = 0;
611     SCULPT_VERTEX_NEIGHBORS_ITER_BEGIN (ss, vd.index, ni) {
612       avg += data->pose_factor[ni.index];
613       total++;
614     }
615     SCULPT_VERTEX_NEIGHBORS_ITER_END(ni);
616 
617     if (total > 0) {
618       data->pose_factor[vd.index] = avg / total;
619     }
620   }
621   BKE_pbvh_vertex_iter_end;
622 }
623 
624 /* Init the IK chain with empty weights. */
pose_ik_chain_new(const int totsegments,const int totverts)625 static SculptPoseIKChain *pose_ik_chain_new(const int totsegments, const int totverts)
626 {
627   SculptPoseIKChain *ik_chain = MEM_callocN(sizeof(SculptPoseIKChain), "Pose IK Chain");
628   ik_chain->tot_segments = totsegments;
629   ik_chain->segments = MEM_callocN(totsegments * sizeof(SculptPoseIKChainSegment),
630                                    "Pose IK Chain Segments");
631   for (int i = 0; i < totsegments; i++) {
632     ik_chain->segments[i].weights = MEM_callocN(totverts * sizeof(float), "Pose IK weights");
633   }
634   return ik_chain;
635 }
636 
637 /* Init the origin/head pairs of all the segments from the calculated origins. */
pose_ik_chain_origin_heads_init(SculptPoseIKChain * ik_chain,const float initial_location[3])638 static void pose_ik_chain_origin_heads_init(SculptPoseIKChain *ik_chain,
639                                             const float initial_location[3])
640 {
641   float origin[3];
642   float head[3];
643   for (int i = 0; i < ik_chain->tot_segments; i++) {
644     if (i == 0) {
645       copy_v3_v3(head, initial_location);
646       copy_v3_v3(origin, ik_chain->segments[i].orig);
647     }
648     else {
649       copy_v3_v3(head, ik_chain->segments[i - 1].orig);
650       copy_v3_v3(origin, ik_chain->segments[i].orig);
651     }
652     copy_v3_v3(ik_chain->segments[i].orig, origin);
653     copy_v3_v3(ik_chain->segments[i].initial_orig, origin);
654     copy_v3_v3(ik_chain->segments[i].head, head);
655     copy_v3_v3(ik_chain->segments[i].initial_head, head);
656     ik_chain->segments[i].len = len_v3v3(head, origin);
657     copy_v3_fl(ik_chain->segments[i].scale, 1.0f);
658   }
659 }
660 
pose_brush_num_effective_segments(const Brush * brush)661 static int pose_brush_num_effective_segments(const Brush *brush)
662 {
663   /* Scaling multiple segments at the same time is not supported as the IK solver can't handle
664    * changes in the segment's length. It will also required a better weight distribution to avoid
665    * artifacts in the areas affected by multiple segments. */
666   if (ELEM(brush->pose_deform_type,
667            BRUSH_POSE_DEFORM_SCALE_TRASLATE,
668            BRUSH_POSE_DEFORM_SQUASH_STRETCH)) {
669     return 1;
670   }
671   return brush->pose_ik_segments;
672 }
673 
pose_ik_chain_init_topology(Sculpt * sd,Object * ob,SculptSession * ss,Brush * br,const float initial_location[3],const float radius)674 static SculptPoseIKChain *pose_ik_chain_init_topology(Sculpt *sd,
675                                                       Object *ob,
676                                                       SculptSession *ss,
677                                                       Brush *br,
678                                                       const float initial_location[3],
679                                                       const float radius)
680 {
681 
682   const float chain_segment_len = radius * (1.0f + br->pose_offset);
683   float next_chain_segment_target[3];
684 
685   int totvert = SCULPT_vertex_count_get(ss);
686   int nearest_vertex_index = SCULPT_nearest_vertex_get(sd, ob, initial_location, FLT_MAX, true);
687 
688   /* Init the buffers used to keep track of the changes in the pose factors as more segments are
689    * added to the IK chain. */
690 
691   /* This stores the whole pose factors values as they grow through the mesh. */
692   float *pose_factor_grow = MEM_callocN(totvert * sizeof(float), "Pose Factor Grow");
693 
694   /* This stores the previous status of the factors when growing a new iteration. */
695   float *pose_factor_grow_prev = MEM_callocN(totvert * sizeof(float),
696                                              "Pose Factor Grow Prev Iteration");
697 
698   pose_factor_grow[nearest_vertex_index] = 1.0f;
699 
700   const int tot_segments = pose_brush_num_effective_segments(br);
701   SculptPoseIKChain *ik_chain = pose_ik_chain_new(tot_segments, totvert);
702 
703   /* Calculate the first segment in the chain using the brush radius and the pose origin offset. */
704   copy_v3_v3(next_chain_segment_target, initial_location);
705   SCULPT_pose_calc_pose_data(sd,
706                              ob,
707                              ss,
708                              next_chain_segment_target,
709                              radius,
710                              br->pose_offset,
711                              ik_chain->segments[0].orig,
712                              pose_factor_grow);
713 
714   copy_v3_v3(next_chain_segment_target, ik_chain->segments[0].orig);
715 
716   /* Init the weights of this segment and store the status of the pose factors to start calculating
717    * new segment origins. */
718   for (int j = 0; j < totvert; j++) {
719     ik_chain->segments[0].weights[j] = pose_factor_grow[j];
720     pose_factor_grow_prev[j] = pose_factor_grow[j];
721   }
722 
723   /* Calculate the next segments in the chain growing the pose factors. */
724   for (int i = 1; i < ik_chain->tot_segments; i++) {
725 
726     /* Grow the factors to get the new segment origin. */
727     sculpt_pose_grow_pose_factor(sd,
728                                  ob,
729                                  ss,
730                                  NULL,
731                                  next_chain_segment_target,
732                                  chain_segment_len,
733                                  ik_chain->segments[i].orig,
734                                  pose_factor_grow);
735     copy_v3_v3(next_chain_segment_target, ik_chain->segments[i].orig);
736 
737     /* Create the weights for this segment from the difference between the previous grow factor
738      * iteration an the current iteration. */
739     for (int j = 0; j < totvert; j++) {
740       ik_chain->segments[i].weights[j] = pose_factor_grow[j] - pose_factor_grow_prev[j];
741       /* Store the current grow factor status for the next interation. */
742       pose_factor_grow_prev[j] = pose_factor_grow[j];
743     }
744   }
745 
746   pose_ik_chain_origin_heads_init(ik_chain, initial_location);
747 
748   MEM_freeN(pose_factor_grow);
749   MEM_freeN(pose_factor_grow_prev);
750 
751   return ik_chain;
752 }
753 
pose_ik_chain_init_face_sets(Sculpt * sd,Object * ob,SculptSession * ss,Brush * br,const float radius)754 static SculptPoseIKChain *pose_ik_chain_init_face_sets(
755     Sculpt *sd, Object *ob, SculptSession *ss, Brush *br, const float radius)
756 {
757 
758   int totvert = SCULPT_vertex_count_get(ss);
759 
760   const int tot_segments = pose_brush_num_effective_segments(br);
761 
762   SculptPoseIKChain *ik_chain = pose_ik_chain_new(tot_segments, totvert);
763 
764   GSet *visited_face_sets = BLI_gset_int_new_ex("visited_face_sets", ik_chain->tot_segments);
765 
766   BLI_bitmap *is_weighted = BLI_BITMAP_NEW(totvert, "weighted");
767 
768   int current_face_set = SCULPT_FACE_SET_NONE;
769   int prev_face_set = SCULPT_FACE_SET_NONE;
770 
771   int current_vertex = SCULPT_active_vertex_get(ss);
772 
773   for (int s = 0; s < ik_chain->tot_segments; s++) {
774 
775     SculptFloodFill flood;
776     SCULPT_floodfill_init(ss, &flood);
777     SCULPT_floodfill_add_initial_with_symmetry(sd, ob, ss, &flood, current_vertex, FLT_MAX);
778 
779     BLI_gset_add(visited_face_sets, POINTER_FROM_INT(current_face_set));
780 
781     PoseFloodFillData fdata = {
782         .radius = radius,
783         .symm = SCULPT_mesh_symmetry_xyz_get(ob),
784         .pose_factor = ik_chain->segments[s].weights,
785         .tot_co = 0,
786         .fallback_count = 0,
787         .current_face_set = current_face_set,
788         .prev_face_set = prev_face_set,
789         .visited_face_sets = visited_face_sets,
790         .is_weighted = is_weighted,
791         .next_face_set_found = false,
792         .is_first_iteration = s == 0,
793     };
794     zero_v3(fdata.pose_origin);
795     zero_v3(fdata.fallback_origin);
796     copy_v3_v3(fdata.pose_initial_co, SCULPT_vertex_co_get(ss, current_vertex));
797     SCULPT_floodfill_execute(ss, &flood, pose_face_sets_floodfill_cb, &fdata);
798     SCULPT_floodfill_free(&flood);
799 
800     if (fdata.tot_co > 0) {
801       mul_v3_fl(fdata.pose_origin, 1.0f / (float)fdata.tot_co);
802       copy_v3_v3(ik_chain->segments[s].orig, fdata.pose_origin);
803     }
804     else if (fdata.fallback_count > 0) {
805       mul_v3_fl(fdata.fallback_origin, 1.0f / (float)fdata.fallback_count);
806       copy_v3_v3(ik_chain->segments[s].orig, fdata.fallback_origin);
807     }
808     else {
809       zero_v3(ik_chain->segments[s].orig);
810     }
811 
812     prev_face_set = fdata.current_face_set;
813     current_face_set = fdata.next_face_set;
814     current_vertex = fdata.next_vertex;
815   }
816 
817   BLI_gset_free(visited_face_sets, NULL);
818 
819   pose_ik_chain_origin_heads_init(ik_chain, SCULPT_active_vertex_co_get(ss));
820 
821   MEM_SAFE_FREE(is_weighted);
822 
823   return ik_chain;
824 }
825 
pose_face_sets_fk_find_masked_floodfill_cb(SculptSession * ss,int from_v,int to_v,bool is_duplicate,void * userdata)826 static bool pose_face_sets_fk_find_masked_floodfill_cb(
827     SculptSession *ss, int from_v, int to_v, bool is_duplicate, void *userdata)
828 {
829   PoseFloodFillData *data = userdata;
830 
831   if (!is_duplicate) {
832     data->floodfill_it[to_v] = data->floodfill_it[from_v] + 1;
833   }
834   else {
835     data->floodfill_it[to_v] = data->floodfill_it[from_v];
836   }
837 
838   const int to_face_set = SCULPT_vertex_face_set_get(ss, to_v);
839   if (!BLI_gset_haskey(data->visited_face_sets, POINTER_FROM_INT(to_face_set))) {
840     if (SCULPT_vertex_has_unique_face_set(ss, to_v) &&
841         !SCULPT_vertex_has_unique_face_set(ss, from_v) &&
842         SCULPT_vertex_has_face_set(ss, from_v, to_face_set)) {
843 
844       BLI_gset_add(data->visited_face_sets, POINTER_FROM_INT(to_face_set));
845 
846       if (data->floodfill_it[to_v] >= data->masked_face_set_it) {
847         data->masked_face_set = to_face_set;
848         data->masked_face_set_it = data->floodfill_it[to_v];
849       }
850 
851       if (data->target_face_set == SCULPT_FACE_SET_NONE) {
852         data->target_face_set = to_face_set;
853       }
854     }
855   }
856 
857   return SCULPT_vertex_has_face_set(ss, to_v, data->initial_face_set);
858 }
859 
pose_face_sets_fk_set_weights_floodfill_cb(SculptSession * ss,int UNUSED (from_v),int to_v,bool UNUSED (is_duplicate),void * userdata)860 static bool pose_face_sets_fk_set_weights_floodfill_cb(
861     SculptSession *ss, int UNUSED(from_v), int to_v, bool UNUSED(is_duplicate), void *userdata)
862 {
863   PoseFloodFillData *data = userdata;
864   data->fk_weights[to_v] = 1.0f;
865   return !SCULPT_vertex_has_face_set(ss, to_v, data->masked_face_set);
866 }
867 
pose_ik_chain_init_face_sets_fk(Sculpt * sd,Object * ob,SculptSession * ss,const float radius,const float * initial_location)868 static SculptPoseIKChain *pose_ik_chain_init_face_sets_fk(
869     Sculpt *sd, Object *ob, SculptSession *ss, const float radius, const float *initial_location)
870 {
871   const int totvert = SCULPT_vertex_count_get(ss);
872 
873   SculptPoseIKChain *ik_chain = pose_ik_chain_new(1, totvert);
874 
875   const int active_vertex = SCULPT_active_vertex_get(ss);
876   const int active_face_set = SCULPT_active_face_set_get(ss);
877 
878   SculptFloodFill flood;
879   SCULPT_floodfill_init(ss, &flood);
880   SCULPT_floodfill_add_initial(&flood, active_vertex);
881   PoseFloodFillData fdata;
882   fdata.floodfill_it = MEM_calloc_arrayN(totvert, sizeof(int), "floodfill iteration");
883   fdata.floodfill_it[active_vertex] = 1;
884   fdata.initial_face_set = active_face_set;
885   fdata.masked_face_set = SCULPT_FACE_SET_NONE;
886   fdata.target_face_set = SCULPT_FACE_SET_NONE;
887   fdata.masked_face_set_it = 0;
888   fdata.visited_face_sets = BLI_gset_int_new_ex("visited_face_sets", 3);
889   SCULPT_floodfill_execute(ss, &flood, pose_face_sets_fk_find_masked_floodfill_cb, &fdata);
890   SCULPT_floodfill_free(&flood);
891   BLI_gset_free(fdata.visited_face_sets, NULL);
892 
893   int origin_count = 0;
894   float origin_acc[3] = {0.0f};
895   for (int i = 0; i < totvert; i++) {
896     if (fdata.floodfill_it[i] != 0 && SCULPT_vertex_has_face_set(ss, i, fdata.initial_face_set) &&
897         SCULPT_vertex_has_face_set(ss, i, fdata.masked_face_set)) {
898       add_v3_v3(origin_acc, SCULPT_vertex_co_get(ss, i));
899       origin_count++;
900     }
901   }
902 
903   int target_count = 0;
904   float target_acc[3] = {0.0f};
905   if (fdata.target_face_set != fdata.masked_face_set) {
906     for (int i = 0; i < totvert; i++) {
907       if (fdata.floodfill_it[i] != 0 &&
908           SCULPT_vertex_has_face_set(ss, i, fdata.initial_face_set) &&
909           SCULPT_vertex_has_face_set(ss, i, fdata.target_face_set)) {
910         add_v3_v3(target_acc, SCULPT_vertex_co_get(ss, i));
911         target_count++;
912       }
913     }
914   }
915 
916   MEM_freeN(fdata.floodfill_it);
917 
918   if (origin_count > 0) {
919     copy_v3_v3(ik_chain->segments[0].orig, origin_acc);
920     mul_v3_fl(ik_chain->segments[0].orig, 1.0f / origin_count);
921   }
922   else {
923     zero_v3(ik_chain->segments[0].orig);
924   }
925 
926   if (target_count > 0) {
927     copy_v3_v3(ik_chain->segments[0].head, target_acc);
928     mul_v3_fl(ik_chain->segments[0].head, 1.0f / target_count);
929     sub_v3_v3v3(ik_chain->grab_delta_offset, ik_chain->segments[0].head, initial_location);
930   }
931   else {
932     copy_v3_v3(ik_chain->segments[0].head, initial_location);
933   }
934 
935   SCULPT_floodfill_init(ss, &flood);
936   SCULPT_floodfill_add_active(sd, ob, ss, &flood, radius);
937   fdata.fk_weights = ik_chain->segments[0].weights;
938   SCULPT_floodfill_execute(ss, &flood, pose_face_sets_fk_set_weights_floodfill_cb, &fdata);
939   SCULPT_floodfill_free(&flood);
940 
941   pose_ik_chain_origin_heads_init(ik_chain, ik_chain->segments[0].head);
942   return ik_chain;
943 }
944 
SCULPT_pose_ik_chain_init(Sculpt * sd,Object * ob,SculptSession * ss,Brush * br,const float initial_location[3],const float radius)945 SculptPoseIKChain *SCULPT_pose_ik_chain_init(Sculpt *sd,
946                                              Object *ob,
947                                              SculptSession *ss,
948                                              Brush *br,
949                                              const float initial_location[3],
950                                              const float radius)
951 {
952   SculptPoseIKChain *ik_chain = NULL;
953 
954   const bool use_fake_neighbors = !(br->flag2 & BRUSH_USE_CONNECTED_ONLY);
955 
956   if (use_fake_neighbors) {
957     SCULPT_fake_neighbors_ensure(sd, ob, br->disconnected_distance_max);
958     SCULPT_fake_neighbors_enable(ob);
959   }
960 
961   switch (br->pose_origin_type) {
962     case BRUSH_POSE_ORIGIN_TOPOLOGY:
963       ik_chain = pose_ik_chain_init_topology(sd, ob, ss, br, initial_location, radius);
964       break;
965     case BRUSH_POSE_ORIGIN_FACE_SETS:
966       ik_chain = pose_ik_chain_init_face_sets(sd, ob, ss, br, radius);
967       break;
968     case BRUSH_POSE_ORIGIN_FACE_SETS_FK:
969       ik_chain = pose_ik_chain_init_face_sets_fk(sd, ob, ss, radius, initial_location);
970       break;
971   }
972 
973   if (use_fake_neighbors) {
974     SCULPT_fake_neighbors_disable(ob);
975   }
976 
977   return ik_chain;
978 }
979 
SCULPT_pose_brush_init(Sculpt * sd,Object * ob,SculptSession * ss,Brush * br)980 void SCULPT_pose_brush_init(Sculpt *sd, Object *ob, SculptSession *ss, Brush *br)
981 {
982   PBVHNode **nodes;
983   PBVH *pbvh = ob->sculpt->pbvh;
984   int totnode;
985 
986   BKE_pbvh_search_gather(pbvh, NULL, NULL, &nodes, &totnode);
987 
988   SculptThreadedTaskData data = {
989       .sd = sd,
990       .ob = ob,
991       .brush = br,
992       .nodes = nodes,
993   };
994 
995   /* Init the IK chain that is going to be used to deform the vertices. */
996   ss->cache->pose_ik_chain = SCULPT_pose_ik_chain_init(
997       sd, ob, ss, br, ss->cache->true_location, ss->cache->radius);
998 
999   /* Smooth the weights of each segment for cleaner deformation. */
1000   for (int ik = 0; ik < ss->cache->pose_ik_chain->tot_segments; ik++) {
1001     data.pose_factor = ss->cache->pose_ik_chain->segments[ik].weights;
1002     for (int i = 0; i < br->pose_smooth_iterations; i++) {
1003       TaskParallelSettings settings;
1004       BKE_pbvh_parallel_range_settings(&settings, true, totnode);
1005       BLI_task_parallel_range(0, totnode, &data, pose_brush_init_task_cb_ex, &settings);
1006     }
1007   }
1008 
1009   MEM_SAFE_FREE(nodes);
1010 }
1011 
sculpt_pose_do_translate_deform(SculptSession * ss,Brush * brush)1012 static void sculpt_pose_do_translate_deform(SculptSession *ss, Brush *brush)
1013 {
1014   SculptPoseIKChain *ik_chain = ss->cache->pose_ik_chain;
1015   BKE_curvemapping_init(brush->curve);
1016   pose_solve_translate_chain(ik_chain, ss->cache->grab_delta);
1017 }
1018 
1019 /* Calculate a scale factor based on the grab delta. */
sculpt_pose_get_scale_from_grab_delta(SculptSession * ss,const float ik_target[3])1020 static float sculpt_pose_get_scale_from_grab_delta(SculptSession *ss, const float ik_target[3])
1021 {
1022   SculptPoseIKChain *ik_chain = ss->cache->pose_ik_chain;
1023   float plane[4];
1024   float segment_dir[3];
1025   sub_v3_v3v3(segment_dir, ik_chain->segments[0].initial_head, ik_chain->segments[0].initial_orig);
1026   normalize_v3(segment_dir);
1027   plane_from_point_normal_v3(plane, ik_chain->segments[0].initial_head, segment_dir);
1028   const float segment_len = ik_chain->segments[0].len;
1029   return segment_len / (segment_len - dist_signed_to_plane_v3(ik_target, plane));
1030 }
1031 
sculpt_pose_do_scale_deform(SculptSession * ss,Brush * brush)1032 static void sculpt_pose_do_scale_deform(SculptSession *ss, Brush *brush)
1033 {
1034   float ik_target[3];
1035   SculptPoseIKChain *ik_chain = ss->cache->pose_ik_chain;
1036 
1037   copy_v3_v3(ik_target, ss->cache->true_location);
1038   add_v3_v3(ik_target, ss->cache->grab_delta);
1039 
1040   /* Solve the IK for the first segment to include rotation as part of scale if enabled. */
1041   if (!(brush->flag2 & BRUSH_POSE_USE_LOCK_ROTATION)) {
1042     pose_solve_ik_chain(ik_chain, ik_target, brush->flag2 & BRUSH_POSE_IK_ANCHORED);
1043   }
1044 
1045   float scale[3];
1046   copy_v3_fl(scale, sculpt_pose_get_scale_from_grab_delta(ss, ik_target));
1047 
1048   /* Write the scale into the segments. */
1049   pose_solve_scale_chain(ik_chain, scale);
1050 }
1051 
sculpt_pose_do_twist_deform(SculptSession * ss,Brush * brush)1052 static void sculpt_pose_do_twist_deform(SculptSession *ss, Brush *brush)
1053 {
1054   SculptPoseIKChain *ik_chain = ss->cache->pose_ik_chain;
1055 
1056   /* Calculate the maximum roll. 0.02 radians per pixel works fine. */
1057   float roll = (ss->cache->initial_mouse[0] - ss->cache->mouse[0]) * ss->cache->bstrength * 0.02f;
1058   BKE_curvemapping_init(brush->curve);
1059   pose_solve_roll_chain(ik_chain, brush, roll);
1060 }
1061 
sculpt_pose_do_rotate_deform(SculptSession * ss,Brush * brush)1062 static void sculpt_pose_do_rotate_deform(SculptSession *ss, Brush *brush)
1063 {
1064   float ik_target[3];
1065   SculptPoseIKChain *ik_chain = ss->cache->pose_ik_chain;
1066 
1067   /* Calculate the IK target. */
1068   copy_v3_v3(ik_target, ss->cache->true_location);
1069   add_v3_v3(ik_target, ss->cache->grab_delta);
1070   add_v3_v3(ik_target, ik_chain->grab_delta_offset);
1071 
1072   /* Solve the IK positions. */
1073   pose_solve_ik_chain(ik_chain, ik_target, brush->flag2 & BRUSH_POSE_IK_ANCHORED);
1074 }
1075 
sculpt_pose_do_rotate_twist_deform(SculptSession * ss,Brush * brush)1076 static void sculpt_pose_do_rotate_twist_deform(SculptSession *ss, Brush *brush)
1077 {
1078   if (ss->cache->invert) {
1079     sculpt_pose_do_twist_deform(ss, brush);
1080   }
1081   else {
1082     sculpt_pose_do_rotate_deform(ss, brush);
1083   }
1084 }
1085 
sculpt_pose_do_scale_translate_deform(SculptSession * ss,Brush * brush)1086 static void sculpt_pose_do_scale_translate_deform(SculptSession *ss, Brush *brush)
1087 {
1088   if (ss->cache->invert) {
1089     sculpt_pose_do_translate_deform(ss, brush);
1090   }
1091   else {
1092     sculpt_pose_do_scale_deform(ss, brush);
1093   }
1094 }
1095 
sculpt_pose_do_squash_stretch_deform(SculptSession * ss,Brush * UNUSED (brush))1096 static void sculpt_pose_do_squash_stretch_deform(SculptSession *ss, Brush *UNUSED(brush))
1097 {
1098   float ik_target[3];
1099   SculptPoseIKChain *ik_chain = ss->cache->pose_ik_chain;
1100 
1101   copy_v3_v3(ik_target, ss->cache->true_location);
1102   add_v3_v3(ik_target, ss->cache->grab_delta);
1103 
1104   float scale[3];
1105   scale[2] = sculpt_pose_get_scale_from_grab_delta(ss, ik_target);
1106   scale[0] = scale[1] = sqrtf(1.0f / scale[2]);
1107 
1108   /* Write the scale into the segments. */
1109   pose_solve_scale_chain(ik_chain, scale);
1110 }
1111 
sculpt_pose_align_pivot_local_space(float r_mat[4][4],ePaintSymmetryFlags symm,ePaintSymmetryAreas symm_area,SculptPoseIKChainSegment * segment,const float grab_location[3])1112 static void sculpt_pose_align_pivot_local_space(float r_mat[4][4],
1113                                                 ePaintSymmetryFlags symm,
1114                                                 ePaintSymmetryAreas symm_area,
1115                                                 SculptPoseIKChainSegment *segment,
1116                                                 const float grab_location[3])
1117 {
1118   float segment_origin_head[3];
1119   float symm_head[3];
1120   float symm_orig[3];
1121 
1122   copy_v3_v3(symm_head, segment->head);
1123   copy_v3_v3(symm_orig, segment->orig);
1124 
1125   SCULPT_flip_v3_by_symm_area(symm_head, symm, symm_area, grab_location);
1126   SCULPT_flip_v3_by_symm_area(symm_orig, symm, symm_area, grab_location);
1127 
1128   sub_v3_v3v3(segment_origin_head, symm_head, symm_orig);
1129   normalize_v3(segment_origin_head);
1130 
1131   copy_v3_v3(r_mat[2], segment_origin_head);
1132   ortho_basis_v3v3_v3(r_mat[0], r_mat[1], r_mat[2]);
1133 }
1134 
1135 /* Main Brush Function. */
SCULPT_do_pose_brush(Sculpt * sd,Object * ob,PBVHNode ** nodes,int totnode)1136 void SCULPT_do_pose_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
1137 {
1138   SculptSession *ss = ob->sculpt;
1139   Brush *brush = BKE_paint_brush(&sd->paint);
1140   const ePaintSymmetryFlags symm = SCULPT_mesh_symmetry_xyz_get(ob);
1141 
1142   /* The pose brush applies all enabled symmetry axis in a single iteration, so the rest can be
1143    * ignored. */
1144   if (ss->cache->mirror_symmetry_pass != 0) {
1145     return;
1146   }
1147 
1148   SculptPoseIKChain *ik_chain = ss->cache->pose_ik_chain;
1149 
1150   switch (brush->pose_deform_type) {
1151     case BRUSH_POSE_DEFORM_ROTATE_TWIST:
1152       sculpt_pose_do_rotate_twist_deform(ss, brush);
1153       break;
1154     case BRUSH_POSE_DEFORM_SCALE_TRASLATE:
1155       sculpt_pose_do_scale_translate_deform(ss, brush);
1156       break;
1157     case BRUSH_POSE_DEFORM_SQUASH_STRETCH:
1158       sculpt_pose_do_squash_stretch_deform(ss, brush);
1159       break;
1160   }
1161 
1162   /* Flip the segment chain in all symmetry axis and calculate the transform matrices for each
1163    * possible combination. */
1164   /* This can be optimized by skipping the calculation of matrices where the symmetry is not
1165    * enabled. */
1166   for (int symm_it = 0; symm_it < PAINT_SYMM_AREAS; symm_it++) {
1167     for (int i = 0; i < ik_chain->tot_segments; i++) {
1168       float symm_rot[4];
1169       float symm_orig[3];
1170       float symm_initial_orig[3];
1171 
1172       ePaintSymmetryAreas symm_area = symm_it;
1173 
1174       copy_qt_qt(symm_rot, ik_chain->segments[i].rot);
1175       copy_v3_v3(symm_orig, ik_chain->segments[i].orig);
1176       copy_v3_v3(symm_initial_orig, ik_chain->segments[i].initial_orig);
1177 
1178       /* Flip the origins and rotation quats of each segment. */
1179       SCULPT_flip_quat_by_symm_area(symm_rot, symm, symm_area, ss->cache->orig_grab_location);
1180       SCULPT_flip_v3_by_symm_area(symm_orig, symm, symm_area, ss->cache->orig_grab_location);
1181       SCULPT_flip_v3_by_symm_area(
1182           symm_initial_orig, symm, symm_area, ss->cache->orig_grab_location);
1183 
1184       float pivot_local_space[4][4];
1185       unit_m4(pivot_local_space);
1186 
1187       /* Align the segment pivot local space to the Z axis. */
1188       if (brush->pose_deform_type == BRUSH_POSE_DEFORM_SQUASH_STRETCH) {
1189         sculpt_pose_align_pivot_local_space(pivot_local_space,
1190                                             symm,
1191                                             symm_area,
1192                                             &ik_chain->segments[i],
1193                                             ss->cache->orig_grab_location);
1194         unit_m4(ik_chain->segments[i].trans_mat[symm_it]);
1195       }
1196       else {
1197         quat_to_mat4(ik_chain->segments[i].trans_mat[symm_it], symm_rot);
1198       }
1199 
1200       /* Apply segement scale to the transform. */
1201       for (int scale_i = 0; scale_i < 3; scale_i++) {
1202         mul_v3_fl(ik_chain->segments[i].trans_mat[symm_it][scale_i],
1203                   ik_chain->segments[i].scale[scale_i]);
1204       }
1205 
1206       translate_m4(ik_chain->segments[i].trans_mat[symm_it],
1207                    symm_orig[0] - symm_initial_orig[0],
1208                    symm_orig[1] - symm_initial_orig[1],
1209                    symm_orig[2] - symm_initial_orig[2]);
1210 
1211       unit_m4(ik_chain->segments[i].pivot_mat[symm_it]);
1212       translate_m4(
1213           ik_chain->segments[i].pivot_mat[symm_it], symm_orig[0], symm_orig[1], symm_orig[2]);
1214       mul_m4_m4_post(ik_chain->segments[i].pivot_mat[symm_it], pivot_local_space);
1215 
1216       invert_m4_m4(ik_chain->segments[i].pivot_mat_inv[symm_it],
1217                    ik_chain->segments[i].pivot_mat[symm_it]);
1218     }
1219   }
1220 
1221   SculptThreadedTaskData data = {
1222       .sd = sd,
1223       .ob = ob,
1224       .brush = brush,
1225       .nodes = nodes,
1226   };
1227 
1228   TaskParallelSettings settings;
1229   BKE_pbvh_parallel_range_settings(&settings, true, totnode);
1230   BLI_task_parallel_range(0, totnode, &data, do_pose_brush_task_cb_ex, &settings);
1231 }
1232 
SCULPT_pose_ik_chain_free(SculptPoseIKChain * ik_chain)1233 void SCULPT_pose_ik_chain_free(SculptPoseIKChain *ik_chain)
1234 {
1235   for (int i = 0; i < ik_chain->tot_segments; i++) {
1236     MEM_SAFE_FREE(ik_chain->segments[i].weights);
1237   }
1238   MEM_SAFE_FREE(ik_chain->segments);
1239   MEM_SAFE_FREE(ik_chain);
1240 }
1241