Blender V5.3
grease_pencil_weight_paint.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include "BKE_armature.hh"
10#include "BKE_brush.hh"
11#include "BKE_context.hh"
12#include "BKE_crazyspace.hh"
13#include "BKE_deform.hh"
14#include "BKE_grease_pencil.hh"
15#include "BKE_modifier.hh"
16#include "BKE_object_deform.h"
17#include "BKE_paint.hh"
18#include "BKE_report.hh"
19
20#include "BLI_listbase.hh"
21#include "BLI_math_geom_c.hh"
22#include "BLI_math_matrix_c.hh"
23
24#include "DNA_brush_types.h"
25#include "DNA_meshdata_types.h"
26#include "DNA_object_types.h"
27
28#include "RNA_access.hh"
29#include "RNA_define.hh"
30
31#include "ED_curves.hh"
32#include "ED_grease_pencil.hh"
33#include "ED_view3d.hh"
34
36
37#include "GEO_smooth_curves.hh"
38
39namespace blender {
40
41namespace ed::greasepencil {
42
44{
45 /* Get all vertex group names in the object. */
46 const ListBaseT<bDeformGroup> *defbase = BKE_object_defgroup_list(&object);
47 Set<std::string> defgroups;
48 for (bDeformGroup &dg : *defbase) {
49 defgroups.add(dg.name);
50 }
51
52 /* Inspect all armature modifiers in the object. */
53 Set<std::string> bone_deformed_vgroups;
54 VirtualModifierData virtual_modifier_data;
55 ModifierData *md = BKE_modifiers_get_virtual_modifierlist(&object, &virtual_modifier_data);
56 for (; md; md = md->next) {
59 {
60 continue;
61 }
63 md);
64 if (!gamd->object || !gamd->object->pose) {
65 continue;
66 }
67
68 bPose *pose = gamd->object->pose;
69 for (bPoseChannel &channel : pose->chanbase) {
70 if (channel.bone_get(*gamd->object)->flag & BONE_NO_DEFORM) {
71 continue;
72 }
73 /* When a vertex group name matches the bone name, it is bone-deformed. */
74 if (defgroups.contains(channel.name)) {
75 bone_deformed_vgroups.add(channel.name);
76 }
77 }
78 }
79
80 return bone_deformed_vgroups;
81}
82
83/* Normalize the weights of vertex groups deformed by bones so that the sum is 1.0f.
84 * Returns false when the normalization failed due to too many locked vertex groups. In that case a
85 * second pass can be done with the active vertex group unlocked.
86 */
88 const int vertex_groups_num,
89 const Span<bool> vertex_group_is_bone_deformed,
90 const FunctionRef<bool(int)> vertex_group_is_locked)
91{
92 /* Nothing to normalize when there are less than two vertex group weights. */
93 if (dvert.totweight <= 1) {
94 return true;
95 }
96
97 /* Get the sum of weights of bone-deformed vertex groups. */
98 float sum_weights_total = 0.0f;
99 float sum_weights_locked = 0.0f;
100 float sum_weights_unlocked = 0.0f;
101 int locked_num = 0;
102 int unlocked_num = 0;
103 for (const int i : IndexRange(dvert.totweight)) {
104 MDeformWeight &dw = dvert.dw[i];
105
106 /* Auto-normalize is only applied on bone-deformed vertex groups that have weight already. */
107 if (dw.def_nr >= vertex_groups_num || !vertex_group_is_bone_deformed[dw.def_nr] ||
108 dw.weight <= FLT_EPSILON)
109 {
110 continue;
111 }
112
113 sum_weights_total += dw.weight;
114
115 if (vertex_group_is_locked(dw.def_nr)) {
116 locked_num++;
117 sum_weights_locked += dw.weight;
118 }
119 else {
120 unlocked_num++;
121 sum_weights_unlocked += dw.weight;
122 }
123 }
124
125 /* Already normalized? */
126 if (sum_weights_total == 1.0f) {
127 return true;
128 }
129
130 /* Any unlocked vertex group to normalize? */
131 if (unlocked_num == 0) {
132 /* We don't need a second pass when there is only one locked group (the active group). */
133 return (locked_num == 1);
134 }
135
136 /* Locked groups can make it impossible to fully normalize. */
137 if (sum_weights_locked >= 1.0f - VERTEX_WEIGHT_LOCK_EPSILON) {
138 /* Zero out the weights we are allowed to touch and return false, indicating a second pass is
139 * needed. */
140 for (const int i : IndexRange(dvert.totweight)) {
141 MDeformWeight &dw = dvert.dw[i];
142 if (dw.def_nr < vertex_groups_num && vertex_group_is_bone_deformed[dw.def_nr] &&
143 !vertex_group_is_locked(dw.def_nr))
144 {
145 dw.weight = 0.0f;
146 }
147 }
148
149 return (sum_weights_locked == 1.0f);
150 }
151
152 /* When the sum of the unlocked weights isn't zero, we can use a multiplier to normalize them
153 * to 1.0f. */
154 if (sum_weights_unlocked != 0.0f) {
155 const float normalize_factor = (1.0f - sum_weights_locked) / sum_weights_unlocked;
156
157 for (const int i : IndexRange(dvert.totweight)) {
158 MDeformWeight &dw = dvert.dw[i];
159 if (dw.def_nr < vertex_groups_num && vertex_group_is_bone_deformed[dw.def_nr] &&
160 dw.weight > FLT_EPSILON && !vertex_group_is_locked(dw.def_nr))
161 {
162 dw.weight = math::clamp(dw.weight * normalize_factor, 0.0f, 1.0f);
163 }
164 }
165
166 return true;
167 }
168
169 /* Spread out the remainder of the locked weights over the unlocked weights. */
170 const float weight_remainder = math::clamp(
171 (1.0f - sum_weights_locked) / unlocked_num, 0.0f, 1.0f);
172
173 for (const int i : IndexRange(dvert.totweight)) {
174 MDeformWeight &dw = dvert.dw[i];
175 if (dw.def_nr < vertex_groups_num && vertex_group_is_bone_deformed[dw.def_nr] &&
176 dw.weight > FLT_EPSILON && !vertex_group_is_locked(dw.def_nr))
177 {
178 dw.weight = weight_remainder;
179 }
180 }
181
182 return true;
183}
184
186 const int active_vertex_group,
187 const Span<bool> vertex_group_is_locked,
188 const Span<bool> vertex_group_is_bone_deformed)
189{
190 /* Try to normalize the weights with both active and explicitly locked vertex groups restricted
191 * from change. */
192 const auto active_vertex_group_is_locked = [&](const int vertex_group_index) {
193 return vertex_group_is_locked[vertex_group_index] || vertex_group_index == active_vertex_group;
194 };
195 const bool success = normalize_vertex_weights_try(dvert,
196 vertex_group_is_locked.size(),
197 vertex_group_is_bone_deformed,
198 active_vertex_group_is_locked);
199
200 if (success) {
201 return;
202 }
203
204 /* Do a second pass with the active vertex group unlocked. */
205 const auto active_vertex_group_is_unlocked = [&](const int vertex_group_index) {
206 return vertex_group_is_locked[vertex_group_index];
207 };
209 vertex_group_is_locked.size(),
210 vertex_group_is_bone_deformed,
211 active_vertex_group_is_unlocked);
212}
213
215 Object &ob, const Bone *bone, const FunctionRef<bool(Object &, const Bone *)> bone_callback)
216{
217 int count = 0;
218
219 if (bone != nullptr) {
220 /* Only call `bone_callback` if the bone is non null */
221 count += bone_callback(ob, bone) ? 1 : 0;
222 /* Try to execute `bone_callback` for the first child. */
223 count += foreach_bone_in_armature_ex(ob, bone->childbase.first(), bone_callback);
224 /* Try to execute `bone_callback` for the next bone at this depth of the recursion. */
225 count += foreach_bone_in_armature_ex(ob, bone->next, bone_callback);
226 }
227
228 return count;
229}
230
232 const bArmature &armature,
233 const FunctionRef<bool(Object &, const Bone *)> bone_callback)
234{
235 return foreach_bone_in_armature_ex(ob, armature.bonebase.first(), bone_callback);
236}
237
238bool add_armature_vertex_groups(Object &object, const Object &ob_armature)
239{
240 const bArmature &armature = *id_cast<const bArmature *>(ob_armature.data);
241
242 const int added_vertex_groups = foreach_bone_in_armature(
243 object, armature, [&](Object &object, const Bone *bone) {
244 if ((bone->flag & BONE_NO_DEFORM) == 0) {
245 /* Check if the name of the bone matches a vertex group name. */
246 if (!BKE_object_defgroup_find_name(&object, bone->name)) {
247 /* Add a new vertex group with the name of the bone. */
248 BKE_object_defgroup_add_name(&object, bone->name);
249 return true;
250 }
251 }
252 return false;
253 });
254
255 return added_vertex_groups > 0;
256}
257
259 Object &object,
260 Vector<const Bone *> &r_skinnable_bones,
261 Vector<std::string> &r_deform_group_names)
262{
263 const int added_vertex_groups = foreach_bone_in_armature(
264 object, armature, [&](Object &object, const Bone *bone) {
265 if ((bone->flag & BONE_NO_DEFORM) == 0) {
266 /* Check if the name of the bone matches a vertex group name. */
267 bDeformGroup *dg = BKE_object_defgroup_find_name(&object, bone->name);
268 if (dg == nullptr) {
269 /* Add a new vertex group with the name of the bone. */
270 dg = BKE_object_defgroup_add_name(&object, bone->name);
271 }
272 r_deform_group_names.append(dg->name);
273 r_skinnable_bones.append(bone);
274 return true;
275 }
276 return false;
277 });
278
279 if (added_vertex_groups <= 0) {
280 return false;
281 }
282 return true;
283}
284
286 const float4x4 &transform,
289{
290 threading::parallel_for(bones.index_range(), 4096, [&](const IndexRange range) {
291 for (const int i : range) {
292 const Bone *bone = bones[i];
293 roots[i] = math::transform_point(transform, float3(bone->arm_head));
294 tips[i] = math::transform_point(transform, float3(bone->arm_tail));
295 }
296 });
297}
298
300{
301 int def_nr = BKE_defgroup_name_index(&curves.vertex_group_names, name);
302
303 /* Lazily add the vertex group. */
304 if (def_nr == -1) {
305 bDeformGroup *defgroup = MEM_new<bDeformGroup>(__func__);
306 name.copy_utf8_truncated(defgroup->name);
307 BLI_addtail(&curves.vertex_group_names, defgroup);
308 def_nr = curves.vertex_group_names.count() - 1;
309 BLI_assert(def_nr >= 0);
310 }
311
312 return def_nr;
313}
314
315void add_armature_envelope_weights(Scene &scene, Object &object, const Object &ob_armature)
316{
317 using namespace bke;
318 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(object.data);
319 const bArmature &armature = *id_cast<const bArmature *>(ob_armature.data);
320 const float4x4 armature_to_world = ob_armature.object_to_world();
321 const float scale = mat4_to_scale(armature_to_world.ptr());
322
323 Vector<const Bone *> skinnable_bones;
324 Vector<std::string> deform_group_names;
326 armature, object, skinnable_bones, deform_group_names))
327 {
328 return;
329 }
330
331 /* Get the roots and tips of the bones in world space. */
332 Array<float3> roots(skinnable_bones.size());
333 Array<float3> tips(skinnable_bones.size());
335 skinnable_bones, armature_to_world, roots.as_mutable_span(), tips.as_mutable_span());
336
340 const bke::greasepencil::Layer &layer = *layers[info.layer_index];
341 const float4x4 layer_to_world = layer.to_world_space(object);
342
344
345 /* Get all the positions in world space. */
346 Array<float3> positions(curves.points_num());
347 math::transform_points(curves.positions(), layer_to_world, positions);
348
349 for (const int bone_i : skinnable_bones.index_range()) {
350 const Bone *bone = skinnable_bones[bone_i];
351 const char *deform_group_name = deform_group_names[bone_i].c_str();
352 const float3 bone_root = roots[bone_i];
353 const float3 bone_tip = tips[bone_i];
354
355 const int def_nr = lookup_or_add_deform_group_index(curves, deform_group_name);
356
357 MutableSpan<MDeformVert> dverts = curves.deform_verts_for_write();
359 for (const int point_i : curves.points_range()) {
360 const float weight = distfactor_to_bone(positions[point_i],
361 bone_root,
362 bone_tip,
363 bone->rad_head * scale,
364 bone->rad_tail * scale,
365 bone->dist * scale);
366 if (weight != 0.0f) {
367 weights.set(point_i, weight);
368 }
369 }
370 }
371 });
372}
373
374void add_armature_automatic_weights(Scene &scene, Object &object, const Object &ob_armature)
375{
376 using namespace bke;
377 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(object.data);
378 const bArmature &armature = *id_cast<const bArmature *>(ob_armature.data);
379 const float4x4 armature_to_world = ob_armature.object_to_world();
380 /* Note: These constant values are taken from the legacy grease pencil code. */
381 const float default_ratio = 0.1f;
382 const float default_decay = 0.8f;
383
384 Vector<const Bone *> skinnable_bones;
385 Vector<std::string> deform_group_names;
387 armature, object, skinnable_bones, deform_group_names))
388 {
389 return;
390 }
391
392 /* Get the roots and tips of the bones in world space. */
393 Array<float3> roots(skinnable_bones.size());
394 Array<float3> tips(skinnable_bones.size());
396 skinnable_bones, armature_to_world, roots.as_mutable_span(), tips.as_mutable_span());
397
398 /* Note: This is taken from the legacy grease pencil code. */
399 const auto get_weight = [](const float dist, const float decay_rad, const float diff_rad) {
400 return (dist < decay_rad) ? 1.0f :
401 math::interpolate(0.9f, 0.0f, (dist - decay_rad) / diff_rad);
402 };
403
407 const bke::greasepencil::Layer &layer = *layers[info.layer_index];
408 const float4x4 layer_to_world = layer.to_world_space(object);
409
411
412 /* Get all the positions in world space. */
413 Array<float3> positions(curves.points_num());
414 math::transform_points(curves.positions(), layer_to_world, positions);
415
416 for (const int bone_i : skinnable_bones.index_range()) {
417 const char *deform_group_name = deform_group_names[bone_i].c_str();
418 const float3 bone_root = roots[bone_i];
419 const float3 bone_tip = tips[bone_i];
420
421 const float radius_squared = math::distance_squared(bone_root, bone_tip) * default_ratio;
422 const float decay_rad = radius_squared - (radius_squared * default_decay);
423 const float diff_rad = radius_squared - decay_rad;
424
425 const int def_nr = lookup_or_add_deform_group_index(curves, deform_group_name);
426
427 MutableSpan<MDeformVert> dverts = curves.deform_verts_for_write();
429 for (const int point_i : curves.points_range()) {
430 const float3 position = positions[point_i];
431 const float dist_to_bone = dist_squared_to_line_segment_v3(position, bone_root, bone_tip);
432 const float weight = (dist_to_bone > radius_squared) ?
433 0.0f :
434 get_weight(dist_to_bone, decay_rad, diff_rad);
435 if (weight != 0.0f) {
436 weights.set(point_i, weight);
437 }
438 }
439 }
440 });
441}
442
448
450 wmOperator * /*op*/,
451 const wmEvent *event)
452{
453 Depsgraph *depsgraph = CTX_data_ensure_evaluated_depsgraph(C);
455
456 /* Get the active vertex group. */
457 const int object_defgroup_nr = BKE_object_defgroup_active_index_get(vc.obact) - 1;
458 if (object_defgroup_nr == -1) {
459 return OPERATOR_CANCELLED;
460 }
461 const bDeformGroup *object_defgroup = static_cast<const bDeformGroup *>(
462 BLI_findlink(BKE_object_defgroup_list(vc.obact), object_defgroup_nr));
463
464 /* Collect visible drawings. */
465 const Object *ob_eval = DEG_get_evaluated(vc.depsgraph, vc.obact);
466 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(vc.obact->data);
468
469 /* Find stroke points closest to mouse cursor position. */
471 drawings.index_range(),
472 1L,
474 [&](const IndexRange range, const ClosestGreasePencilDrawing &init) {
475 ClosestGreasePencilDrawing new_closest = init;
476 for (const int i : range) {
477 DrawingInfo info = drawings[i];
479
480 /* Skip drawing when it doesn't use the active vertex group. */
481 const int drawing_defgroup_nr = BKE_defgroup_name_index(
482 &info.drawing.strokes().vertex_group_names, object_defgroup->name);
483 if (drawing_defgroup_nr == -1) {
484 continue;
485 }
486
487 /* Get deformation by modifiers. */
490 ob_eval, *vc.obact, info.drawing);
491
492 IndexMaskMemory memory;
493 const IndexMask points = retrieve_visible_points(*vc.obact, info.drawing, memory);
494 if (points.is_empty()) {
495 continue;
496 }
497 const float4x4 layer_to_world = layer.to_world_space(*ob_eval);
499 layer_to_world);
501 std::optional<ed::curves::FindClosestData> new_closest_elem =
503 curves.points_by_curve(),
504 deformation.positions,
505 curves.cyclic(),
506 projection,
507 points,
509 event->mval,
510 new_closest.elem);
511 if (new_closest_elem) {
512 new_closest.elem = *new_closest_elem;
513 new_closest.drawing = &info.drawing;
514 new_closest.active_defgroup_index = drawing_defgroup_nr;
515 }
516 }
517 return new_closest;
518 },
520 return (a.elem.distance_sq < b.elem.distance_sq) ? a : b;
521 });
522
523 if (!closest.drawing) {
524 return OPERATOR_CANCELLED;
525 }
526
527 /* From the closest point found, get the vertex weight in the active vertex group. */
528 const VArray<float> point_weights = bke::varray_for_deform_verts(
529 closest.drawing->strokes().deform_verts(), closest.active_defgroup_index);
530 const float new_weight = math::clamp(point_weights[closest.elem.index], 0.0f, 1.0f);
531
532 /* Set the new brush weight. */
533 const ToolSettings *ts = vc.scene->toolsettings;
536
537 /* Update brush settings in UI. */
539
540 return OPERATOR_FINISHED;
541}
542
544{
545 /* Identifiers. */
546 ot->name = "Weight Paint Sample Weight";
547 ot->idname = "GREASE_PENCIL_OT_weight_sample";
548 ot->description =
549 "Set the weight of the Draw tool to the weight of the vertex under the mouse cursor";
550
551 /* Callbacks. */
554
555 /* Flags. */
557}
558
560{
563
564 /* Toggle direction flag. */
565 brush->flag ^= BRUSH_DIR_IN;
566
568 /* Update brush settings in UI. */
570
571 return OPERATOR_FINISHED;
572}
573
575{
577 return false;
578 }
579
581 if (paint == nullptr) {
582 return false;
583 }
585 if (brush == nullptr) {
586 return false;
587 }
588 return brush->gpencil_weight_brush_type == GPWEIGHT_BRUSH_TYPE_DRAW;
589}
590
592{
593 /* Identifiers. */
594 ot->name = "Weight Paint Toggle Direction";
595 ot->idname = "GREASE_PENCIL_OT_weight_toggle_direction";
596 ot->description = "Toggle Add/Subtract for the weight paint draw tool";
597
598 /* Callbacks. */
601
602 /* Flags. */
604}
605
607{
608 const Scene &scene = *CTX_data_scene(C);
610 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(object->data);
611
612 /* Object vgroup index. */
613 const int active_index = BKE_object_defgroup_active_index_get(object) - 1;
614 if (active_index == -1) {
615 return OPERATOR_CANCELLED;
616 }
617
618 const bDeformGroup *active_defgroup = static_cast<const bDeformGroup *>(
619 BLI_findlink(BKE_object_defgroup_list(object), active_index));
620
621 if (active_defgroup->flag & DG_LOCK_WEIGHT) {
622 BKE_report(op->reports, RPT_WARNING, "Active Vertex Group is locked");
623 return OPERATOR_CANCELLED;
624 }
625
627
630 /* Active vgroup index of drawing. */
631 const int drawing_vgroup_index = BKE_defgroup_name_index(&curves.vertex_group_names,
632 active_defgroup->name);
633 if (drawing_vgroup_index == -1) {
634 return;
635 }
636
638 curves.deform_verts_for_write(), drawing_vgroup_index);
639 if (weights.size() == 0) {
640 return;
641 }
642
643 for (const int i : weights.index_range()) {
644 const float invert_weight = 1.0f - weights[i];
645 weights.set(i, invert_weight);
646 }
647 });
648
651 return OPERATOR_FINISHED;
652}
653
655{
657 return false;
658 }
659
660 const Object *ob = CTX_data_active_object(C);
661 if (ob == nullptr || BLI_listbase_is_empty(BKE_object_defgroup_list(ob))) {
662 return false;
663 }
664
665 return true;
666}
667
669{
670 /* identifiers */
671 ot->name = "Invert Weight";
672 ot->idname = "GREASE_PENCIL_OT_weight_invert";
673 ot->description = "Invert the weight of active vertex group";
674
675 /* API callbacks. */
678
679 /* flags */
681}
682
684{
685 /* Get the active vertex group in the Grease Pencil object. */
687 const int object_defgroup_nr = BKE_object_defgroup_active_index_get(object) - 1;
688 if (object_defgroup_nr == -1) {
689 return OPERATOR_CANCELLED;
690 }
691 const bDeformGroup *object_defgroup = static_cast<const bDeformGroup *>(
692 BLI_findlink(BKE_object_defgroup_list(object), object_defgroup_nr));
693 if (object_defgroup->flag & DG_LOCK_WEIGHT) {
694 BKE_report(op->reports, RPT_WARNING, "Active vertex group is locked");
695 return OPERATOR_CANCELLED;
696 }
697
698 const float smooth_factor = RNA_float_get(op->ptr, "factor");
699 const int repeat = RNA_int_get(op->ptr, "repeat");
700
701 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(object->data);
702 const Scene &scene = *CTX_data_scene(C);
704
705 /* Smooth weights in all editable drawings. */
706 threading::parallel_for(drawings.index_range(), 1, [&](const IndexRange drawing_range) {
707 for (const int drawing : drawing_range) {
708 bke::CurvesGeometry &curves = drawings[drawing].drawing.strokes_for_write();
709 bke::MutableAttributeAccessor attributes = curves.attributes_for_write();
710
711 /* Skip the drawing when it doesn't use the active vertex group. */
712 if (!attributes.contains(object_defgroup->name)) {
713 continue;
714 }
715
716 bke::SpanAttributeWriter<float> weights = attributes.lookup_for_write_span<float>(
717 object_defgroup->name);
718 geometry::smooth_curve_attribute(curves.curves_range(),
719 curves.points_by_curve(),
720 VArray<bool>::from_single(true, curves.points_num()),
721 curves.cyclic(),
722 repeat,
723 smooth_factor,
724 true,
725 false,
726 weights.span);
727 weights.finish();
728 }
729 });
730
733
734 return OPERATOR_FINISHED;
735}
736
738{
739 /* Identifiers. */
740 ot->name = "Smooth Vertex Group";
741 ot->idname = "GREASE_PENCIL_OT_vertex_group_smooth";
742 ot->description = "Smooth the weights of the active vertex group";
743
744 /* Callbacks. */
747
748 /* Flags. */
750
751 /* Operator properties. */
752 RNA_def_float(ot->srna, "factor", 0.5f, 0.0f, 1.0, "Factor", "", 0.0f, 1.0f);
753 RNA_def_int(ot->srna, "repeat", 1, 1, 10000, "Iterations", "", 1, 200);
754}
755
757{
758 /* Get the active vertex group in the Grease Pencil object. */
760 const int object_defgroup_nr = BKE_object_defgroup_active_index_get(object) - 1;
761 if (object_defgroup_nr == -1) {
762 return OPERATOR_CANCELLED;
763 }
764 const bDeformGroup *object_defgroup = static_cast<const bDeformGroup *>(
765 BLI_findlink(BKE_object_defgroup_list(object), object_defgroup_nr));
766 if (object_defgroup->flag & DG_LOCK_WEIGHT) {
767 BKE_report(op->reports, RPT_WARNING, "Active vertex group is locked");
768 return OPERATOR_CANCELLED;
769 }
770
771 /* Get all editable drawings, grouped per frame. */
772 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(object->data);
773 const Scene &scene = *CTX_data_scene(C);
774 Array<Vector<MutableDrawingInfo>> drawings_per_frame =
776
777 /* Per frame, normalize the weights in the active vertex group. */
778 bool changed = false;
779 for (const int frame_i : drawings_per_frame.index_range()) {
780 /* Get the maximum weight in the active vertex group for this frame. */
781 const Vector<MutableDrawingInfo> drawings = drawings_per_frame[frame_i];
782 const float max_weight_in_frame = threading::parallel_reduce(
783 drawings.index_range(),
784 1,
785 0.0f,
786 [&](const IndexRange drawing_range, const float &drawing_weight_init) {
787 float max_weight_in_drawing = drawing_weight_init;
788 for (const int drawing_i : drawing_range) {
789 const bke::CurvesGeometry &curves = drawings[drawing_i].drawing.strokes();
790 const bke::AttributeAccessor attributes = curves.attributes();
791
792 /* Skip the drawing when it doesn't use the active vertex group. */
793 if (!attributes.contains(object_defgroup->name)) {
794 continue;
795 }
796
797 /* Get the maximum weight in this drawing. */
798 const VArray<float> weights = *curves.attributes().lookup_or_default<float>(
799 object_defgroup->name, bke::AttrDomain::Point, 0.0f);
800 const float max_weight_in_points = threading::parallel_reduce(
801 weights.index_range(),
802 1024,
803 max_weight_in_drawing,
804 [&](const IndexRange point_range, const float &init) {
805 float max_weight = init;
806 for (const int point_i : point_range) {
807 max_weight = math::max(max_weight, weights[point_i]);
808 }
809 return max_weight;
810 },
811 [](const float a, const float b) { return math::max(a, b); });
812 max_weight_in_drawing = math::max(max_weight_in_drawing, max_weight_in_points);
813 }
814 return max_weight_in_drawing;
815 },
816 [](const float a, const float b) { return math::max(a, b); });
817
818 if (ELEM(max_weight_in_frame, 0.0f, 1.0f)) {
819 continue;
820 }
821
822 /* Normalize weights from 0.0 to 1.0, by dividing the weights in the active vertex group by the
823 * maximum weight in the frame. */
824 changed = true;
825 threading::parallel_for(drawings.index_range(), 1, [&](const IndexRange drawing_range) {
826 for (const int drawing_i : drawing_range) {
827 bke::CurvesGeometry &curves = drawings[drawing_i].drawing.strokes_for_write();
828 bke::MutableAttributeAccessor attributes = curves.attributes_for_write();
829
830 /* Skip the drawing when it doesn't use the active vertex group. */
831 if (!attributes.contains(object_defgroup->name)) {
832 continue;
833 }
834
835 bke::SpanAttributeWriter<float> weights = attributes.lookup_for_write_span<float>(
836 object_defgroup->name);
837 threading::parallel_for(
838 weights.span.index_range(), 1024, [&](const IndexRange point_range) {
839 for (const int point_i : point_range) {
840 weights.span[point_i] /= max_weight_in_frame;
841 }
842 });
843 weights.finish();
844 }
845 });
846 }
847
848 if (changed) {
851 }
852
853 return OPERATOR_FINISHED;
854}
855
857{
858 /* Identifiers. */
859 ot->name = "Normalize Vertex Group";
860 ot->idname = "GREASE_PENCIL_OT_vertex_group_normalize";
861 ot->description = "Normalize weights of the active vertex group";
862
863 /* Callbacks. */
866
867 /* Flags. */
869}
870
872{
873 /* Get the active vertex group in the Grease Pencil object. */
875 const int object_defgroup_nr = BKE_object_defgroup_active_index_get(object) - 1;
876 const bDeformGroup *object_defgroup = static_cast<const bDeformGroup *>(
877 BLI_findlink(BKE_object_defgroup_list(object), object_defgroup_nr));
878
879 /* Get the locked vertex groups in the object. */
880 Set<std::string> object_locked_defgroups;
881 const ListBaseT<bDeformGroup> *defgroups = BKE_object_defgroup_list(object);
882 for (bDeformGroup &dg : *defgroups) {
883 if ((dg.flag & DG_LOCK_WEIGHT) != 0) {
884 object_locked_defgroups.add(dg.name);
885 }
886 }
887 const bool lock_active_group = RNA_boolean_get(op->ptr, "lock_active");
888
889 /* Get all editable drawings. */
890 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(object->data);
891 const Scene &scene = *CTX_data_scene(C);
893
894 /* Normalize weights in all drawings. */
895 threading::parallel_for(drawings.index_range(), 1, [&](const IndexRange drawing_range) {
896 for (const int drawing_i : drawing_range) {
897 bke::CurvesGeometry &curves = drawings[drawing_i].drawing.strokes_for_write();
898
899 /* Get the active vertex group in the drawing when it needs to be locked. */
900 int active_vertex_group = -1;
901 if (object_defgroup && lock_active_group) {
902 active_vertex_group = BKE_defgroup_name_index(&curves.vertex_group_names,
903 object_defgroup->name);
904 }
905
906 /* Put the lock state of every vertex group in a boolean array. */
907 Vector<bool> vertex_group_is_locked;
908 Vector<bool> vertex_group_is_included;
909 for (bDeformGroup &dg : curves.vertex_group_names) {
910 vertex_group_is_locked.append(object_locked_defgroups.contains(dg.name));
911 /* Dummy, needed for the #normalize_vertex_weights() call. */
912 vertex_group_is_included.append(true);
913 }
914
915 /* For all points in the drawing, normalize the weights of all vertex groups to the sum
916 * of 1.0. */
917 MutableSpan<MDeformVert> deform_verts = curves.deform_verts_for_write();
918 threading::parallel_for(curves.points_range(), 1024, [&](const IndexRange point_range) {
919 for (const int point_i : point_range) {
920 normalize_vertex_weights(deform_verts[point_i],
921 active_vertex_group,
922 vertex_group_is_locked,
923 vertex_group_is_included);
924 }
925 });
926 }
927 });
928
931
932 return OPERATOR_FINISHED;
933}
934
936{
937 /* Identifiers. */
938 ot->name = "Normalize All Vertex Groups";
939 ot->idname = "GREASE_PENCIL_OT_vertex_group_normalize_all";
940 ot->description =
941 "Normalize the weights of all vertex groups, so that for each vertex, the sum of all "
942 "weights is 1.0";
943
944 /* Callbacks. */
947
948 /* Flags. */
950
951 /* Operator properties. */
953 "lock_active",
954 true,
955 "Lock Active",
956 "Keep the values of the active group while normalizing others");
957}
958
959} // namespace ed::greasepencil
960
971
972} // namespace blender
support for deformation groups and hooks.
#define VERTEX_WEIGHT_LOCK_EPSILON
Low-level operations for grease pencil.
Functions for dealing with objects and deform verts, used by painting and tools.
Object is a sort of wrapper for general info.
#define C
Definition RandGen.cpp:29
#define NC_GEOM
Definition WM_types.hh:406
#define NC_BRUSH
Definition WM_types.hh:398
#define ND_DATA
Definition WM_types.hh:552
#define NA_EDITED
Definition WM_types.hh:634
#define ELEM(...)
bool closest(btVector3 &v)
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:259
IndexRange index_range() const
Definition BLI_array.hh:371
constexpr IndexRange()=default
bool contains(const Key &key) const
Definition BLI_set.hh:310
bool add(const Key &key)
Definition BLI_set.hh:248
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
IndexRange index_range() const
void set(const int64_t index, T value)
int64_t size() const
void append(const T &value)
IndexRange index_range() const
bke::CurvesGeometry & strokes_for_write()
const bke::CurvesGeometry & strokes() const
void copy_utf8_truncated(char *dst, int64_t dst_size) const
Definition string_ref.cc:28
#define FLT_EPSILON
#define position
#define layer
float3x3 scale(float3x3 mat, float2 scale)
GeometryDeformation get_evaluated_grease_pencil_drawing_deformation(const Object *ob_eval, const Object &ob_orig, const bke::greasepencil::Drawing &drawing_orig)
VMutableArray< float > varray_for_mutable_deform_verts(MutableSpan< MDeformVert > dverts, int defgroup_index)
Definition deform.cc:1752
VArray< float > varray_for_deform_verts(Span< MDeformVert > dverts, int defgroup_index)
Definition deform.cc:1748
std::optional< FindClosestData > closest_elem_find_screen_space(const ViewContext &vc, const OffsetIndices< int > points_by_curve, const Span< float3 > positions, const VArray< bool > &cyclic, const float4x4 &projection, const IndexMask &mask, const bke::AttrDomain domain, const int2 coord, const FindClosestData &initial_closest)
static bool normalize_vertex_weights_try(MDeformVert &dvert, const int vertex_groups_num, const Span< bool > vertex_group_is_bone_deformed, const FunctionRef< bool(int)> vertex_group_is_locked)
static wmOperatorStatus grease_pencil_weight_invert_exec(bContext *C, wmOperator *op)
Set< std::string > get_bone_deformed_vertex_group_names(const Object &object)
static wmOperatorStatus vertex_group_smooth_exec(bContext *C, wmOperator *op)
static void GREASE_PENCIL_OT_vertex_group_smooth(wmOperatorType *ot)
static int foreach_bone_in_armature(Object &ob, const bArmature &armature, const FunctionRef< bool(Object &, const Bone *)> bone_callback)
static void GREASE_PENCIL_OT_vertex_group_normalize(wmOperatorType *ot)
void add_armature_automatic_weights(Scene &scene, Object &object, const Object &ob_armature)
IndexMask retrieve_visible_points(Object &object, const bke::greasepencil::Drawing &drawing, IndexMaskMemory &memory)
Vector< DrawingInfo > retrieve_visible_drawings(const Scene &scene, const GreasePencil &grease_pencil, const bool do_onion_skinning)
static wmOperatorStatus vertex_group_normalize_all_exec(bContext *C, wmOperator *op)
static bool toggle_weight_tool_direction_poll(bContext *C)
static wmOperatorStatus vertex_group_normalize_exec(bContext *C, wmOperator *op)
static void GREASE_PENCIL_OT_weight_sample(wmOperatorType *ot)
void normalize_vertex_weights(MDeformVert &dvert, const int active_vertex_group, const Span< bool > vertex_group_is_locked, const Span< bool > vertex_group_is_bone_deformed)
static void GREASE_PENCIL_OT_vertex_group_normalize_all(wmOperatorType *ot)
static void GREASE_PENCIL_OT_weight_invert(wmOperatorType *ot)
static wmOperatorStatus toggle_weight_tool_direction_exec(bContext *C, wmOperator *)
static void GREASE_PENCIL_OT_weight_toggle_direction(wmOperatorType *ot)
static wmOperatorStatus weight_sample_invoke(bContext *C, wmOperator *, const wmEvent *event)
void add_armature_envelope_weights(Scene &scene, Object &object, const Object &ob_armature)
bool grease_pencil_weight_painting_poll(bContext *C)
bool add_armature_vertex_groups(Object &object, const Object &ob_armature)
Vector< MutableDrawingInfo > retrieve_editable_drawings(const Scene &scene, GreasePencil &grease_pencil)
static int foreach_bone_in_armature_ex(Object &ob, const Bone *bone, const FunctionRef< bool(Object &, const Bone *)> bone_callback)
static bool get_skinnable_bones_and_deform_group_names(const bArmature &armature, Object &object, Vector< const Bone * > &r_skinnable_bones, Vector< std::string > &r_deform_group_names)
Array< Vector< MutableDrawingInfo > > retrieve_editable_drawings_grouped_per_frame(const Scene &scene, GreasePencil &grease_pencil)
static void get_root_and_tips_of_bones(Span< const Bone * > bones, const float4x4 &transform, MutableSpan< float3 > roots, MutableSpan< float3 > tips)
static bool grease_pencil_vertex_group_weight_poll(bContext *C)
static int lookup_or_add_deform_group_index(CurvesGeometry &curves, const StringRef name)
T clamp(const T &a, const T &min, const T &max)
T interpolate(const T &a, const T &b, const FactorT &t)
T distance_squared(const VecBase< T, Size > &a, const VecBase< T, Size > &b)
T max(const T &a, const T &b)
void transform_points(const float4x4 &transform, MutableSpan< float3 > points, bool use_threading=true)
void parallel_for_each(Range &&range, const Function &function)
Definition BLI_task.hh:31
void parallel_for(const IndexRange range, const int64_t grain_size, const Function &function, const TaskSizeHints &size_hints=detail::TaskSizeHints_Static(1))
Definition BLI_task.hh:69
Value parallel_reduce(IndexRange range, int64_t grain_size, const Value &identity, const Function &function, const Reduction &reduction)
Definition BLI_task.hh:127
BMesh Iterators.
void WM_main_add_notifier(uint type, void *reference)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void WM_operatortype_append(void(*opfunc)(wmOperatorType *))
@ RPT_WARNING
Definition BKE_report.hh:40
const ListBaseT< bDeformGroup > * BKE_object_defgroup_list(const Object *ob)
Definition deform.cc:591
@ GPWEIGHT_BRUSH_TYPE_DRAW
ViewContext ED_view3d_viewcontext_init(bContext *C, Depsgraph *depsgraph)
bDeformGroup * BKE_object_defgroup_find_name(const Object *ob, StringRef name)
Definition deform.cc:530
float mat4_to_scale(const float mat[4][4])
@ eModifierType_GreasePencilArmature
int RNA_int_get(PointerRNA *ptr, const char *name)
BLI_INLINE bool BLI_listbase_is_empty(const ListBase *lb)
MatBase< float, 4, 4 > float4x4
int BKE_defgroup_name_index(const ListBaseT< bDeformGroup > *defbase, StringRef name)
Definition deform.cc:544
float distfactor_to_bone(const float3 &position, const float3 &head, const float3 &tail, float radius_head, float radius_tail, float falloff_distance)
void BKE_brush_tag_unsaved_changes(Brush *brush)
Definition brush.cc:843
void * BLI_findlink(const ListBase *listbase, int number) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:541
void DEG_id_tag_update(ID *id, unsigned int flags)
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
BMesh const char void * data
T * DEG_get_evaluated(const Depsgraph *depsgraph, T *id)
Depsgraph * CTX_data_ensure_evaluated_depsgraph(const bContext *C, bool rna_write_check=false)
ModifierData * BKE_modifiers_get_virtual_modifierlist(const Object *ob, VirtualModifierData *data)
void ED_operatortypes_grease_pencil_weight_paint()
struct bDeformGroup * BKE_object_defgroup_add_name(struct Object *ob, const char *name)
float dist_squared_to_line_segment_v3(const float p[3], const float l1[3], const float l2[3])
Definition math_geom.cc:535
bool RNA_boolean_get(PointerRNA *ptr, const char *name)
void WM_event_add_notifier(const bContext *C, uint type, void *reference)
PropertyRNA * RNA_def_int(StructOrFunctionRNA *cont_, const char *identifier, const int default_value, const int hardmin, const int hardmax, const char *ui_name, const char *ui_description, const int softmin, const int softmax)
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:118
Paint * BKE_paint_get_active_from_context(const bContext *C)
void BKE_brush_weight_set(Paint *paint, Brush *brush, float value)
Definition brush.cc:1472
@ ID_RECALC_GEOMETRY
Definition DNA_ID.h:1074
float4x4 ED_view3d_ob_project_mat_get_from_obmat(const RegionView3D *rv3d, const float4x4 &obmat)
Brush * BKE_paint_brush(Paint *paint)
Scene * CTX_data_scene(const bContext *C)
@ OPTYPE_REGISTER
Definition WM_types.hh:188
@ OPTYPE_UNDO
Definition WM_types.hh:190
@ OPTYPE_DEPENDS_ON_CURSOR
Definition WM_types.hh:228
VecBase< float, 3 > float3
PropertyRNA * RNA_def_boolean(StructOrFunctionRNA *cont_, const char *identifier, const bool default_value, const char *ui_name, const char *ui_description)
PropertyRNA * RNA_def_float(StructOrFunctionRNA *cont_, const char *identifier, const float default_value, const float hardmin, const float hardmax, const char *ui_name, const char *ui_description, const float softmin, const float softmax)
Object * CTX_data_active_object(const bContext *C)
float RNA_float_get(PointerRNA *ptr, const char *name)
int BKE_object_defgroup_active_index_get(const Object *ob)
Definition deform.cc:613
struct Bone * next
ListBaseT< Bone > childbase
ListBaseT< struct bDeformGroup > vertex_group_names
struct MDeformWeight * dw
const c_style_mat & ptr() const
struct ModifierData * next
struct bPose * pose
struct ToolSettings * toolsettings
GpWeightPaint * gp_weightpaint
RegionView3D * rv3d
Definition ED_view3d.hh:86
Depsgraph * depsgraph
Definition ED_view3d.hh:78
ListBaseT< Bone > bonebase
ebDeformGroup_Flag flag
const bke::greasepencil::Drawing & drawing
wmOperatorStatus(*) exec(bContext *C, wmOperator *op) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1125
const char * description
Definition WM_types.hh:1115
bool(*) poll(bContext *C) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1165
wmOperatorStatus(*) invoke(bContext *C, wmOperator *op, const wmEvent *event) ATTR_WARN_UNUSED_RESULT
Definition WM_types.hh:1141
struct ReportList * reports