Blender V5.3
grease_pencil.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#include <iostream>
10#include <optional>
11
12#include "BKE_action.hh"
13#include "BKE_anim_data.hh"
14#include "BKE_animsys.hh"
15#include "BKE_asset_edit.hh"
20#include "BKE_brush.hh"
21#include "BKE_curves.hh"
22#include "BKE_customdata.hh"
23#include "BKE_deform.hh"
24#include "BKE_fcurve.hh"
25#include "BKE_geometry_set.hh"
26#include "BKE_grease_pencil.h"
27#include "BKE_grease_pencil.hh"
29#include "BKE_idtype.hh"
30#include "BKE_lib_id.hh"
31#include "BKE_lib_query.hh"
32#include "BKE_main.hh"
33#include "BKE_material.hh"
34#include "BKE_modifier.hh"
35#include "BKE_object.hh"
36#include "BKE_object_types.hh"
37#include "BKE_paint.hh"
38
39#include "BLI_array_utils.hh"
40#include "BLI_bounds.hh"
41#include "BLI_color_types.hh"
42#include "BLI_delaunay_2d.hh"
44#include "BLI_listbase.hh"
45#include "BLI_map.hh"
46#include "BLI_math_color_c.hh"
48#include "BLI_math_geom_c.hh"
49#include "BLI_math_matrix.hh"
50#include "BLI_math_matrix_c.hh"
53#include "BLI_memarena.hh"
54#include "BLI_memory_utils.hh"
55#include "BLI_polyfill_2d.hh"
56#include "BLI_resource_scope.hh"
57#include "BLI_span.hh"
58#include "BLI_stack.hh"
59#include "BLI_string.hh"
60#include "BLI_string_ref.hh"
61#include "BLI_string_utf8.hh"
62#include "BLI_string_utils.hh"
63#include "BLI_task.hh"
64#include "BLI_utildefines.hh"
65#include "BLI_vector_set.hh"
66#include "BLI_virtual_array.hh"
67
68#include "BLO_read_write.hh"
69
70#include "BLT_translation.hh"
71
72#include "DNA_ID.h"
73#include "DNA_ID_enums.h"
74#include "DNA_brush_types.h"
76#include "DNA_material_types.h"
77#include "DNA_modifier_types.h"
78
79#include "DEG_depsgraph.hh"
81
83
84#include "RNA_access.hh"
85#include "RNA_path.hh"
86#include "RNA_prototypes.hh"
87
88#include "MEM_guardedalloc.h"
89
90#include "CLG_log.h"
91
93
94namespace blender {
95
96static CLG_LogRef LOG = {"geom.grease_pencil"};
97
98static const char *ATTR_POSITION = "position";
99
100/* Forward declarations. */
103 ResourceScope &scope,
104 BlendWriter *writer);
106
109
111{
112 using namespace blender::bke;
113
114 GreasePencil *grease_pencil = reinterpret_cast<GreasePencil *>(id);
116
117 grease_pencil->root_group_ptr = MEM_new<greasepencil::LayerGroup>(__func__);
118 grease_pencil->set_active_node(nullptr);
119
120 CustomData_reset(&grease_pencil->layers_data_legacy);
121 new (&grease_pencil->attribute_storage.wrap()) bke::AttributeStorage();
122
123 grease_pencil->runtime = MEM_new<GreasePencilRuntime>(__func__);
124}
125
126/* See if the layer visibility is animated. This is determined whenever a copy is made, so that
127 * this happens in the "create evaluation copy" node of the depsgraph. */
129{
130 using namespace blender::bke;
131
132 if (!DEG_is_evaluated(&id_dst) || !grease_pencil.adt) {
133 return;
134 }
135
136 PropertyRNA *layer_hide_prop = RNA_struct_type_find_property(RNA_GreasePencilLayer, "hide");
137 BLI_assert_msg(layer_hide_prop,
138 "RNA struct GreasePencilLayer is expected to have a 'hide' property.");
139 PropertyRNA *group_hide_prop = RNA_struct_type_find_property(RNA_GreasePencilLayerGroup, "hide");
140 BLI_assert_msg(group_hide_prop,
141 "RNA struct GreasePencilLayerGroup is expected to have a 'hide' property.");
142
143 for (greasepencil::LayerGroup *layer_group : grease_pencil.layer_groups_for_write()) {
145 &id_dst, RNA_GreasePencilLayerGroup, layer_group);
146 std::optional<std::string> rna_path = RNA_path_from_ID_to_property(&layer_ptr,
147 group_hide_prop);
149 rna_path,
150 "It should be possible to construct the RNA path of a grease pencil layer group.");
151
152 layer_group->runtime->is_visibility_animated_ = animdata::prop_is_animated(
153 grease_pencil.adt, rna_path->c_str(), 0);
154 }
155
156 std::function<bool(greasepencil::LayerGroup &)> parent_group_visibility_animated =
157 [&](greasepencil::LayerGroup &parent) {
158 if (parent.runtime->is_visibility_animated_) {
159 return true;
160 }
161 greasepencil::LayerGroup *parent_group = parent.as_node().parent_group();
162 if (parent_group) {
163 return parent_group_visibility_animated(*parent_group);
164 }
165 return false;
166 };
167
168 for (greasepencil::Layer *layer : grease_pencil.layers_for_write()) {
169 if (parent_group_visibility_animated(layer->parent_group())) {
170 layer->runtime->is_visibility_animated_ = true;
171 continue;
172 }
173 PointerRNA layer_ptr = RNA_pointer_create_discrete(&id_dst, RNA_GreasePencilLayer, layer);
174 std::optional<std::string> rna_path = RNA_path_from_ID_to_property(&layer_ptr,
175 layer_hide_prop);
177 "It should be possible to construct the RNA path of a grease pencil layer.");
178 layer->runtime->is_visibility_animated_ = animdata::prop_is_animated(
179 grease_pencil.adt, rna_path.value(), 0);
180 }
181}
182
191{
192 using namespace blender::bke::greasepencil;
193 int empty_drawing_users = 0;
194 const int empty_drawing_index = grease_pencil.drawings().size();
195 for (Layer *layer : grease_pencil.layers_for_write()) {
196 for (GreasePencilFrame &frame : layer->frames_for_write().values()) {
197 if (frame.is_end()) {
198 empty_drawing_users++;
199 frame.drawing_index = empty_drawing_index;
200 frame.flag |= GP_FRAME_IMPLICIT_HOLD;
201 layer->tag_frames_map_keys_changed();
202 }
203 }
204 }
205 if (empty_drawing_users > 0) {
206 grease_pencil.add_empty_drawings(1);
207 BLI_assert(grease_pencil.drawings().index_range().contains(empty_drawing_index));
208
209 CLOG_WARN(&LOG,
210 "Converted %d end frames to regular frames using an empty drawing in \"%s\"",
211 empty_drawing_users,
213 }
214}
215
217{
218 using namespace blender::bke::greasepencil;
219 /* Unknown types have no runtime data, and only the base struct was read. */
220 for (const GreasePencilDrawingBase *drawing_base : grease_pencil.drawings()) {
221 if (!ELEM(drawing_base->type, GP_DRAWING, GP_DRAWING_REFERENCE)) {
222 return false;
223 }
224 }
225 for (const Layer *layer : grease_pencil.layers()) {
226 for (const GreasePencilFrame &value : layer->frames().values()) {
227 if (!grease_pencil.drawings().index_range().contains(value.drawing_index)) {
228 return false;
229 }
230 }
231 }
232 const Array<int> user_counts = grease_pencil.count_frame_users_for_drawings();
233 BLI_assert(user_counts.size() == grease_pencil.drawings().size());
234 for (const int drawing_i : grease_pencil.drawings().index_range()) {
235 GreasePencilDrawingBase *drawing_base = grease_pencil.drawing(drawing_i);
236 if (drawing_base->type != GP_DRAWING_REFERENCE) {
237 Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base)->wrap();
238 drawing.runtime->user_count.store(user_counts[drawing_i]);
239 }
240 }
241 return true;
242}
243
244static void grease_pencil_copy_data(Main * /*bmain*/,
245 std::optional<Library *> /*owner_library*/,
246 ID *id_dst,
247 const ID *id_src,
248 const int /*flag*/)
249{
250 GreasePencil *grease_pencil_dst = reinterpret_cast<GreasePencil *>(id_dst);
251 const GreasePencil *grease_pencil_src = reinterpret_cast<const GreasePencil *>(id_src);
252
253 /* Duplicate material array. */
254 grease_pencil_dst->material_array = static_cast<Material **>(
255 MEM_dupalloc(grease_pencil_src->material_array));
256
257 BKE_grease_pencil_duplicate_drawing_array(grease_pencil_src, grease_pencil_dst);
258
259 /* Duplicate layer tree. */
260 grease_pencil_dst->root_group_ptr = MEM_new<bke::greasepencil::LayerGroup>(
261 __func__, grease_pencil_src->root_group());
262
263 /* Set active node. */
264 if (grease_pencil_src->get_active_node()) {
265 bke::greasepencil::TreeNode *active_node = grease_pencil_dst->find_node_by_name(
266 grease_pencil_src->get_active_node()->name());
267 BLI_assert(active_node);
268 grease_pencil_dst->set_active_node(active_node);
269 }
270
271 new (&grease_pencil_dst->attribute_storage.wrap())
272 bke::AttributeStorage(grease_pencil_src->attribute_storage.wrap());
273
274 BKE_defgroup_copy_list(&grease_pencil_dst->vertex_group_names,
275 &grease_pencil_src->vertex_group_names);
276
277 /* Make sure the runtime pointer exists. */
278 grease_pencil_dst->runtime = MEM_new<bke::GreasePencilRuntime>(__func__);
279
280 if (grease_pencil_src->runtime->bake_materials) {
281 grease_pencil_dst->runtime->bake_materials = std::make_unique<bke::bake::BakeMaterialsList>(
282 *grease_pencil_src->runtime->bake_materials);
283 }
284
285 grease_pencil_set_runtime_visibilities(*id_dst, *grease_pencil_dst);
286
287 /* Duplicating drawings does not copy over their user count. */
289}
290
292{
293 GreasePencil *grease_pencil = reinterpret_cast<GreasePencil *>(id);
294 BKE_animdata_free(&grease_pencil->id, false);
295
296 MEM_SAFE_DELETE(grease_pencil->material_array);
297
298 grease_pencil->attribute_storage.wrap().~AttributeStorage();
299
301 MEM_delete(&grease_pencil->root_group());
302
303 grease_pencil->vertex_group_names.free_no_destruct();
304
306
307 MEM_delete(grease_pencil->runtime);
308 grease_pencil->runtime = nullptr;
309}
310
312{
313 GreasePencil *grease_pencil = reinterpret_cast<GreasePencil *>(id);
314 for (int i = 0; i < grease_pencil->material_array_num; i++) {
316 }
317 for (GreasePencilDrawingBase *drawing_base : grease_pencil->drawings()) {
318 if (drawing_base->type == GP_DRAWING_REFERENCE) {
319 GreasePencilDrawingReference *drawing_reference =
320 reinterpret_cast<GreasePencilDrawingReference *>(drawing_base);
322 }
323 }
324 for (const bke::greasepencil::Layer *layer : grease_pencil->layers()) {
325 if (layer->parent) {
327 }
328 }
329}
330
333{
334 GreasePencil *grease_pencil = reinterpret_cast<GreasePencil *>(id);
335
336 fn.single(grease_pencil->onion_skinning_settings.color_after);
337 fn.single(grease_pencil->onion_skinning_settings.color_before);
338
339 for (bke::greasepencil::TreeNode *node : grease_pencil->nodes_for_write()) {
340 fn.single(node->color);
341 }
342
343 grease_pencil->attribute_storage.wrap().foreach_working_space_color(fn);
344}
345
346static void grease_pencil_blend_write(BlendWriter *writer, ID *id, const void *id_address)
347{
348 using namespace blender::bke;
349 GreasePencil *grease_pencil = reinterpret_cast<GreasePencil *>(id);
350
351 ResourceScope scope;
352
353 Vector<CustomDataLayer, 16> layers_data_layers;
354 bke::AttributeStorage::BlendWriteData attribute_data{writer, scope};
356 grease_pencil->attribute_storage.wrap(),
357 !writer->is_undo(),
358 [&](const AttrDomain /*domain*/) { return grease_pencil->layers().size(); },
359 attribute_data);
360 grease_pencil->attribute_storage.dna_attributes = attribute_data.attributes.data();
361 grease_pencil->attribute_storage.dna_attributes_num = attribute_data.attributes.size();
362 writer->generated_pointer_tag(grease_pencil->attribute_storage.dna_attributes);
363
364 CustomData_reset(&grease_pencil->layers_data_legacy);
365
366 /* Write LibData */
367 writer->write_id_struct(
368 id_address, grease_pencil, [](BlendStructWriter<GreasePencil> &struct_writer) {
369 struct_writer.generated_ptr(offsetof(GreasePencil, attribute_storage.dna_attributes));
370 });
371 BKE_id_blend_write(writer, &grease_pencil->id);
372
373 grease_pencil->attribute_storage.wrap().blend_write(*writer, attribute_data);
374
375 /* Write drawings. */
376 write_drawing_array(*grease_pencil, scope, writer);
377 /* Write layer tree. */
379
380 /* Write materials. */
381 writer->write_pointer_array(grease_pencil->material_array_num, grease_pencil->material_array);
382 /* Write vertex group names. */
383 BKE_defbase_blend_write(writer, &grease_pencil->vertex_group_names);
384}
385
387{
388 using namespace blender::bke::greasepencil;
389 GreasePencil *grease_pencil = reinterpret_cast<GreasePencil *>(id);
390
391 /* Read drawings. */
393 /* Read layer tree. */
395
397 reader, &grease_pencil->layers_data_legacy, grease_pencil->layers().size());
398 grease_pencil->attribute_storage.wrap().blend_read(*reader);
399
400 /* Read materials. */
402 reader, &grease_pencil->material_array, &grease_pencil->material_array_num);
403 /* Read vertex group names. */
404 BLO_read_struct_list(reader, bDeformGroup, &grease_pencil->vertex_group_names);
405
406 grease_pencil->runtime = MEM_new<bke::GreasePencilRuntime>(__func__);
407
408 /* End-frames used to be 'encoded' using an invalid drawing index (`-1`), until Blender 5.3. But
409 * most of GP code does not handle them correctly.
410 *
411 * As backward-compatible solution, they are converted into regular frames pointing at an empty
412 * drawing. This will give the same visual result (for rendering e.g.), until proper
413 * implementation of endframes is reworked for Blender 5.4. */
415
416 /* Initialize drawing user counts. Failure means the file is badly corrupted. Done last, because
417 * the ID gets freed after an invalidated read, which requires all of it to be initialized. */
419 BLO_read_data_invalidate(reader, "Invalid Grease Pencil data");
420 }
421}
422
424 .id_code = GreasePencil::id_type,
425 .id_filter = FILTER_ID_GP,
426 .dependencies_id_types = FILTER_ID_GP | FILTER_ID_MA | FILTER_ID_OB,
427 .main_listbase_index = INDEX_ID_GP,
428 .struct_size = sizeof(GreasePencil),
429 .name = "GreasePencil",
430 .name_plural = N_("grease_pencils"),
431 .translation_context = BLT_I18NCONTEXT_ID_GPENCIL,
433 .asset_type_info = nullptr,
434
435 .init_data = grease_pencil_init_data,
436 .copy_data = grease_pencil_copy_data,
437 .free_data = grease_pencil_free_data,
438 .make_local = nullptr,
439 .foreach_id = grease_pencil_foreach_id,
440 .foreach_cache = nullptr,
441 .foreach_path = nullptr,
442 .foreach_working_space_color = grease_pencil_foreach_working_space_color,
443 .foreach_asset_weak_reference = nullptr,
444 .owner_pointer_get = nullptr,
445
446 .blend_write = grease_pencil_blend_write,
447 .blend_read_data = grease_pencil_blend_read_data,
448 .blend_read_after_liblink = nullptr,
449
450 .blend_read_undo_preserve = nullptr,
451
452 .lib_override_apply_post = nullptr,
453};
454
455namespace bke::greasepencil {
456constexpr StringRef ATTR_RADIUS = "radius";
457constexpr StringRef ATTR_OPACITY = "opacity";
458constexpr StringRef ATTR_VERTEX_COLOR = "vertex_color";
459constexpr StringRef ATTR_FILL_COLOR = "fill_color";
460
462{
463 this->base.type = GP_DRAWING;
465
466 new (&this->geometry) bke::CurvesGeometry();
467 /* Initialize runtime data. */
468 this->runtime = MEM_new<bke::greasepencil::DrawingRuntime>(__func__);
469}
470
472{
473 this->base.type = GP_DRAWING;
474 this->base.flag = other.base.flag;
475
476 new (&this->geometry) bke::CurvesGeometry(other.strokes());
477 /* Initialize runtime data. */
478 this->runtime = MEM_new<bke::greasepencil::DrawingRuntime>(__func__);
479
481 this->runtime->fill_cache = other.runtime->fill_cache;
484}
485
487{
488 this->base.type = GP_DRAWING;
489 other.base.type = GP_DRAWING;
490 this->base.flag = other.base.flag;
491 other.base.flag = GreasePencilDrawingBaseFlag{};
492
493 new (&this->geometry) bke::CurvesGeometry(std::move(other.geometry.wrap()));
494
495 this->runtime = other.runtime;
496 other.runtime = nullptr;
497}
498
500{
501 if (this == &other) {
502 return *this;
503 }
504 std::destroy_at(this);
505 new (this) Drawing(other);
506 return *this;
507}
508
510{
511 if (this == &other) {
512 return *this;
513 }
514 std::destroy_at(this);
515 new (this) Drawing(std::move(other));
516 return *this;
517}
518
520{
521 this->strokes().~CurvesGeometry();
522 MEM_delete(this->runtime);
523 this->runtime = nullptr;
524}
525
526static void ensure_fill_cache(const Drawing &drawing)
527{
528 drawing.runtime->fill_cache.ensure([&](std::optional<FillCache> &r_fill_cache) {
529 const CurvesGeometry &curves = drawing.strokes();
530 const bke::AttributeAccessor attributes = curves.attributes();
531
532 const VArray<int> fill_ids = *attributes.lookup<int>("fill_id", bke::AttrDomain::Curve);
533 r_fill_cache = fill_cache_from_fill_ids(fill_ids);
534 });
535}
536
537std::optional<GroupedSpan<int>> Drawing::fills() const
538{
539 ensure_fill_cache(*this);
540 if (this->runtime->fill_cache.data().has_value()) {
541 const FillCache &fill_cache = *this->runtime->fill_cache.data();
542 return GroupedSpan<int>(fill_cache.fill_offsets.as_span(), fill_cache.fill_map.as_span());
543 }
544 return std::nullopt;
545}
546
548 const Span<float3> normals,
549 const OffsetIndices<int> points_by_curve,
550 const IndexMask &fill_mask,
551 const GroupedSpan<int> fills,
552 Vector<int3> &r_triangles,
553 MutableSpan<int> r_triangle_offsets,
554 Vector<float3> &r_intersection_points,
555 MutableSpan<int> r_intersection_point_offsets)
556{
557 struct LocalMemArena {
558 MemArena *pf_arena = nullptr;
559 LocalMemArena() : pf_arena(BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "Drawing::triangles")) {}
560
561 ~LocalMemArena()
562 {
563 if (pf_arena != nullptr) {
564 BLI_memarena_free(pf_arena);
565 }
566 }
567 };
568
569 Array<Vector<int3>> triangle_results(fill_mask.size());
570 Array<Vector<float3>> intersection_point_results(fill_mask.size());
571
573 fill_mask.foreach_segment(
574 [&](const IndexMaskSegment mask_segment, const int segment_pos) {
576 MemArena *pf_arena = all_local_mem_arenas.local().pf_arena;
577 for (const int index : mask_segment.index_range()) {
578 const int fill_index = mask_segment[index];
579 const int pos = segment_pos + index;
580
581 IndexMaskMemory memory;
582 const IndexMask base_fill = IndexMask::from_indices(fills[fill_index], memory);
583
584 /* Only get curves that are in the fill and valid. */
586 base_fill, memory, [&](const int64_t curve_i) {
587 const IndexRange points = points_by_curve[curve_i];
588 return points.size() >= 3;
589 });
590
591 if (fill.is_empty()) {
592 continue;
593 }
594
595 float3x3 axis_mat;
596 axis_dominant_v3_to_m3(axis_mat.ptr(), normals[fill.first()]);
597 const int num_points = offset_indices::sum_group_sizes(points_by_curve, fill);
598
599 float (*projverts)[2] = static_cast<float (*)[2]>(
600 BLI_memarena_alloc(pf_arena, sizeof(*projverts) * size_t(num_points)));
601
602 int *fill_points_by_curve_data = static_cast<int(*)>(BLI_memarena_alloc(
603 pf_arena, sizeof(*fill_points_by_curve_data) * size_t(fill.size() + 1)));
604 const OffsetIndices<int> fill_points_by_curve =
606 points_by_curve,
607 fill,
608 MutableSpan(fill_points_by_curve_data, fill.size() + 1));
609
610 fill.foreach_index(
611 [&](const int64_t curve_i, const int64_t pos) {
612 const IndexRange fill_points = fill_points_by_curve[pos];
613 const IndexRange points = points_by_curve[curve_i];
614 for (const int i : points.index_range()) {
615 const int curve_p = points[i];
616 const int fill_p = fill_points[i];
617 mul_v2_m3v3(projverts[fill_p], axis_mat.ptr(), positions[curve_p]);
618 }
619 },
621
622 /* If there is only one stroke then simple poly fill will be used. */
623 if (fill.size() == 1) {
624 triangle_results[pos].resize(num_points - 2);
625 MutableSpan<int3> r_tris = triangle_results[pos];
626
627 BLI_polyfill_calc_arena(projverts,
628 num_points,
629 0,
630 reinterpret_cast<uint32_t (*)[3]>(r_tris.data()),
631 pf_arena);
632
633 BLI_memarena_clear(pf_arena);
634 continue;
635 }
636
637 Array<double2, 64> verts(num_points);
638 threading::parallel_for(IndexRange(num_points), 512, [&](const IndexRange range) {
639 for (const int i : range) {
640 verts[i] = double2(projverts[i]);
641 }
642 });
643
644 const Span<float2> projverts_span = Span(reinterpret_cast<float2 *>(projverts),
645 num_points);
646
647 Array<int, 64> face_vert_indices(fill_points_by_curve.total_size());
648 threading::parallel_for(fill.index_range(), 256, [&](const IndexRange range) {
649 for (const int i : range) {
650 const IndexRange fill_points = fill_points_by_curve[i];
651 MutableSpan<int> face = face_vert_indices.as_mutable_span().slice(fill_points);
652
653 array_utils::fill_index_range<int>(face, fill_points.first());
654 const Span<float2> projpoints = projverts_span.slice(fill_points);
655
656 /* Curve have to be in a counterclockwise order, so check if a flip is need. */
657 if (cross_poly_v2(reinterpret_cast<const float (*)[2]>(projpoints.data()),
658 projpoints.size()) < 0.0)
659 {
660 face.reverse();
661 }
662 }
663 });
664
666 input.vert = verts;
667 input.face_offsets = fill_points_by_curve;
668 input.face_vert_indices = face_vert_indices;
670
671 meshintersect::CDT_result<double> result = delaunay_2d_calc(input,
673
674 Map<int, int> vert_id_to_intersection_point;
675 const float3x3 invert_axis_mat = math::invert(axis_mat);
676 const float3 depth_point = positions[points_by_curve[fill.first()].first()];
677 float2 pos2d;
678 mul_v2_m3v3(pos2d, axis_mat.ptr(), depth_point);
679 const float3 depth_direction = depth_point - invert_axis_mat * float3(pos2d, 0.0f);
680
681 for (const int vert : result.vert.index_range()) {
682 /* The point already exists. */
683 if (!result.vert_orig[vert].is_empty()) {
684 continue;
685 }
686
687 vert_id_to_intersection_point.add_new(vert, intersection_point_results[pos].size());
688
689 const float2 co = float2(result.vert[vert]);
690 intersection_point_results[pos].append(invert_axis_mat * float3(co.x, co.y, 0.0f) +
691 depth_direction);
692 }
693
694 auto vert_to_point = [&](const int vert) {
695 /* The points is a newly added intersection point. */
696 if (result.vert_orig[vert].is_empty()) {
697 const int inter = vert_id_to_intersection_point.lookup(vert);
698 return -(inter + 1);
699 }
700 /* Just get the first point if there are multiple at the same position. */
701 return int(result.vert_orig[vert].first());
702 };
703
704 for (const int i : result.face.index_range()) {
705 BLI_assert(result.face[i].size() == 3);
706 const int3 tri = int3(vert_to_point(result.face[i][0]),
707 vert_to_point(result.face[i][1]),
708 vert_to_point(result.face[i][2]));
709
710 triangle_results[pos].append(tri);
711 }
712
713 BLI_memarena_clear(pf_arena);
714 }
715 });
716 },
718
719 threading::parallel_for(triangle_results.index_range(), 512, [&](const IndexRange range) {
720 for (const int i : range) {
721 r_triangle_offsets[i] = triangle_results[i].size();
722 }
723 });
725 intersection_point_results.index_range(), 512, [&](const IndexRange range) {
726 for (const int i : range) {
727 r_intersection_point_offsets[i] = intersection_point_results[i].size();
728 }
729 });
730
732 r_triangle_offsets);
733 const OffsetIndices<int> intersection_point_offsets =
734 offset_indices::accumulate_counts_to_offsets(r_intersection_point_offsets);
735
736 r_triangles.resize(triangle_offsets.total_size());
737 r_intersection_points.resize(intersection_point_offsets.total_size());
738
739 MutableSpan<int3> r_triangles_span = r_triangles.as_mutable_span();
740 threading::parallel_for(fill_mask.index_range(), 512, [&](const IndexRange range) {
741 for (const int pos : range) {
742 const IndexRange fill_range = triangle_offsets[pos];
743 array_utils::copy(triangle_results[pos].as_span(), r_triangles_span.slice(fill_range));
744 }
745 });
746
747 MutableSpan<float3> r_intersection_points_span = r_intersection_points.as_mutable_span();
748 threading::parallel_for(fill_mask.index_range(), 512, [&](const IndexRange range) {
749 for (const int pos : range) {
750 const IndexRange fill_range = intersection_point_offsets[pos];
751 array_utils::copy(intersection_point_results[pos].as_span(),
752 r_intersection_points_span.slice(fill_range));
753 }
754 });
755}
756
757static void ensure_triangle_cache(const Drawing &drawing)
758{
759 drawing.runtime->triangle_cache.ensure([&](std::optional<TriangleCache> &r_triangle_cache) {
760 if (const std::optional<GroupedSpan<int>> fills = drawing.fills()) {
761 TriangleCache triangle_cache;
762 triangle_cache.triangle_offsets.resize(fills->size() + 1);
763 triangle_cache.intersection_point_offsets.resize(fills->size() + 1);
764
765 const CurvesGeometry &curves = drawing.strokes();
767 curves.evaluated_positions(),
768 drawing.curve_plane_normals(),
769 curves.evaluated_points_by_curve(),
770 fills->index_range(),
771 *fills,
772 triangle_cache.triangles,
773 triangle_cache.triangle_offsets.as_mutable_span(),
774 triangle_cache.intersection_points,
776
777 r_triangle_cache = std::move(triangle_cache);
778 }
779 else {
780 r_triangle_cache = std::nullopt;
781 }
782 });
783}
784
785std::optional<GroupedSpan<int3>> Drawing::triangles() const
786{
788 if (this->runtime->triangle_cache.data().has_value()) {
789 const TriangleCache &triangle_cache = *this->runtime->triangle_cache.data();
790 return GroupedSpan<int3>(triangle_cache.triangle_offsets.as_span(),
791 triangle_cache.triangles.as_span());
792 }
793 return std::nullopt;
794}
795
797{
799 if (this->runtime->triangle_cache.data().has_value()) {
800 const TriangleCache &triangle_cache = *this->runtime->triangle_cache.data();
802 triangle_cache.intersection_points.as_span());
803 }
804 return GroupedSpan<float3>({}, {});
805}
806
808 const OffsetIndices<int> points_by_curve,
809 const IndexMask &curve_mask,
810 MutableSpan<float3> normals)
811{
812 curve_mask.foreach_index(
813 [&](const int curve_i) {
814 const IndexRange points = points_by_curve[curve_i];
815 if (points.size() < 2) {
816 normals[curve_i] = float3(1.0f, 0.0f, 0.0f);
817 return;
818 }
819
820 /* Calculate normal using Newell's method. */
821 float3 normal(0.0f);
822 const float3 first_point = positions[points.first()];
823 float3 prev_point = positions[points.last()];
824 float max_extent_sq = 0.0f;
825 for (const int point_i : points) {
826 const float3 curr_point = positions[point_i];
827 add_newell_cross_v3_v3v3(normal, prev_point, curr_point);
828 max_extent_sq = math::max(max_extent_sq, math::length_squared(curr_point - first_point));
829 prev_point = curr_point;
830 }
831
832 float length;
833 normal = math::normalize_and_get_length(normal, length);
834 /* Check for degenerate case where the points are on a line (Newell's method can introduce
835 * a small error that accumulates with many points, scaling with the squared extent of the
836 * stroke, hence the `max_extent_sq` factor). */
837 if (length <
838 std::numeric_limits<float>::epsilon() * math::max(points.size() * max_extent_sq, 1.0f))
839 {
840 for (const int point_i : points.drop_back(1)) {
841 float3 segment_vec = positions[point_i] - positions[point_i + 1];
842 if (math::length_squared(segment_vec) != 0.0f) {
843 normal = math::normalize(float3(segment_vec.y, -segment_vec.x, 0.0f));
844 break;
845 }
846 }
847 }
848
849 normals[curve_i] = normal;
850 },
852}
853
855{
856 this->runtime->curve_plane_normals_cache.ensure([&](Vector<float3> &r_data) {
857 const CurvesGeometry &curves = this->strokes();
858 r_data.reinitialize(curves.curves_num());
860 curves.points_by_curve(),
861 curves.curves_range(),
862 r_data.as_mutable_span());
863 });
864 return this->runtime->curve_plane_normals_cache.data().as_span();
865}
866
867/*
868 * Returns the matrix that transforms from a 3D point in layer-space to a 2D point in
869 * stroke-space for the stroke `curve_i`
870 */
871static float4x2 get_local_to_stroke_matrix(const Span<float3> positions, const float3 normal)
872{
873 using namespace blender::math;
874
875 if (positions.size() <= 2) {
876 return float4x2::identity();
877 }
878
879 const float3 point_0 = positions[0];
880 const float3 point_1 = positions[1];
881
882 /* Local X axis (p0 -> p1) */
883 const float3 local_x = normalize(point_1 - point_0);
884 /* Local Y axis (cross to normal/x axis). */
885 const float3 local_y = normalize(cross(normal, local_x));
886
887 if (length_squared(local_x) == 0.0f || length_squared(local_y) == 0.0f) {
888 return float4x2::identity();
889 }
890
891 /* Get local space using first point as origin. */
892 const float4x2 mat = transpose(
893 float2x4(float4(local_x, -dot(point_0, local_x)), float4(local_y, -dot(point_0, local_y))));
894
895 return mat;
896}
897
898/*
899 * Returns the matrix that transforms from a 2D point in stroke-space to a 2D point in
900 * texture-space for a stroke `curve_i`
901 */
902static float3x2 get_stroke_to_texture_matrix(const float uv_rotation,
903 const float2 uv_translation,
904 const float2 uv_scale)
905{
906 using namespace blender::math;
907
908 const float2 uv_scale_inv = safe_rcp(uv_scale);
909 const float s = sin(uv_rotation);
910 const float c = cos(uv_rotation);
911 const float2x2 rot = float2x2(float2(c, s), float2(-s, c));
912
913 float3x2 texture_matrix = float3x2::identity();
914 /*
915 * The order in which the three transforms are applied has been carefully chosen to be easy to
916 * invert.
917 *
918 * The translation is applied last so that the origin goes to `uv_translation`
919 * The rotation is applied after the scale so that the `u` direction's angle is `uv_rotation`
920 * Scale is the only transform that changes the length of the basis vectors and if it is applied
921 * first it's independent of the other transforms.
922 *
923 * These properties are not true with a different order.
924 */
925
926 /* Apply scale. */
927 texture_matrix = from_scale<float2x2>(uv_scale_inv) * texture_matrix;
928
929 /* Apply rotation. */
930 texture_matrix = rot * texture_matrix;
931
932 /* Apply translation. */
933 texture_matrix[2] += uv_translation;
934
935 return texture_matrix;
936}
937
938static float4x3 expand_4x2_mat(const float4x2 &strokemat)
939{
940 float4x3 strokemat4x3 = float4x3(strokemat);
941
942 /*
943 * We need the diagonal of ones to start from the bottom right instead top left to properly
944 * apply the two matrices.
945 *
946 * i.e.
947 * # # # # # # # #
948 * We need # # # # Instead of # # # #
949 * 0 0 0 1 0 0 1 0
950 *
951 */
952 strokemat4x3[2][2] = 0.0f;
953 strokemat4x3[3][2] = 1.0f;
954
955 return strokemat4x3;
956}
957
959{
960 this->runtime->curve_texture_matrices.ensure([&](Vector<float4x2> &r_data) {
961 const CurvesGeometry &curves = this->strokes();
962 const AttributeAccessor attributes = curves.attributes();
963
964 const VArray<float> uv_rotations = *attributes.lookup_or_default<float>(
965 "uv_rotation", AttrDomain::Curve, 0.0f);
966 const VArray<float2> uv_translations = *attributes.lookup_or_default<float2>(
967 "uv_translation", AttrDomain::Curve, float2(0.0f, 0.0f));
968 const VArray<float2> uv_scales = *attributes.lookup_or_default<float2>(
969 "uv_scale", AttrDomain::Curve, float2(1.0f, 1.0f));
970
971 const OffsetIndices<int> points_by_curve = curves.points_by_curve();
972 const Span<float3> positions = curves.positions();
973 const Span<float3> normals = this->curve_plane_normals();
974
975 r_data.reinitialize(curves.curves_num());
976 threading::parallel_for(curves.curves_range(), 512, [&](const IndexRange range) {
977 for (const int curve_i : range) {
978 const IndexRange points = points_by_curve[curve_i];
979 const float3 normal = normals[curve_i];
980 const float4x2 strokemat = get_local_to_stroke_matrix(positions.slice(points), normal);
981 const float3x2 texture_matrix = get_stroke_to_texture_matrix(
982 uv_rotations[curve_i], uv_translations[curve_i], uv_scales[curve_i]);
983
984 const float4x2 texspace = texture_matrix * expand_4x2_mat(strokemat);
985
986 r_data[curve_i] = texspace;
987 }
988 });
989 });
990 return this->runtime->curve_texture_matrices.data().as_span();
991}
992
994{
996 MutableAttributeAccessor attributes = curves.attributes_for_write();
997 SpanAttributeWriter<float> uv_rotations = attributes.lookup_or_add_for_write_span<float>(
998 "uv_rotation", AttrDomain::Curve);
1000 "uv_translation", AttrDomain::Curve);
1002 "uv_scale", AttrDomain::Curve, AttributeInitValue(float2(1.0f, 1.0f)));
1003
1004 if (!uv_rotations || !uv_translations || !uv_scales) {
1005 /* FIXME: It might be better to ensure the attributes exist and are on the right domain. */
1006 return;
1007 }
1008
1009 const OffsetIndices<int> points_by_curve = curves.points_by_curve();
1010 const Span<float3> positions = curves.positions();
1011 const Span<float3> normals = this->curve_plane_normals();
1012
1013 selection.foreach_index(
1014 [&](const int64_t curve_i, const int64_t pos) {
1015 const IndexRange points = points_by_curve[curve_i];
1016 const float3 normal = normals[curve_i];
1017 const float4x2 strokemat = get_local_to_stroke_matrix(positions.slice(points), normal);
1018 const float4x2 texspace = matrices[pos];
1019
1020 /* We do the computation using doubles to avoid numerical precision errors. */
1021 const double4x3 strokemat4x3 = double4x3(expand_4x2_mat(strokemat));
1022
1023 /*
1024 * We want to solve for `texture_matrix` in the equation:
1025 * `texspace = texture_matrix * strokemat4x3`
1026 * Because these matrices are not square we can not use a standard inverse.
1027 *
1028 * Our problem has the form of: `X = A * Y`
1029 * We can solve for `A` using: `A = X * B`
1030 *
1031 * Where `B` is the Right-sided inverse or Moore-Penrose pseudo inverse.
1032 * Calculated as:
1033 *
1034 * |--------------------------|
1035 * | B = T(Y) * (Y * T(Y))^-1 |
1036 * |--------------------------|
1037 *
1038 * And `T()` is transpose and `()^-1` is the inverse.
1039 */
1040
1041 const double3x4 transpose_strokemat = math::transpose(strokemat4x3);
1042 const double3x4 right_inverse = transpose_strokemat *
1043 math::invert(strokemat4x3 * transpose_strokemat);
1044
1045 const float3x2 texture_matrix = float3x2(double4x2(texspace) * right_inverse);
1046
1047 /* Solve for translation, the translation is simply the origin. */
1048 const float2 uv_translation = texture_matrix[2];
1049
1050 /* Solve rotation, the angle of the `u` basis is the rotation. */
1051 const float uv_rotation = math::atan2(texture_matrix[0][1], texture_matrix[0][0]);
1052
1053 /* Calculate the determinant to check if the `v` scale is negative. */
1054 const float det = math::determinant(float2x2(texture_matrix));
1055
1056 /* Solve scale, scaling is the only transformation that changes the length, so scale factor
1057 * is simply the length. And flip the sign of `v` if the determinant is negative. */
1058 const float2 uv_scale = math::safe_rcp(float2(
1059 math::length(texture_matrix[0]), math::sign(det) * math::length(texture_matrix[1])));
1060
1061 uv_rotations.span[curve_i] = uv_rotation;
1062 uv_translations.span[curve_i] = uv_translation;
1063 uv_scales.span[curve_i] = uv_scale;
1064 },
1066 uv_rotations.finish();
1067 uv_translations.finish();
1068 uv_scales.finish();
1069
1071}
1072
1074{
1075 return this->geometry.wrap();
1076}
1077
1079{
1080 return this->geometry.wrap();
1081}
1082
1084{
1085 return *this->strokes().attributes().lookup_or_default<float>(
1087}
1088
1090{
1091 return bke::get_mutable_attribute<float>(this->strokes_for_write().attribute_storage.wrap(),
1094 this->strokes().points_num(),
1095 0.01f);
1096}
1097
1099{
1100 return *this->strokes().attributes().lookup_or_default<float>(
1102}
1103
1105{
1106 return bke::get_mutable_attribute<float>(this->strokes_for_write().attribute_storage.wrap(),
1109 this->strokes().points_num(),
1110 1.0f);
1111}
1112
1118
1120{
1122 this->strokes_for_write().attribute_storage.wrap(),
1125 this->strokes().points_num(),
1126 ColorGeometry4f(0.0f, 0.0f, 0.0f, 0.0f));
1127}
1128
1134
1136{
1138 this->strokes_for_write().attribute_storage.wrap(),
1141 this->strokes().curves_num(),
1142 ColorGeometry4f(0.0f, 0.0f, 0.0f, 0.0f));
1143}
1144
1149
1151{
1152 this->runtime->triangle_cache.tag_dirty();
1153}
1154
1156{
1157 this->runtime->fill_cache.tag_dirty();
1158 this->tag_triangles_changed();
1159}
1160
1168
1170 const std::optional<GroupedSpan<int>> fills,
1171 const int num_curves,
1172 IndexMaskMemory &memory)
1173{
1174 if (!fills) {
1175 return curve_mask;
1176 }
1177
1178 Array<bool> selected_curves(num_curves);
1179 curve_mask.to_bools(selected_curves);
1180
1181 return IndexMask::from_predicate(fills->index_range(), memory, [&](const int64_t fill_index) {
1182 const Span<int> fill = (*fills)[fill_index];
1183 return std::any_of(
1184 fill.begin(), fill.end(), [&](const int curve_i) { return selected_curves[curve_i]; });
1185 });
1186}
1187
1189 const Span<float3> normals,
1190 const OffsetIndices<int> dst_points_by_curve,
1191 const IndexMask &changed_curves,
1192 const std::optional<GroupedSpan<int>> fills,
1193 const GroupedSpan<int3> src_triangles,
1194 const GroupedSpan<float3> src_intersection_points,
1195 Vector<int3> &r_triangles,
1196 MutableSpan<int> r_triangle_offsets,
1197 Vector<float3> &r_intersection_points,
1198 MutableSpan<int> r_intersection_point_offsets)
1199{
1200 const int num_fills = fills.has_value() ? fills->size() : 0;
1201
1202 IndexMaskMemory memory;
1203 const IndexMask changed_fills = curves_to_fills_mask(
1204 changed_curves, fills, dst_points_by_curve.size(), memory);
1205 const IndexMask unchanged_fills = changed_fills.complement(IndexRange(num_fills), memory);
1206
1207 Array<int> changed_triangle_offsets_data(changed_fills.size() + 1);
1208 Vector<int3> changed_triangles;
1209 Array<int> changed_intersection_point_offsets_data(changed_fills.size() + 1);
1210 Vector<float3> changed_intersection_points;
1211
1212 if (fills) {
1214 normals,
1215 dst_points_by_curve,
1216 changed_fills,
1217 *fills,
1218 changed_triangles,
1219 changed_triangle_offsets_data.as_mutable_span(),
1220 changed_intersection_points,
1221 changed_intersection_point_offsets_data.as_mutable_span()
1222
1223 );
1224 }
1225
1226 const OffsetIndices<int> changed_triangle_offsets = OffsetIndices<int>(
1227 changed_triangle_offsets_data);
1228 const OffsetIndices<int> changed_intersection_point_offsets = OffsetIndices<int>(
1229 changed_intersection_point_offsets_data);
1230
1231 Array<int> all_src_triangle_sizes(num_fills);
1232 Array<int> changed_triangle_sizes(changed_fills.size());
1233 Array<int> all_src_intersection_point_sizes(num_fills);
1234 Array<int> changed_intersection_point_sizes(changed_fills.size());
1235 copy_group_sizes(src_triangles.offsets, src_triangles.index_range(), all_src_triangle_sizes);
1236 copy_group_sizes(
1237 changed_triangle_offsets, changed_triangle_offsets.index_range(), changed_triangle_sizes);
1238 copy_group_sizes(src_intersection_points.offsets,
1239 src_intersection_points.index_range(),
1240 all_src_intersection_point_sizes);
1241 copy_group_sizes(changed_intersection_point_offsets,
1242 changed_intersection_point_offsets.index_range(),
1243 changed_intersection_point_sizes);
1244
1245 Array<int> src_triangle_sizes(unchanged_fills.size());
1246 Array<int> src_intersection_point_sizes(unchanged_fills.size());
1248 all_src_triangle_sizes.as_span(), unchanged_fills, src_triangle_sizes.as_mutable_span());
1249 array_utils::gather(all_src_intersection_point_sizes.as_span(),
1250 unchanged_fills,
1251 src_intersection_point_sizes.as_mutable_span());
1252
1253 array_utils::scatter(src_triangle_sizes.as_span(), unchanged_fills, r_triangle_offsets);
1254 array_utils::scatter(changed_triangle_sizes.as_span(), changed_fills, r_triangle_offsets);
1256 src_intersection_point_sizes.as_span(), unchanged_fills, r_intersection_point_offsets);
1258 changed_intersection_point_sizes.as_span(), changed_fills, r_intersection_point_offsets);
1259
1261 r_triangle_offsets);
1262 const OffsetIndices<int> intersection_point_offsets =
1263 offset_indices::accumulate_counts_to_offsets(r_intersection_point_offsets);
1264
1265 r_triangles.resize(r_triangle_offsets.last());
1266 r_intersection_points.resize(r_intersection_point_offsets.last());
1268 triangle_offsets,
1269 unchanged_fills,
1270 src_triangles.data,
1271 r_triangles.as_mutable_span());
1272 array_utils::copy_group_to_group(src_intersection_points.offsets,
1273 intersection_point_offsets,
1274 unchanged_fills,
1275 src_intersection_points.data,
1276 r_intersection_points.as_mutable_span());
1277
1278 changed_fills.foreach_index(
1279 [&](const int i, const int pos) {
1280 r_triangles.as_mutable_span()
1281 .slice(triangle_offsets[i])
1282 .copy_from(changed_triangles.as_span().slice(changed_triangle_offsets[pos]));
1283 },
1285 changed_fills.foreach_index(
1286 [&](const int i, const int pos) {
1287 r_intersection_points.as_mutable_span()
1288 .slice(intersection_point_offsets[i])
1289 .copy_from(changed_intersection_points.as_span().slice(
1290 changed_intersection_point_offsets[pos]));
1291 },
1293}
1294
1296{
1297 if (changed_curves.is_empty()) {
1298 return;
1299 }
1300 /* If more than half of the curves have changed, update the entire cache instead.
1301 * The assumption here is that it's better to lazily compute the caches if more than half of the
1302 * curves need to be updated.
1303 * TODO: This could probably be a bit more rigorous once this function gets used in more places.
1304 */
1305 if (changed_curves.size() > this->strokes().curves_num() / 2) {
1306 this->tag_positions_changed();
1307 return;
1308 }
1309 if (!this->runtime->triangle_cache.is_cached() ||
1310 !this->runtime->curve_plane_normals_cache.is_cached())
1311 {
1312 this->tag_positions_changed();
1313 return;
1314 }
1315 /* Positions needs to be tagged first, because the triangle cache updates just after need the
1316 * positions to be up-to-date. */
1318 this->runtime->curve_plane_normals_cache.update([&](Vector<float3> &normals) {
1319 const CurvesGeometry &curves = this->strokes();
1321 curves.positions(), curves.points_by_curve(), changed_curves, normals);
1322 });
1323
1325
1326 /* Fills cache needs to be up-to-date. */
1327 this->runtime->fill_cache.tag_dirty();
1328
1329 if (const std::optional<TriangleCache> src_triangle_cache = this->runtime->triangle_cache.data())
1330 {
1331 /* Copy the triangle data. */
1332 const Array<int> src_triangle_offsets(src_triangle_cache->triangle_offsets.as_span());
1333 const Array<int3> src_triangles_data(src_triangle_cache->triangles.as_span());
1334 const GroupedSpan<int3> src_triangles(src_triangle_offsets.as_span(),
1335 src_triangles_data.as_span());
1336 const Array<int> src_intersection_point_offsets(
1337 src_triangle_cache->intersection_point_offsets.as_span());
1338 const Array<float3> src_intersection_points_data(
1339 src_triangle_cache->intersection_points.as_span());
1340 const GroupedSpan<float3> src_intersection_points(src_intersection_point_offsets.as_span(),
1341 src_intersection_points_data.as_span());
1342
1343 this->runtime->triangle_cache.update([&](std::optional<TriangleCache> &r_triangle_cache) {
1344 const std::optional<GroupedSpan<int>> fills = this->fills();
1345 BLI_assert(fills.has_value());
1346
1347 TriangleCache triangle_cache;
1348 triangle_cache.triangle_offsets.resize(fills->size() + 1);
1349 triangle_cache.intersection_point_offsets.resize(fills->size() + 1);
1350
1351 update_triangle_and_offsets_changed(this->strokes().evaluated_positions(),
1352 this->curve_plane_normals(),
1353 this->strokes().evaluated_points_by_curve(),
1354 changed_curves,
1355 fills,
1356 src_triangles,
1357 src_intersection_points,
1358 triangle_cache.triangles,
1359 triangle_cache.triangle_offsets,
1360 triangle_cache.intersection_points,
1361 triangle_cache.intersection_point_offsets);
1362 r_triangle_cache = std::move(triangle_cache);
1363 });
1364 }
1365 else {
1366 this->runtime->triangle_cache.tag_dirty();
1367 }
1368}
1369
1376
1377void Drawing::tag_topology_changed(const IndexMask &changed_curves)
1378{
1379 if (changed_curves.is_empty()) {
1380 return;
1381 }
1382 /* If more than half of the curves have changed, update the entire cache instead.
1383 * The assumption here is that it's better to lazily compute the caches if more than half of the
1384 * curves need to be updated.
1385 * TODO: This could probably be a bit more rigorous once this function gets used in more places.
1386 */
1387 if (changed_curves.size() > this->strokes().curves_num() / 2) {
1388 this->tag_topology_changed();
1389 return;
1390 }
1391 if (!this->runtime->triangle_cache.is_cached() ||
1392 !this->runtime->curve_plane_normals_cache.is_cached())
1393 {
1394 this->tag_topology_changed();
1395 return;
1396 }
1397 /* Positions needs to be tagged first, because the triangle cache updates just after need the
1398 * positions to be up-to-date. */
1400 this->runtime->curve_plane_normals_cache.update([&](Vector<float3> &normals) {
1401 const CurvesGeometry &curves = this->strokes();
1403 curves.positions(), curves.points_by_curve(), changed_curves, normals);
1404 });
1405
1406 /* Fills cache needs to be up-to-date. */
1407 this->runtime->fill_cache.tag_dirty();
1408
1409 if (const std::optional<TriangleCache> src_triangle_cache = this->runtime->triangle_cache.data())
1410 {
1411 /* Copy the triangle data. */
1412 const Array<int> src_triangle_offsets(src_triangle_cache->triangle_offsets.as_span());
1413 const Array<int3> src_triangles_data(src_triangle_cache->triangles.as_span());
1414 const GroupedSpan<int3> src_triangles(src_triangle_offsets.as_span(),
1415 src_triangles_data.as_span());
1416 const Array<int> src_intersection_point_offsets(
1417 src_triangle_cache->intersection_point_offsets.as_span());
1418 const Array<float3> src_intersection_points_data(
1419 src_triangle_cache->intersection_points.as_span());
1420 const GroupedSpan<float3> src_intersection_points(src_intersection_point_offsets.as_span(),
1421 src_intersection_points_data.as_span());
1422
1423 this->runtime->triangle_cache.update([&](std::optional<TriangleCache> &r_triangle_cache) {
1424 const std::optional<GroupedSpan<int>> fills = this->fills();
1425 BLI_assert(fills.has_value());
1426
1427 TriangleCache triangle_cache;
1428 triangle_cache.triangle_offsets.resize(fills->size() + 1);
1429 triangle_cache.intersection_point_offsets.resize(fills->size() + 1);
1430
1431 update_triangle_and_offsets_changed(this->strokes().evaluated_positions(),
1432 this->curve_plane_normals(),
1433 this->strokes().evaluated_points_by_curve(),
1434 changed_curves,
1435 fills,
1436 src_triangles,
1437 src_intersection_points,
1438 triangle_cache.triangles,
1439 triangle_cache.triangle_offsets,
1440 triangle_cache.intersection_points,
1441 triangle_cache.intersection_point_offsets);
1442 r_triangle_cache = std::move(triangle_cache);
1443 });
1444 }
1445 else {
1446 this->runtime->triangle_cache.tag_dirty();
1447 }
1448
1450}
1451
1453{
1456
1457 this->id_reference = nullptr;
1458}
1459
1461{
1463 this->base.flag = other.base.flag;
1464
1465 this->id_reference = other.id_reference;
1466}
1467
1469
1472{
1473 BLI_assert(src_drawings.size() == dst_drawings.size());
1474 for (const int i : src_drawings.index_range()) {
1475 const GreasePencilDrawingBase *src_drawing_base = src_drawings[i];
1476 switch (src_drawing_base->type) {
1477 case GP_DRAWING: {
1478 const GreasePencilDrawing *src_drawing = reinterpret_cast<const GreasePencilDrawing *>(
1479 src_drawing_base);
1480 dst_drawings[i] = reinterpret_cast<GreasePencilDrawingBase *>(
1481 MEM_new<bke::greasepencil::Drawing>(__func__, src_drawing->wrap()));
1482 break;
1483 }
1484 case GP_DRAWING_REFERENCE: {
1485 const GreasePencilDrawingReference *src_drawing_reference =
1486 reinterpret_cast<const GreasePencilDrawingReference *>(src_drawing_base);
1487 dst_drawings[i] = reinterpret_cast<GreasePencilDrawingBase *>(
1488 MEM_new<bke::greasepencil::DrawingReference>(__func__, src_drawing_reference->wrap()));
1489 break;
1490 }
1491 }
1492 }
1493}
1494
1496{
1497 this->next = this->prev = nullptr;
1498 this->parent = nullptr;
1499
1500 this->GreasePencilLayerTreeNode::name = nullptr;
1502 this->color[0] = this->color[1] = this->color[2] = 0;
1503}
1504
1506{
1507 this->type = type;
1508}
1509
1515
1517{
1518 this->GreasePencilLayerTreeNode::name = BLI_strdup_null(other.GreasePencilLayerTreeNode::name);
1519 this->flag = other.flag;
1520 copy_v3_v3(this->color, other.color);
1521}
1522
1524{
1525 MEM_SAFE_DELETE(this->GreasePencilLayerTreeNode::name);
1526}
1527
1528void TreeNode::set_name(const StringRef name)
1529{
1530 MEM_SAFE_DELETE(this->GreasePencilLayerTreeNode::name);
1531 this->GreasePencilLayerTreeNode::name = BLI_strdupn(name.data(), name.size());
1532}
1533
1535{
1536 return *reinterpret_cast<const LayerGroup *>(this);
1537}
1538
1540{
1541 return *reinterpret_cast<const Layer *>(this);
1542}
1543
1545{
1546 return *reinterpret_cast<LayerGroup *>(this);
1547}
1548
1550{
1551 return *reinterpret_cast<Layer *>(this);
1552}
1553
1555{
1556 return (this->parent) ? &this->parent->wrap() : nullptr;
1557}
1559{
1560 return (this->parent) ? &this->parent->wrap() : nullptr;
1561}
1563{
1564 return this->parent_group() ? &this->parent->wrap().as_node() : nullptr;
1565}
1567{
1568 return this->parent_group() ? &this->parent->wrap().as_node() : nullptr;
1569}
1570
1572{
1573 const LayerGroup *parent = this->parent_group();
1574 if (parent == nullptr) {
1575 /* The root group has a depth of 0. */
1576 return 0;
1577 }
1578 return 1 + parent->as_node().depth();
1579}
1580
1582{
1583 this->layer_name = nullptr;
1585}
1586
1588{
1589 this->layer_name = BLI_strdupn(name.data(), name.size());
1590}
1591
1593{
1594 this->layer_name = BLI_strdup_null(other.layer_name);
1595 this->flag = other.flag;
1596}
1597
1599{
1600 if (this->layer_name) {
1601 MEM_delete(this->layer_name);
1602 }
1603}
1604
1606{
1607 frames_.clear();
1608 sorted_keys_cache_.tag_dirty();
1609 masks_.clear_and_shrink();
1610 trans_data_ = {};
1611}
1612
1614{
1615 new (&this->base) TreeNode(GP_LAYER_TREE_LEAF);
1616
1617 this->frames_storage.num = 0;
1618 this->frames_storage.keys = nullptr;
1619 this->frames_storage.values = nullptr;
1621
1623 this->opacity = 1.0f;
1624
1625 this->parent = nullptr;
1626 this->parsubstr = nullptr;
1627 unit_m4(this->parentinv);
1628
1629 zero_v3(this->translation);
1630 zero_v3(this->rotation);
1631 copy_v3_fl(this->scale, 1.0f);
1632
1633 this->viewlayername = nullptr;
1634
1635 this->masks.clear_no_delete();
1636 this->active_mask_index = 0;
1637
1638 this->runtime = MEM_new<LayerRuntime>(__func__);
1639}
1640
1642{
1643 new (&this->base) TreeNode(GP_LAYER_TREE_LEAF, name);
1644}
1645
1646Layer::Layer(const Layer &other) : Layer()
1647{
1648 new (&this->base) TreeNode(other.base.wrap());
1649
1650 for (GreasePencilLayerMask &other_mask : other.masks) {
1651 LayerMask *new_mask = MEM_new<LayerMask>(__func__,
1652 *reinterpret_cast<LayerMask *>(&other_mask));
1653 BLI_addtail(&this->masks, reinterpret_cast<GreasePencilLayerMask *>(new_mask));
1654 }
1656
1657 this->blend_mode = other.blend_mode;
1658 this->opacity = other.opacity;
1659
1660 this->parent = other.parent;
1661 this->set_parent_bone_name(other.parsubstr);
1662 copy_m4_m4(this->parentinv, other.parentinv);
1663
1664 copy_v3_v3(this->translation, other.translation);
1665 copy_v3_v3(this->rotation, other.rotation);
1666 copy_v3_v3(this->scale, other.scale);
1667
1669
1670 /* NOTE: We do not duplicate the frame storage since it is only needed for writing to file. */
1671 this->runtime->frames_ = other.runtime->frames_;
1673 /* Tag the frames map, so the frame storage is recreated once the DNA is saved. */
1674 this->tag_frames_map_changed();
1675
1676 /* Keep the mapping to the original layer when evaluated data is copied, e.g. by modifiers. */
1678
1679 /* TODO: what about masks cache? */
1680}
1681
1683{
1684 this->base.wrap().~TreeNode();
1685
1686 MEM_SAFE_DELETE(this->frames_storage.keys);
1687 MEM_SAFE_DELETE(this->frames_storage.values);
1688
1689 for (GreasePencilLayerMask &mask : this->masks.items_mutable()) {
1690 MEM_delete(reinterpret_cast<LayerMask *>(&mask));
1691 }
1692 this->masks.clear_no_delete();
1693
1694 MEM_SAFE_DELETE(this->parsubstr);
1695 MEM_SAFE_DELETE(this->viewlayername);
1696
1697 MEM_delete(this->runtime);
1698 this->runtime = nullptr;
1699}
1700
1702{
1703 return this->runtime->frames_;
1704}
1705
1710
1711Layer::SortedKeysIterator Layer::remove_leading_end_frames_in_range(
1713{
1715 while (next_it != end && this->frames().lookup(*next_it).is_end()) {
1716 this->frames_for_write().remove_contained(*next_it);
1718 next_it = std::next(next_it);
1719 }
1720 return next_it;
1721}
1722
1723GreasePencilFrame *Layer::add_frame_internal(const FramesMapKeyT frame_number)
1724{
1725 if (!this->frames().contains(frame_number)) {
1726 GreasePencilFrame frame{};
1727 this->frames_for_write().add_new(frame_number, frame);
1729 return this->frames_for_write().lookup_ptr(frame_number);
1730 }
1731 /* Overwrite end-frames. */
1732 if (this->frames().lookup(frame_number).is_end()) {
1733 GreasePencilFrame frame{};
1734 this->frames_for_write().add_overwrite(frame_number, frame);
1735 this->tag_frames_map_changed();
1736 return this->frames_for_write().lookup_ptr(frame_number);
1737 }
1738 return nullptr;
1739}
1740
1741GreasePencilFrame *Layer::add_frame(const FramesMapKeyT key, /* const */ int duration)
1742{
1743 BLI_assert(duration == 0);
1744 duration = 0;
1745 GreasePencilFrame *frame = this->add_frame_internal(key);
1746 if (frame == nullptr) {
1747 return nullptr;
1748 }
1749 Span<FramesMapKeyT> sorted_keys = this->sorted_keys();
1750 const FramesMapKeyT end_key = key + duration;
1751 /* Finds the next greater key that is stored in the map. */
1752 SortedKeysIterator next_key_it = std::upper_bound(sorted_keys.begin(), sorted_keys.end(), key);
1753 /* If the next frame we found is at the end of the frame we're inserting, then we are done. */
1754 if (next_key_it != sorted_keys.end() && *next_key_it == end_key) {
1755 return frame;
1756 }
1757 next_key_it = this->remove_leading_end_frames_in_range(next_key_it, sorted_keys.end());
1758 /* If the duration is set to 0, the frame is marked as an implicit hold. */
1759 if (duration == 0) {
1760 frame->flag |= GP_FRAME_IMPLICIT_HOLD;
1761 return frame;
1762 }
1763 /* If the next frame comes after the end of the frame we're inserting (or if there are no more
1764 * frames), add an end-frame. */
1765 if (next_key_it == sorted_keys.end() || *next_key_it > end_key) {
1766 this->frames_for_write().add_new(end_key, GreasePencilFrame::end());
1768 }
1769 return frame;
1770}
1771
1773{
1774 /* If the frame number is not in the frames map, do nothing. */
1775 if (!this->frames().contains(key)) {
1776 return false;
1777 }
1778 if (this->frames().size() == 1) {
1779 this->frames_for_write().remove_contained(key);
1781 return true;
1782 }
1783 Span<FramesMapKeyT> sorted_keys = this->sorted_keys();
1784 /* Find the index of the frame to remove in the `sorted_keys` array. */
1785 SortedKeysIterator remove_key_it = std::lower_bound(sorted_keys.begin(), sorted_keys.end(), key);
1786 /* If there is a next frame: */
1787 if (std::next(remove_key_it) != sorted_keys.end()) {
1788 SortedKeysIterator next_key_it = std::next(remove_key_it);
1789 this->remove_leading_end_frames_in_range(next_key_it, sorted_keys.end());
1790 }
1791 /* If there is a previous frame: */
1792 if (remove_key_it != sorted_keys.begin()) {
1793 SortedKeysIterator prev_key_it = std::prev(remove_key_it);
1794 const GreasePencilFrame &prev_frame = this->frames().lookup(*prev_key_it);
1795 /* If the previous frame is not an implicit hold (e.g. it has a fixed duration) and it's not an
1796 * end frame, we cannot just delete the frame. We need to replace it with an end frame. */
1797 /* FIXME: Disabled for now, do not create end frames ever. */
1798 if (false && !prev_frame.is_implicit_hold() && !prev_frame.is_end()) {
1799 this->frames_for_write().lookup(key) = GreasePencilFrame::end();
1800 this->tag_frames_map_changed();
1801 /* Since the original frame was replaced with an end frame, we consider the frame to be
1802 * successfully removed here. */
1803 return true;
1804 }
1805 }
1806 /* Finally, remove the actual frame. */
1807 this->frames_for_write().remove_contained(key);
1809 return true;
1810}
1811
1813{
1814 this->runtime->sorted_keys_cache_.ensure([&](Vector<FramesMapKeyT> &r_data) {
1815 r_data.reinitialize(this->frames().size());
1816 int i = 0;
1817 for (const FramesMapKeyT key : this->frames().keys()) {
1818 r_data[i++] = key;
1819 }
1820 std::ranges::sort(r_data);
1821 });
1822 return this->runtime->sorted_keys_cache_.data();
1823}
1824
1826{
1827 Span<int> sorted_keys = this->sorted_keys();
1828 /* No keyframes, return nullptr. */
1829 if (sorted_keys.is_empty()) {
1830 return nullptr;
1831 }
1832 /* Before the first frame, return nullptr. */
1833 if (frame_number < sorted_keys.first()) {
1834 return nullptr;
1835 }
1836 /* After or at the last frame, return iterator to last. */
1837 if (frame_number >= sorted_keys.last()) {
1838 return std::prev(sorted_keys.end());
1839 }
1840 /* Search for the frame. std::upper_bound will get the frame just after. */
1841 SortedKeysIterator it = std::upper_bound(sorted_keys.begin(), sorted_keys.end(), frame_number);
1842 if (it == sorted_keys.end()) {
1843 return nullptr;
1844 }
1845 return std::prev(it);
1846}
1847
1848std::optional<FramesMapKeyT> Layer::frame_key_at(const int frame_number) const
1849{
1850 SortedKeysIterator it = this->sorted_keys_iterator_at(frame_number);
1851 if (it == nullptr) {
1852 return {};
1853 }
1854 return *it;
1855}
1856
1857std::optional<int> Layer::start_frame_at(int frame_number) const
1858{
1859 const std::optional<FramesMapKeyT> frame_key = this->frame_key_at(frame_number);
1860 /* Return the frame number only if the frame key exists and if it's not an end frame. */
1861 if (frame_key && !this->frames().lookup_ptr(*frame_key)->is_end()) {
1862 return frame_key;
1863 }
1864 return {};
1865}
1866
1867int Layer::sorted_keys_index_at(const int frame_number) const
1868{
1869 SortedKeysIterator it = this->sorted_keys_iterator_at(frame_number);
1870 if (it == nullptr) {
1871 return -1;
1872 }
1873 return std::distance(this->sorted_keys().begin(), it);
1874}
1875
1876const GreasePencilFrame *Layer::frame_at(const int frame_number) const
1877{
1878 const GreasePencilFrame *frame_ptr = [&]() -> const GreasePencilFrame * {
1879 if (const GreasePencilFrame *frame = this->frames().lookup_ptr(frame_number)) {
1880 return frame;
1881 }
1882 /* Look for a keyframe that starts before `frame_number` and ends after `frame_number`. */
1883 const std::optional<FramesMapKeyT> frame_key = this->frame_key_at(frame_number);
1884 if (!frame_key) {
1885 return nullptr;
1886 }
1887 return this->frames().lookup_ptr(*frame_key);
1888 }();
1889 if (frame_ptr == nullptr || frame_ptr->is_end()) {
1890 /* Not a valid frame. */
1891 return nullptr;
1892 }
1893 return frame_ptr;
1894}
1895
1896GreasePencilFrame *Layer::frame_at(const int frame_number)
1897{
1898 GreasePencilFrame *frame_ptr = [&]() -> GreasePencilFrame * {
1899 if (GreasePencilFrame *frame = this->frames_for_write().lookup_ptr(frame_number)) {
1900 return frame;
1901 }
1902 /* Look for a keyframe that starts before `frame_number`. */
1903 const std::optional<FramesMapKeyT> frame_key = this->frame_key_at(frame_number);
1904 if (!frame_key) {
1905 return nullptr;
1906 }
1907 return this->frames_for_write().lookup_ptr(*frame_key);
1908 }();
1909 if (frame_ptr == nullptr || frame_ptr->is_end()) {
1910 /* Not a valid frame. */
1911 return nullptr;
1912 }
1913 return frame_ptr;
1914}
1915
1916int Layer::drawing_index_at(const int frame_number) const
1917{
1918 const GreasePencilFrame *frame = frame_at(frame_number);
1919 return (frame != nullptr) ? frame->drawing_index : -1;
1920}
1921
1922bool Layer::has_drawing_at(const int frame_number) const
1923{
1924 return frame_at(frame_number) != nullptr;
1925}
1926
1927int Layer::get_frame_duration_at(const int frame_number) const
1928{
1929 SortedKeysIterator it = this->sorted_keys_iterator_at(frame_number);
1930 if (it == nullptr) {
1931 return -1;
1932 }
1933 const FramesMapKeyT key = *it;
1934 const GreasePencilFrame *frame = this->frames().lookup_ptr(key);
1935 /* For frames that are implicitly held, we return a duration of 0. */
1936 if (frame->is_implicit_hold()) {
1937 return 0;
1938 }
1939 /* Frame is an end frame, so there is no keyframe at `frame_number`. */
1940 if (frame->is_end()) {
1941 return -1;
1942 }
1943 /* Last frame without a following end frame (end frames are not created anymore), it is
1944 * effectively held indefinitely. */
1945 if (std::next(it) == this->sorted_keys().end()) {
1946 return 0;
1947 } /* Compute the distance in frames between this key and the next key. */
1948 const int next_frame_number = *(std::next(it));
1949 return math::distance(key, next_frame_number);
1950}
1951
1956
1958{
1959 this->tag_frames_map_changed();
1960 this->runtime->sorted_keys_cache_.tag_dirty();
1961}
1962
1964{
1965 /* Re-create the frames storage only if it was tagged dirty. */
1967 return;
1968 }
1969
1970 MEM_SAFE_DELETE(frames_storage.keys);
1971 MEM_SAFE_DELETE(frames_storage.values);
1972
1973 const size_t frames_num = size_t(frames().size());
1974 frames_storage.num = int(frames_num);
1975 frames_storage.keys = MEM_new_array<int>(frames_num, __func__);
1976 frames_storage.values = MEM_new_array<GreasePencilFrame>(frames_num, __func__);
1977 const Span<int> sorted_keys_data = sorted_keys();
1978 for (const int64_t i : sorted_keys_data.index_range()) {
1979 frames_storage.keys[i] = sorted_keys_data[i];
1980 frames_storage.values[i] = frames().lookup(sorted_keys_data[i]);
1981 }
1982
1983 /* Reset the flag. */
1985}
1986
1988{
1989 /* Re-create frames data in runtime map. */
1990 /* NOTE: Avoid re-allocating runtime data to reduce 'false positive' change detection from
1991 * MEMFILE undo. */
1992 if (runtime) {
1993 runtime->clear();
1994 }
1995 else {
1996 runtime = MEM_new<bke::greasepencil::LayerRuntime>(__func__);
1997 }
1999 for (int i = 0; i < frames_storage.num; i++) {
2001 }
2002}
2003
2005{
2006 if (this->parent == nullptr) {
2007 return object.object_to_world() * this->local_transform();
2008 }
2009 const Object &parent = *this->parent;
2010 return this->parent_to_world(parent) * this->parent_inverse() * this->local_transform();
2011}
2012
2014{
2015 if (this->parent == nullptr) {
2016 return this->local_transform();
2017 }
2018 const Object &parent = *this->parent;
2019 return object.world_to_object() * this->parent_to_world(parent) * this->parent_inverse() *
2020 this->local_transform();
2021}
2022
2024{
2025 return (this->parsubstr != nullptr) ? StringRefNull(this->parsubstr) : StringRefNull();
2026}
2027
2029{
2030 if (this->parsubstr != nullptr) {
2031 MEM_delete(this->parsubstr);
2032 this->parsubstr = nullptr;
2033 }
2034 if (!new_name.is_empty()) {
2035 this->parsubstr = BLI_strdupn(new_name.data(), new_name.size());
2036 }
2037}
2038
2039float4x4 Layer::parent_to_world(const Object &parent) const
2040{
2041 const float4x4 &parent_object_to_world = parent.object_to_world();
2042 if (parent.type == OB_ARMATURE && !this->parent_bone_name().is_empty()) {
2044 this->parent_bone_name().c_str()))
2045 {
2046 return parent_object_to_world * float4x4_view(channel->pose_mat);
2047 }
2048 }
2049 return parent_object_to_world;
2050}
2051
2053{
2054 return float4x4_view(this->parentinv);
2055}
2056
2062
2064{
2066 *reinterpret_cast<float3 *>(this->translation),
2067 *reinterpret_cast<math::EulerXYZ *>(this->rotation),
2068 *reinterpret_cast<float3 *>(this->scale));
2069}
2070
2072{
2073 return (this->viewlayername != nullptr) ? StringRefNull(this->viewlayername) : StringRefNull();
2074}
2075
2077{
2078 if (this->viewlayername != nullptr) {
2079 MEM_delete(this->viewlayername);
2080 this->viewlayername = nullptr;
2081 }
2082 if (!new_name.is_empty()) {
2083 this->viewlayername = BLI_strdupn(new_name.data(), new_name.size());
2084 }
2085}
2086
2088{
2089 new (&this->base) TreeNode(GP_LAYER_TREE_GROUP);
2090
2091 this->children.clear_no_delete();
2093
2094 this->runtime = MEM_new<LayerGroupRuntime>(__func__);
2095}
2096
2098{
2099 new (&this->base) TreeNode(GP_LAYER_TREE_GROUP, name);
2100}
2101
2103{
2104 new (&this->base) TreeNode(other.base.wrap());
2105
2106 for (GreasePencilLayerTreeNode &child : other.children) {
2107 switch (child.type) {
2108 case GP_LAYER_TREE_LEAF: {
2109 GreasePencilLayer *layer = reinterpret_cast<GreasePencilLayer *>(&child);
2110 Layer *dup_layer = MEM_new<Layer>(__func__, layer->wrap());
2111 this->add_node(dup_layer->as_node());
2112 break;
2113 }
2114 case GP_LAYER_TREE_GROUP: {
2115 GreasePencilLayerTreeGroup *group = reinterpret_cast<GreasePencilLayerTreeGroup *>(&child);
2116 LayerGroup *dup_group = MEM_new<LayerGroup>(__func__, group->wrap());
2117 this->add_node(dup_group->as_node());
2118 break;
2119 }
2120 }
2121 }
2122
2123 this->color_tag = other.color_tag;
2124}
2125
2127{
2128 this->base.wrap().~TreeNode();
2129
2130 for (GreasePencilLayerTreeNode &child : this->children.items_mutable()) {
2131 switch (child.type) {
2132 case GP_LAYER_TREE_LEAF: {
2133 GreasePencilLayer *layer = reinterpret_cast<GreasePencilLayer *>(&child);
2134 MEM_delete(&layer->wrap());
2135 break;
2136 }
2137 case GP_LAYER_TREE_GROUP: {
2138 GreasePencilLayerTreeGroup *group = reinterpret_cast<GreasePencilLayerTreeGroup *>(&child);
2139 MEM_delete(&group->wrap());
2140 break;
2141 }
2142 }
2143 }
2144
2145 MEM_delete(this->runtime);
2146 this->runtime = nullptr;
2147}
2148
2150{
2151 if (this == &other) {
2152 return *this;
2153 }
2154
2155 this->~LayerGroup();
2156 new (this) LayerGroup(other);
2157
2158 return *this;
2159}
2160
2162{
2163 return this->children.is_empty();
2164}
2165
2167{
2168 BLI_addtail(&this->children, &node);
2169 node.parent = reinterpret_cast<GreasePencilLayerTreeGroup *>(this);
2170 this->tag_nodes_cache_dirty();
2171 return node;
2172}
2174{
2175 BLI_assert(BLI_findindex(&this->children, &link) != -1);
2176 BLI_insertlinkbefore(&this->children, &link, &node);
2177 node.parent = reinterpret_cast<GreasePencilLayerTreeGroup *>(this);
2178 this->tag_nodes_cache_dirty();
2179}
2181{
2182 BLI_assert(BLI_findindex(&this->children, &link) != -1);
2183 BLI_insertlinkafter(&this->children, &link, &node);
2184 node.parent = reinterpret_cast<GreasePencilLayerTreeGroup *>(this);
2185 this->tag_nodes_cache_dirty();
2186}
2187
2189{
2191 this->tag_nodes_cache_dirty();
2192}
2194{
2196 this->tag_nodes_cache_dirty();
2197}
2199{
2200 BLI_remlink(&this->children, &node);
2201 BLI_insertlinkafter(&this->children, this->children.last(), &node);
2202 this->tag_nodes_cache_dirty();
2203}
2205{
2206 BLI_remlink(&this->children, &node);
2207 BLI_insertlinkbefore(&this->children, this->children.first(), &node);
2208 this->tag_nodes_cache_dirty();
2209}
2210
2212{
2213 return this->children.count();
2214}
2215
2217{
2218 this->ensure_nodes_cache();
2219 return this->runtime->nodes_cache_.size();
2220}
2221
2222bool LayerGroup::unlink_node(TreeNode &link, const bool keep_children)
2223{
2224 if (link.is_group() && !link.as_group().is_empty() && keep_children) {
2225 if (BLI_findindex(&this->children, &link) == -1) {
2226 return false;
2227 }
2228
2229 /* Take ownership of the children of `link` by replacing the node with the listbase of its
2230 * children. */
2231 ListBaseT<GreasePencilLayerTreeNode> link_children = link.as_group().children;
2232 GreasePencilLayerTreeNode *first = link_children.first();
2233 GreasePencilLayerTreeNode *last = link_children.last();
2234
2235 /* Rewrite the parent pointers. */
2236 for (GreasePencilLayerTreeNode &child : link_children) {
2237 child.parent = this;
2238 }
2239
2240 /* Update previous and/or next link(s). */
2241 if (link.next != nullptr) {
2242 link.next->prev = last;
2243 last->next = link.next;
2244 }
2245 if (link.prev != nullptr) {
2246 link.prev->next = first;
2247 first->prev = link.prev;
2248 }
2249
2250 /* Update first and/or last link(s). */
2251 if (this->children.last() == &link) {
2252 this->children.last_ = last;
2253 }
2254 if (this->children.first() == &link) {
2255 this->children.first_ = first;
2256 }
2257
2258 /* Listbase has been inserted in `this->children` we can clear the pointers in `link`. */
2260 link.parent = nullptr;
2261
2262 this->tag_nodes_cache_dirty();
2263 return true;
2264 }
2265 if (BLI_remlink_safe(&this->children, &link)) {
2266 link.parent = nullptr;
2267 this->tag_nodes_cache_dirty();
2268 return true;
2269 }
2270 return false;
2271}
2272
2274{
2275 this->ensure_nodes_cache();
2276 return this->runtime->nodes_cache_.as_span();
2277}
2278
2280{
2281 this->ensure_nodes_cache();
2282 return this->runtime->nodes_cache_.as_span();
2283}
2284
2286{
2287 this->ensure_nodes_cache();
2288 return this->runtime->layer_cache_.as_span();
2289}
2290
2292{
2293 this->ensure_nodes_cache();
2294 return this->runtime->layer_cache_.as_span();
2295}
2296
2298{
2299 this->ensure_nodes_cache();
2300 return this->runtime->layer_group_cache_.as_span();
2301}
2302
2304{
2305 this->ensure_nodes_cache();
2306 return this->runtime->layer_group_cache_.as_span();
2307}
2308
2310{
2311 for (const TreeNode *node : this->nodes()) {
2312 if (node->name() == name) {
2313 return node;
2314 }
2315 }
2316 return nullptr;
2317}
2318
2320{
2321 for (TreeNode *node : this->nodes_for_write()) {
2322 if (node->name() == name) {
2323 return node;
2324 }
2325 }
2326 return nullptr;
2327}
2328
2330{
2331 return (this->base.flag & GP_LAYER_TREE_NODE_EXPANDED) != 0;
2332}
2333
2334void LayerGroup::set_expanded(const bool expanded)
2335{
2337}
2338
2339void LayerGroup::print_nodes(const StringRef header) const
2340{
2341 std::cout << header << std::endl;
2343 for (const GreasePencilLayerTreeNode &child_ : this->children.items_reversed()) {
2344 const TreeNode *child = reinterpret_cast<const TreeNode *>(&child_);
2345 next_node.push(std::make_pair(1, child));
2346 }
2347 while (!next_node.is_empty()) {
2348 auto [indent, node] = next_node.pop();
2349 for (int i = 0; i < indent; i++) {
2350 std::cout << " ";
2351 }
2352 if (node->is_layer()) {
2353 std::cout << node->name();
2354 }
2355 else if (node->is_group()) {
2356 std::cout << node->name() << ": ";
2357 for (const GreasePencilLayerTreeNode &child_ : node->as_group().children.items_reversed()) {
2358 const TreeNode *child = reinterpret_cast<const TreeNode *>(&child_);
2359 next_node.push(std::make_pair(indent + 1, child));
2360 }
2361 }
2362 std::cout << std::endl;
2363 }
2364 std::cout << std::endl;
2365}
2366
2367void LayerGroup::ensure_nodes_cache() const
2368{
2369 this->runtime->nodes_cache_mutex_.ensure([&]() {
2370 this->runtime->nodes_cache_.clear_and_shrink();
2371 this->runtime->layer_cache_.clear_and_shrink();
2372 this->runtime->layer_group_cache_.clear_and_shrink();
2373
2374 for (GreasePencilLayerTreeNode &child_ : this->children) {
2375 TreeNode *node = reinterpret_cast<TreeNode *>(&child_);
2376 this->runtime->nodes_cache_.append(node);
2377 switch (node->type) {
2378 case GP_LAYER_TREE_LEAF: {
2379 this->runtime->layer_cache_.append(&node->as_layer());
2380 break;
2381 }
2382 case GP_LAYER_TREE_GROUP: {
2383 this->runtime->layer_group_cache_.append(&node->as_group());
2384 for (TreeNode *child : node->as_group().nodes_for_write()) {
2385 this->runtime->nodes_cache_.append(child);
2386 if (child->is_layer()) {
2387 this->runtime->layer_cache_.append(&child->as_layer());
2388 }
2389 else if (child->is_group()) {
2390 this->runtime->layer_group_cache_.append(&child->as_group());
2391 }
2392 }
2393 break;
2394 }
2395 }
2396 }
2397 });
2398}
2399
2400void LayerGroup::tag_nodes_cache_dirty() const
2401{
2403 if (this->base.parent) {
2404 this->base.parent->wrap().tag_nodes_cache_dirty();
2405 }
2406}
2407
2409{
2410 for (GreasePencilLayerTreeNode &child_ : children) {
2411 TreeNode &child = child_.wrap();
2412 switch (child.type) {
2413 case GP_LAYER_TREE_LEAF: {
2415 break;
2416 }
2417 case GP_LAYER_TREE_GROUP: {
2419 break;
2420 }
2421 }
2422 }
2423}
2424
2426{
2427 for (GreasePencilLayerTreeNode &child_ : children) {
2428 TreeNode &child = child_.wrap();
2429 switch (child.type) {
2430 case GP_LAYER_TREE_LEAF: {
2432 break;
2433 }
2434 case GP_LAYER_TREE_GROUP: {
2436 break;
2437 }
2438 }
2439 }
2440}
2441
2443{
2444 for (bke::greasepencil::Layer *layer : grease_pencil.layers_for_write()) {
2445 if (layer->name().is_empty()) {
2446 grease_pencil.rename_node(bmain, layer->as_node(), DATA_("Layer"));
2447 }
2448 }
2449}
2450
2451} // namespace bke::greasepencil
2452
2453namespace bke {
2454
2457
2458std::optional<Span<float3>> GreasePencilDrawingEditHints::positions() const
2459{
2460 if (!this->positions_data.has_value()) {
2461 return std::nullopt;
2462 }
2463 const int points_num = this->drawing_orig->geometry.wrap().points_num();
2464 return Span(static_cast<const float3 *>(this->positions_data.data), points_num);
2465}
2466
2467std::optional<MutableSpan<float3>> GreasePencilDrawingEditHints::positions_for_write()
2468{
2469 if (!this->positions_data.has_value()) {
2470 return std::nullopt;
2471 }
2472
2473 const int points_num = this->drawing_orig->geometry.wrap().points_num();
2475 if (data.sharing_info->is_mutable()) {
2476 /* If the referenced component is already mutable, return it directly. */
2477 data.sharing_info->tag_ensured_mutable();
2478 }
2479 else {
2480 auto *new_sharing_info = new ImplicitSharedValue<Array<float3>>(*this->positions());
2481 data.sharing_info = ImplicitSharingPtr<>(new_sharing_info);
2482 data.data = new_sharing_info->data.data();
2483 }
2484
2485 return MutableSpan(const_cast<float3 *>(static_cast<const float3 *>(data.data)), points_num);
2486}
2487
2488} // namespace bke
2489
2490/* ------------------------------------------------------------------- */
2493
2495 const StringRef name)
2496{
2497 return name == ATTR_POSITION;
2498}
2499
2500GreasePencil *BKE_grease_pencil_add(Main *bmain, const char *name)
2501{
2503
2504 return grease_pencil;
2505}
2506
2512
2514{
2515 GreasePencil *grease_pencil = reinterpret_cast<GreasePencil *>(
2516 BKE_id_copy_ex(nullptr, &grease_pencil_src->id, nullptr, LIB_ID_COPY_LOCALIZE));
2517 grease_pencil->runtime->eval_frame = grease_pencil_src->runtime->eval_frame;
2518 return grease_pencil;
2519}
2520
2522{
2523 dst.material_array_num = src.material_array_num;
2524 dst.material_array = MEM_dupalloc(src.material_array);
2525 dst.attributes_active_index = src.attributes_active_index;
2526 dst.flag = src.flag;
2527 BLI_duplicatelist(&dst.vertex_group_names, &src.vertex_group_names);
2528 dst.vertex_group_active_index = src.vertex_group_active_index;
2529 dst.onion_skinning_settings = src.onion_skinning_settings;
2530}
2531
2534{
2535 using namespace blender::bke::greasepencil;
2536 dst.as_node().flag = src.as_node().flag;
2537 copy_v3_v3(dst.as_node().color, src.as_node().color);
2538
2539 dst.blend_mode = src.blend_mode;
2540 dst.opacity = src.opacity;
2541
2542 for (GreasePencilLayerMask &src_mask : src.masks) {
2543 LayerMask *new_mask = MEM_new<LayerMask>(__func__, *reinterpret_cast<LayerMask *>(&src_mask));
2544 BLI_addtail(&dst.masks, reinterpret_cast<GreasePencilLayerMask *>(new_mask));
2545 }
2547
2548 dst.parent = src.parent;
2550 copy_m4_m4(dst.parentinv, src.parentinv);
2551
2553 copy_v3_v3(dst.rotation, src.rotation);
2554 copy_v3_v3(dst.scale, src.scale);
2555
2557}
2558
2567
2569 GreasePencil *grease_pencil_dst)
2570{
2573
2574 /* Drawings. */
2575 free_drawing_array(*grease_pencil_dst);
2576 grease_pencil_dst->resize_drawings(grease_pencil_src->drawing_array_num);
2577 for (const int i : IndexRange(grease_pencil_dst->drawing_array_num)) {
2578 switch (grease_pencil_src->drawing_array[i]->type) {
2579 case GP_DRAWING: {
2580 const Drawing &src_drawing =
2581 reinterpret_cast<GreasePencilDrawing *>(grease_pencil_src->drawing_array[i])->wrap();
2582 grease_pencil_dst->drawing_array[i] = &MEM_new<Drawing>(__func__, src_drawing)->base;
2583 break;
2584 }
2586 const DrawingReference &src_drawing_ref = reinterpret_cast<GreasePencilDrawingReference *>(
2587 grease_pencil_src->drawing_array[i])
2588 ->wrap();
2589 grease_pencil_dst->drawing_array[i] =
2590 &MEM_new<DrawingReference>(__func__, src_drawing_ref)->base;
2591 break;
2592 }
2593 }
2594
2595 /* Layers. */
2596 if (grease_pencil_dst->root_group_ptr) {
2597 MEM_delete(&grease_pencil_dst->root_group());
2598 }
2599
2600 grease_pencil_dst->root_group_ptr = MEM_new<bke::greasepencil::LayerGroup>(
2601 __func__, grease_pencil_src->root_group_ptr->wrap());
2602 BLI_assert(grease_pencil_src->layers().size() == grease_pencil_dst->layers().size());
2603
2604 /* Reset the active node. */
2605 grease_pencil_dst->active_node = nullptr;
2606
2607 grease_pencil_dst->attribute_storage.wrap() = std::move(
2608 grease_pencil_src->attribute_storage.wrap());
2609
2610 /* Duplicating drawings does not copy over their user count. */
2612
2613 DEG_id_tag_update(&grease_pencil_dst->id, ID_RECALC_GEOMETRY);
2614
2615 BKE_id_free(nullptr, grease_pencil_src);
2616}
2617
2618void BKE_grease_pencil_vgroup_name_update(Object *ob, const char *old_name, const char *new_name)
2619{
2620 using namespace blender::bke::greasepencil;
2621 GreasePencil &grease_pencil = *id_cast<GreasePencil *>(ob->data);
2622 for (GreasePencilDrawingBase *base : grease_pencil.drawings()) {
2623 Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(base)->wrap();
2625 for (bDeformGroup &vgroup : curves.vertex_group_names) {
2626 if (STREQ(vgroup.name, old_name)) {
2627 STRNCPY_UTF8(vgroup.name, new_name);
2628 }
2629 }
2630 }
2631}
2632
2633static void grease_pencil_evaluate_modifiers(Depsgraph *depsgraph,
2634 Scene *scene,
2635 Object *object,
2636 bke::GeometrySet &geometry_set)
2637{
2638 /* Modifier evaluation modes. */
2639 const bool use_render = DEG_get_mode(depsgraph) == DAG_EVAL_RENDER;
2640 ModifierMode required_mode = use_render ? eModifierMode_Render : eModifierMode_Realtime;
2641 if (BKE_object_is_in_editmode(object)) {
2642 required_mode |= eModifierMode_Editmode;
2643 }
2644 ModifierApplyFlag apply_flag = use_render ? MOD_APPLY_RENDER : MOD_APPLY_USECACHE;
2645 const ModifierEvalContext mectx = {depsgraph, object, apply_flag};
2646
2648
2649 /* Get effective list of modifiers to execute. Some effects like shape keys
2650 * are added as virtual modifiers before the user created modifiers. */
2651 VirtualModifierData virtualModifierData;
2652 ModifierData *md = BKE_modifiers_get_virtual_modifierlist(object, &virtualModifierData);
2653
2654 /* Evaluate time modifiers.
2655 * The time offset modifier can change what drawings are shown on the current frame. But it
2656 * doesn't affect the drawings data. Modifiers that modify the drawings data are only evaluated
2657 * for the current frame, so we run the time offset modifiers before all the other ones. */
2658 ModifierData *tmd = md;
2659 for (; tmd; tmd = tmd->next) {
2660 const ModifierTypeInfo *mti = BKE_modifier_get_info(tmd->type);
2661
2662 if (!BKE_modifier_is_enabled(scene, tmd, required_mode) ||
2664 {
2665 continue;
2666 }
2667
2668 bke::ScopedModifierTimer modifier_timer{*md};
2669
2670 if (mti->modify_geometry_set != nullptr) {
2671 mti->modify_geometry_set(tmd, &mectx, &geometry_set);
2672 }
2673 }
2674
2675 /* Evaluate drawing modifiers. */
2676 for (; md; md = md->next) {
2678
2679 if (!BKE_modifier_is_enabled(scene, md, required_mode) ||
2681 {
2682 continue;
2683 }
2684
2685 bke::ScopedModifierTimer modifier_timer{*md};
2686
2687 if (mti->modify_geometry_set != nullptr) {
2688 mti->modify_geometry_set(md, &mectx, &geometry_set);
2689 }
2690 }
2691}
2692
2694{
2695 using namespace bke::greasepencil;
2696
2697 const bke::AttributeAccessor layer_attributes = grease_pencil.attributes();
2698
2699 struct LayerDrawingInfo {
2700 Drawing *drawing;
2701 const int layer_index;
2702 };
2703
2704 Set<Drawing *> all_drawings;
2705 Vector<LayerDrawingInfo> drawing_infos;
2706 for (const int layer_i : grease_pencil.layers().index_range()) {
2707 const Layer &layer = grease_pencil.layer(layer_i);
2708 /* Set of owned drawings, ignore drawing references to other data blocks. */
2709 if (Drawing *drawing = grease_pencil.get_eval_drawing(layer)) {
2710 if (all_drawings.add(drawing)) {
2711 drawing_infos.append({drawing, layer_i});
2712 }
2713 }
2714 }
2715
2716 if (layer_attributes.contains("radius_offset")) {
2717 const VArray<float> radius_offsets = *layer_attributes.lookup_or_default<float>(
2718 "radius_offset", bke::AttrDomain::Layer, 0.0f);
2719 threading::parallel_for_each(drawing_infos, [&](LayerDrawingInfo &info) {
2720 if (radius_offsets[info.layer_index] == 0.0f) {
2721 return;
2722 }
2723 MutableSpan<float> radii = info.drawing->radii_for_write();
2724 threading::parallel_for(radii.index_range(), 4096, [&](const IndexRange range) {
2725 for (const int i : range) {
2726 radii[i] += radius_offsets[info.layer_index];
2727 }
2728 });
2729 });
2730 }
2731
2732 if (layer_attributes.contains("tint_color")) {
2733 auto mix_tint = [](const float4 base, const float4 tint) -> float4 {
2734 return base * (1.0 - tint.w) + tint * tint.w;
2735 };
2736 const VArray<ColorGeometry4f> tint_colors =
2737 *layer_attributes.lookup_or_default<ColorGeometry4f>(
2738 "tint_color", bke::AttrDomain::Layer, ColorGeometry4f(0.0f, 0.0f, 0.0f, 0.0f));
2739 threading::parallel_for_each(drawing_infos, [&](LayerDrawingInfo &info) {
2740 if (tint_colors[info.layer_index].a == 0.0f) {
2741 return;
2742 }
2743 MutableSpan<ColorGeometry4f> vertex_colors = info.drawing->vertex_colors_for_write();
2744 threading::parallel_for(vertex_colors.index_range(), 4096, [&](const IndexRange range) {
2745 for (const int i : range) {
2746 vertex_colors[i] = ColorGeometry4f(
2747 mix_tint(float4(vertex_colors[i]), float4(tint_colors[info.layer_index])));
2748 }
2749 });
2750 MutableSpan<ColorGeometry4f> fill_colors = info.drawing->fill_colors_for_write();
2751 threading::parallel_for(fill_colors.index_range(), 4096, [&](const IndexRange range) {
2752 for (const int i : range) {
2753 fill_colors[i] = ColorGeometry4f(
2754 mix_tint(float4(fill_colors[i]), float4(tint_colors[info.layer_index])));
2755 }
2756 });
2757 });
2758 }
2759}
2760
2762{
2763 using namespace blender::bke::greasepencil;
2764
2765 /* Copy the layer cache into an array here, because removing a layer will invalidate the layer
2766 * cache. This will only copy the pointers to the layers, not the layers themselves. */
2767 Array<Layer *> layers = grease_pencil.layers_for_write();
2768
2769 for (const int layer_i : layers.index_range()) {
2770 Layer *layer = layers[layer_i];
2771 /* Store the original index of the layer. */
2772 layer->runtime->orig_layer_index_ = layer_i;
2773 /* When the visibility is animated, the layer should be retained even when it is invisible.
2774 * Changing the visibility through the animation system does NOT create another evaluated copy,
2775 * and thus the layer has to be kept for this future use. */
2776 if (layer->is_visible() || layer->runtime->is_visibility_animated_) {
2777 continue;
2778 }
2779
2780 /* Remove layer from evaluated data. */
2781 grease_pencil.remove_layer(*layer);
2782 }
2783}
2784
2786{
2787 /* Store the frame that this grease pencil is evaluated on. */
2788 grease_pencil->runtime->eval_frame = int(DEG_get_ctime(depsgraph));
2789 /* This will remove layers that aren't visible. */
2791}
2792
2793void BKE_object_eval_grease_pencil(Depsgraph *depsgraph, Scene *scene, Object *object)
2794{
2795 using namespace blender::bke;
2796 /* Free any evaluated data and restore original data. */
2798
2799 GreasePencil *grease_pencil = id_cast<GreasePencil *>(object->data);
2802 /* The layer adjustments for tinting and radii offsets are applied before modifier evaluation.
2803 * This ensures that the evaluated geometry contains the modifications. In the future, it would
2804 * be better to move these into modifiers. For now, these are hardcoded. */
2805 const bke::AttributeAccessor layer_attributes = grease_pencil->attributes();
2806 if (layer_attributes.contains("tint_color") || layer_attributes.contains("radius_offset")) {
2808 }
2809 /* Only add the edit hint component in modes where users can potentially interact with deformed
2810 * drawings. */
2811 if (ELEM(object->mode,
2816 {
2817 GeometryComponentEditData &edit_component =
2819 edit_component.grease_pencil_edit_hints_ = std::make_unique<GreasePencilEditHints>(
2820 *id_cast<const GreasePencil *>(DEG_get_original(object)->data));
2821 }
2822 grease_pencil_evaluate_modifiers(depsgraph, scene, object, geometry_set);
2823
2824 if (geometry_set.has_grease_pencil()) {
2825 /* Output geometry set may be different from the input,
2826 * set the frame again to ensure a correct value. */
2827 geometry_set.get_grease_pencil()->runtime->eval_frame = int(DEG_get_ctime(depsgraph));
2828 }
2829 else {
2830 GreasePencil *empty_grease_pencil = BKE_grease_pencil_new_nomain();
2831 empty_grease_pencil->runtime->eval_frame = int(DEG_get_ctime(depsgraph));
2832 geometry_set.replace_grease_pencil(empty_grease_pencil);
2833 }
2834
2835 /* For now the evaluated data is not const. We could use #get_grease_pencil_for_write, but that
2836 * would result in a copy when it's shared. So for now, we use a const_cast here. */
2837 GreasePencil *grease_pencil_eval = const_cast<GreasePencil *>(geometry_set.get_grease_pencil());
2838
2839 /* Assign evaluated object. */
2840 BKE_object_eval_assign_data(object, &grease_pencil_eval->id, false);
2841 object->runtime->geometry_set_eval = new GeometrySet(std::move(geometry_set));
2842}
2843
2845 GreasePencil *grease_pencil_dst)
2846{
2847 grease_pencil_dst->drawing_array_num = grease_pencil_src->drawing_array_num;
2848 if (grease_pencil_dst->drawing_array_num > 0) {
2849 grease_pencil_dst->drawing_array = MEM_new_array<GreasePencilDrawingBase *>(
2850 grease_pencil_src->drawing_array_num, __func__);
2851 bke::greasepencil::copy_drawing_array(grease_pencil_src->drawings(),
2852 grease_pencil_dst->drawings());
2853 }
2854}
2855
2857
2858/* ------------------------------------------------------------------- */
2862
2864{
2865 for (const GreasePencilDrawingBase *base : grease_pencil.drawings()) {
2866 if (base->type != GP_DRAWING) {
2867 continue;
2868 }
2869 const bke::greasepencil::Drawing &drawing =
2870 reinterpret_cast<const GreasePencilDrawing *>(base)->wrap();
2871 const bke::CurvesGeometry &curves = drawing.strokes();
2872 if (curves.has_curve_with_type(type)) {
2873 return true;
2874 }
2875 }
2876
2877 return false;
2878}
2879
2881{
2882 int total_points = 0;
2883
2884 for (const int layer_i : grease_pencil.layers().index_range()) {
2885 const bke::greasepencil::Layer &layer = grease_pencil.layer(layer_i);
2887 frames.foreach_item(
2888 [&](const bke::greasepencil::FramesMapKeyT /*key*/, const GreasePencilFrame frame) {
2889 const GreasePencilDrawingBase *base = grease_pencil.drawing(frame.drawing_index);
2890 if (base->type != GP_DRAWING) {
2891 return;
2892 }
2893 const bke::greasepencil::Drawing &drawing =
2894 reinterpret_cast<const GreasePencilDrawing *>(base)->wrap();
2895 const bke::CurvesGeometry &curves = drawing.strokes();
2896 total_points += curves.points_num();
2897 });
2898 }
2899
2900 return total_points;
2901}
2902
2904 MutableSpan<float3> all_positions,
2905 MutableSpan<float> all_radii)
2906{
2907 int64_t index = 0;
2908 for (const int layer_i : grease_pencil.layers().index_range()) {
2909 const bke::greasepencil::Layer &layer = grease_pencil.layer(layer_i);
2910 const float4x4 layer_to_object = layer.local_transform();
2912 frames.foreach_item([&](const bke::greasepencil::FramesMapKeyT /*key*/,
2913 const GreasePencilFrame frame) {
2914 const GreasePencilDrawingBase *base = grease_pencil.drawing(frame.drawing_index);
2915 if (base->type != GP_DRAWING) {
2916 return;
2917 }
2918 const bke::greasepencil::Drawing &drawing =
2919 reinterpret_cast<const GreasePencilDrawing *>(base)->wrap();
2920 const bke::CurvesGeometry &curves = drawing.strokes();
2921 const Span<float3> positions = curves.positions();
2922 const VArray<float> radii = drawing.radii();
2923
2924 if (!curves.has_curve_with_type(CURVE_TYPE_BEZIER)) {
2925 for (const int i : curves.points_range()) {
2926 all_positions[index] = math::transform_point(layer_to_object, positions[i]);
2927 all_radii[index] = radii[i];
2928 index++;
2929 }
2930 }
2931 else {
2932 const std::optional<Span<float3>> handle_positions_left = curves.handle_positions_left();
2933 const std::optional<Span<float3>> handle_positions_right = curves.handle_positions_right();
2934 for (const int i : curves.points_range()) {
2935 const int index_pos = index * 3;
2936 all_positions[index_pos] = math::transform_point(layer_to_object,
2937 (*handle_positions_left)[i]);
2938 all_positions[index_pos + 1] = math::transform_point(layer_to_object, positions[i]);
2939 all_positions[index_pos + 2] = math::transform_point(layer_to_object,
2940 (*handle_positions_right)[i]);
2941 all_radii[index] = radii[i];
2942 index++;
2943 }
2944 }
2945 });
2946 }
2947}
2948
2950 Span<float3> all_positions,
2951 Span<float> all_radii)
2952{
2953 int64_t index = 0;
2954 for (const int layer_i : grease_pencil.layers().index_range()) {
2956 const float4x4 layer_to_object = layer.local_transform();
2957 const float4x4 object_to_layer = math::invert(layer_to_object);
2961 if (base->type != GP_DRAWING) {
2962 return;
2963 }
2964 bke::greasepencil::Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(base)->wrap();
2966
2967 MutableSpan<float3> positions = curves.positions_for_write();
2968 MutableSpan<float> radii = drawing.radii_for_write();
2969
2970 if (!curves.has_curve_with_type(CURVE_TYPE_BEZIER)) {
2971 for (const int i : curves.points_range()) {
2972 positions[i] = math::transform_point(object_to_layer, all_positions[index]);
2973 radii[i] = all_radii[index];
2974 index++;
2975 }
2976 }
2977 else {
2978 MutableSpan<float3> handle_positions_left = curves.handle_positions_left_for_write();
2979 MutableSpan<float3> handle_positions_right = curves.handle_positions_right_for_write();
2980 for (const int i : curves.points_range()) {
2981 const int index_pos = index * 3;
2982 handle_positions_left[i] = math::transform_point(object_to_layer,
2983 all_positions[index_pos]);
2984 positions[i] = math::transform_point(object_to_layer, all_positions[index_pos + 1]);
2985 handle_positions_right[i] = math::transform_point(object_to_layer,
2986 all_positions[index_pos + 2]);
2987 radii[i] = all_radii[index];
2988 index++;
2989 }
2990 }
2991
2992 curves.tag_radii_changed();
2993 drawing.tag_positions_changed();
2994 });
2995 }
2996}
2997
2999 Span<float3> all_positions,
3000 Span<float> all_radii,
3001 const float4x4 &mat)
3002{
3003 const float scalef = mat4_to_scale(mat.ptr());
3004 int64_t index = 0;
3005 for (const int layer_i : grease_pencil.layers().index_range()) {
3007 const float4x4 layer_to_object = layer.local_transform();
3008 const float4x4 object_to_layer = math::invert(layer_to_object);
3012 if (base->type != GP_DRAWING) {
3013 return;
3014 }
3015 bke::greasepencil::Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(base)->wrap();
3017
3018 MutableSpan<float3> positions = curves.positions_for_write();
3019 MutableSpan<float> radii = drawing.radii_for_write();
3020
3021 if (!curves.has_curve_with_type(CURVE_TYPE_BEZIER)) {
3022 for (const int i : curves.points_range()) {
3023 positions[i] = math::transform_point(object_to_layer * mat, all_positions[index]);
3024 radii[i] = all_radii[index] * scalef;
3025 index++;
3026 }
3027 }
3028 else {
3029 MutableSpan<float3> handle_positions_left = curves.handle_positions_left_for_write();
3030 MutableSpan<float3> handle_positions_right = curves.handle_positions_right_for_write();
3031 for (const int i : curves.points_range()) {
3032 const int index_pos = index * 3;
3033 handle_positions_left[i] = math::transform_point(object_to_layer * mat,
3034 all_positions[index_pos]);
3035 positions[i] = math::transform_point(object_to_layer * mat,
3036 all_positions[index_pos + 1]);
3037 handle_positions_right[i] = math::transform_point(object_to_layer * mat,
3038 all_positions[index_pos + 2]);
3039 radii[i] = all_radii[index] * scalef;
3040 index++;
3041 }
3042 }
3043
3044 curves.tag_radii_changed();
3045 drawing.tag_positions_changed();
3046 });
3047 }
3048}
3049
3051
3052/* ------------------------------------------------------------------- */
3055
3057{
3058 short *totcol = BKE_object_material_len_p(ob);
3059 Material *read_ma = nullptr;
3060 for (short i = 0; i < *totcol; i++) {
3061 read_ma = BKE_object_material_get(ob, i + 1);
3062 if (STREQ(name, read_ma->id.name + 2)) {
3063 return i;
3064 }
3065 }
3066
3067 return -1;
3068}
3069
3071 Object *ob,
3072 const char *name,
3073 int *r_index)
3074{
3075 Material *ma = BKE_gpencil_material_add(bmain, name);
3076 id_us_min(&ma->id); /* no users yet */
3077
3080
3081 if (r_index) {
3082 *r_index = ob->actcol - 1;
3083 }
3084 return ma;
3085}
3086
3088{
3089 if (brush && brush->gpencil_settings &&
3090 (brush->gpencil_settings->flag & GP_BRUSH_MATERIAL_PINNED))
3091 {
3092 return brush->gpencil_settings->material;
3093 }
3094
3095 return BKE_object_material_get(ob, ob->actcol);
3096}
3097
3099 Object *ob,
3100 const char *name,
3101 int *r_index)
3102{
3104 if (index != -1) {
3105 *r_index = index;
3106 return BKE_object_material_get(ob, index + 1);
3107 }
3108 return BKE_grease_pencil_object_material_new(bmain, ob, name, r_index);
3109}
3110
3112 Object *ob,
3113 Brush *brush)
3114{
3115 Material *ma = (brush->gpencil_settings) ? brush->gpencil_settings->material : nullptr;
3116
3117 if (ma && BKE_object_material_index_get(ob, ma) < 0) {
3118 /* Ensure we assign a local datablock if this is an editable asset. */
3119 ma = reinterpret_cast<Material *>(bke::asset_edit_id_ensure_local(*bmain, ma->id));
3120 }
3121
3122 /* check if the material is already on object material slots and add it if missing */
3123 if (ma && BKE_object_material_index_get(ob, ma) < 0) {
3124 /* The object's active material is what's used for the unpinned material. Do not touch it
3125 * while using a pinned material. */
3126 const bool change_active_material = false;
3127
3128 BKE_object_material_slot_add(bmain, ob, change_active_material);
3130 }
3131
3132 return ma;
3133}
3134
3136 Object *ob,
3137 Brush *brush)
3138{
3139 /* Use pinned material. */
3140 if (brush && brush->gpencil_settings &&
3141 (brush->gpencil_settings->flag & GP_BRUSH_MATERIAL_PINNED))
3142 {
3144 return ma;
3145 }
3146
3147 /* It is easier to just unpin a null material, instead of setting a new one. */
3148 brush->gpencil_settings->flag &= ~GP_BRUSH_MATERIAL_PINNED;
3149 }
3150
3151 /* Use the active material. */
3152 if (Material *ma = BKE_object_material_get(ob, ob->actcol)) {
3153 return ma;
3154 }
3155
3156 /* Fall back to default material. */
3157 /* XXX FIXME This is critical abuse of the 'default material' feature, these IDs should never be
3158 * used/returned as 'regular' data. */
3160}
3161
3163 Object *ob,
3164 Brush *brush)
3165{
3166 Material *material_alt = (brush->gpencil_settings) ? brush->gpencil_settings->material_alt :
3167 nullptr;
3168 if (material_alt) {
3169 material_alt = reinterpret_cast<Material *>(
3170 bke::asset_edit_id_find_local(*bmain, material_alt->id));
3171 if (material_alt && BKE_object_material_slot_find_index(ob, material_alt) != -1) {
3172 return material_alt;
3173 }
3174 }
3175
3177}
3178
3180{
3181 using namespace blender::bke;
3182
3183 for (GreasePencilDrawingBase *base : grease_pencil->drawings()) {
3184 if (base->type != GP_DRAWING) {
3185 continue;
3186 }
3187 greasepencil::Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(base)->wrap();
3189 SpanAttributeWriter<int> material_indices = attributes.lookup_for_write_span<int>(
3190 "material_index");
3191 if (!material_indices) {
3192 continue;
3193 }
3194 BLI_assert(material_indices.domain == AttrDomain::Curve);
3195 for (const int i : material_indices.span.index_range()) {
3196 BLI_assert(IndexRange(totcol).contains(remap[material_indices.span[i]]));
3197 UNUSED_VARS_NDEBUG(totcol);
3198 material_indices.span[i] = remap[material_indices.span[i]];
3199 }
3200 material_indices.finish();
3201 }
3202}
3203
3205{
3206 using namespace blender::bke;
3207
3208 for (GreasePencilDrawingBase *base : grease_pencil->drawings()) {
3209 if (base->type != GP_DRAWING) {
3210 continue;
3211 }
3212 greasepencil::Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(base)->wrap();
3214 SpanAttributeWriter<int> material_indices = attributes.lookup_for_write_span<int>(
3215 "material_index");
3216 if (!material_indices) {
3217 continue;
3218 }
3219 BLI_assert(material_indices.domain == AttrDomain::Curve);
3220 for (const int i : material_indices.span.index_range()) {
3221 if (material_indices.span[i] > 0 && material_indices.span[i] >= index) {
3222 material_indices.span[i]--;
3223 }
3224 }
3225 material_indices.finish();
3226 }
3227}
3228
3230{
3231 using namespace blender::bke;
3232
3233 for (GreasePencilDrawingBase *base : grease_pencil->drawings()) {
3234 if (base->type != GP_DRAWING) {
3235 continue;
3236 }
3237 greasepencil::Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(base)->wrap();
3238 AttributeAccessor attributes = drawing.strokes().attributes();
3239 const VArraySpan<int> material_indices = *attributes.lookup_or_default<int>(
3240 "material_index", AttrDomain::Curve, 0);
3241
3242 if (material_indices.contains(index)) {
3243 return true;
3244 }
3245 }
3246 return false;
3247}
3248
3250{
3252 BLI_assert(brush->gpencil_settings);
3253 if (brush->gpencil_settings->material != ma) {
3254 if (brush->gpencil_settings->material) {
3255 id_us_min(&brush->gpencil_settings->material->id);
3256 }
3257 if (ma) {
3258 id_us_plus(&ma->id);
3259 }
3260 brush->gpencil_settings->material = ma;
3262 }
3263}
3264
3266
3267/* ------------------------------------------------------------------- */
3270
3272{
3273 const char *hexcol[] = {
3274 "FFFFFF", "F2F2F2", "E6E6E6", "D9D9D9", "CCCCCC", "BFBFBF", "B2B2B2", "A6A6A6", "999999",
3275 "8C8C8C", "808080", "737373", "666666", "595959", "4C4C4C", "404040", "333333", "262626",
3276 "1A1A1A", "000000", "F2FC24", "FFEA00", "FEA711", "FE8B68", "FB3B02", "FE3521", "D00000",
3277 "A81F3D", "780422", "2B0000", "F1E2C5", "FEE4B3", "FEDABB", "FEC28E", "D88F57", "BD6340",
3278 "A2402B", "63352D", "6B2833", "34120C", "E7CB8F", "D1B38B", "C1B17F", "D7980B", "FFB100",
3279 "FE8B00", "FF6A00", "B74100", "5F3E1D", "3B2300", "FECADA", "FE65CB", "FE1392", "DD3062",
3280 "C04A6D", "891688", "4D2689", "441521", "2C1139", "241422", "FFFF7D", "FFFF00", "FF7F00",
3281 "FF7D7D", "FF7DFF", "FF00FE", "FF007F", "FF0000", "7F0000", "0A0A00", "F6FDFF", "E9F7FF",
3282 "CFE6FE", "AAC7FE", "77B3FE", "1E74FD", "0046AA", "2F4476", "003052", "0E0E25", "EEF5F0",
3283 "D6E5DE", "ACD8B9", "6CADC6", "42A9AF", "007F7F", "49675C", "2E4E4E", "1D3239", "0F1C21",
3284 "D8FFF4", "B8F4F5", "AECCB5", "76C578", "358757", "409B68", "468768", "1F512B", "2A3C37",
3285 "122E1D", "EFFFC9", "E6F385", "BCF51C", "D4DC18", "82D322", "5C7F00", "59932B", "297F00",
3286 "004320", "1C3322", "00FF7F", "00FF00", "7DFF7D", "7DFFFF", "00FFFF", "7D7DFF", "7F00FF",
3287 "0000FF", "3F007F", "00007F"};
3288
3289 ToolSettings *ts = scene->toolsettings;
3290 if (ts->gp_paint->paint.palette != nullptr) {
3291 return;
3292 }
3293
3294 /* Try to find the default palette. */
3295 const char *palette_id = "Palette";
3296 Palette *palette = static_cast<Palette *>(
3297 BLI_findstring(&bmain->palettes, palette_id, offsetof(ID, name) + 2));
3298
3299 if (palette == nullptr) {
3300 /* Fall back to the first palette. */
3301 palette = bmain->palettes.first();
3302 }
3303
3304 if (palette == nullptr) {
3305 /* Fall back to creating a palette. */
3306 palette = BKE_palette_add(bmain, palette_id);
3307 id_us_min(&palette->id);
3308
3309 /* Create Colors. */
3310 for (int i = 0; i < ARRAY_SIZE(hexcol); i++) {
3311 PaletteColor *palcol = BKE_palette_color_add(palette);
3312 hex_to_rgb(hexcol[i], palcol->color, palcol->color + 1, palcol->color + 2);
3314 }
3315 }
3316
3317 BLI_assert(palette != nullptr);
3318 BKE_paint_palette_set(&ts->gp_paint->paint, palette);
3320}
3321
3323
3324/* ------------------------------------------------------------------- */
3327
3330{
3331 for (const GreasePencilDrawingBase *base : grease_pencil->drawings()) {
3332 if (base->type == GP_DRAWING_REFERENCE) {
3333 const auto *reference = reinterpret_cast<const GreasePencilDrawingReference *>(base);
3334 if (id_reference == reference->id_reference) {
3335 return true;
3336 }
3337
3338 if (grease_pencil_references_cyclic_check_internal(id_reference, reference->id_reference)) {
3339 return true;
3340 }
3341 }
3342 }
3343 return false;
3344}
3345
3351
3353
3354/* ------------------------------------------------------------------- */
3357
3359 int mode) = nullptr;
3361
3363{
3364 if (grease_pencil->runtime && grease_pencil->runtime->batch_cache) {
3366 }
3367}
3368
3375
3377
3378/* ------------------------------------------------------------------- */
3381
3382template<typename T> static void grow_array(T **array, int *num, const int add_num)
3383{
3384 BLI_assert(add_num > 0);
3385 const int new_array_num = *num + add_num;
3386 T *new_array = MEM_new_array_zeroed<T>(new_array_num, __func__);
3387
3388 uninitialized_relocate_n(*array, *num, new_array);
3389 if (*array != nullptr) {
3390 MEM_delete(*array);
3391 }
3392
3393 *array = new_array;
3394 *num = new_array_num;
3395}
3396template<typename T> static void shrink_array(T **array, int *num, const int shrink_num)
3397{
3398 BLI_assert(shrink_num > 0);
3399 const int new_array_num = *num - shrink_num;
3400 if (new_array_num == 0) {
3401 MEM_delete(*array);
3402 *array = nullptr;
3403 *num = 0;
3404 return;
3405 }
3406
3407 T *new_array = MEM_new_array_zeroed<T>(new_array_num, __func__);
3408
3409 uninitialized_move_n(*array, new_array_num, new_array);
3410 MEM_delete(*array);
3411
3412 *array = new_array;
3413 *num = new_array_num;
3414}
3415
3416Span<const GreasePencilDrawingBase *> GreasePencil::drawings() const
3417{
3418 return Span<GreasePencilDrawingBase *>{this->drawing_array, this->drawing_array_num};
3419}
3420
3421MutableSpan<GreasePencilDrawingBase *> GreasePencil::drawings()
3422{
3423 return MutableSpan<GreasePencilDrawingBase *>{this->drawing_array, this->drawing_array_num};
3424}
3425
3426static void delete_drawing(GreasePencilDrawingBase *drawing_base)
3427{
3428 /* Unknown types from corrupt files, only the base struct was read. */
3429 if (!ELEM(drawing_base->type, GP_DRAWING, GP_DRAWING_REFERENCE)) {
3430 MEM_delete(drawing_base);
3431 return;
3432 }
3433
3434 switch (GreasePencilDrawingType(drawing_base->type)) {
3435 case GP_DRAWING: {
3436 GreasePencilDrawing *drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base);
3437 MEM_delete(&drawing->wrap());
3438 break;
3439 }
3440 case GP_DRAWING_REFERENCE: {
3441 GreasePencilDrawingReference *drawing_reference =
3442 reinterpret_cast<GreasePencilDrawingReference *>(drawing_base);
3443 MEM_delete(&drawing_reference->wrap());
3444 break;
3445 }
3446 }
3447}
3448
3449void GreasePencil::resize_drawings(const int new_num)
3450{
3451 BLI_assert(new_num >= 0);
3452
3453 const int prev_num = int(this->drawings().size());
3454 if (new_num == prev_num) {
3455 return;
3456 }
3457 if (new_num > prev_num) {
3458 const int add_num = new_num - prev_num;
3459 grow_array<GreasePencilDrawingBase *>(&this->drawing_array, &this->drawing_array_num, add_num);
3460 }
3461 else { /* if (new_num < prev_num) */
3462 const int shrink_num = prev_num - new_num;
3463 MutableSpan<GreasePencilDrawingBase *> old_drawings = this->drawings().drop_front(new_num);
3464 for (const int64_t i : old_drawings.index_range()) {
3465 if (GreasePencilDrawingBase *drawing_base = old_drawings[i]) {
3466 delete_drawing(drawing_base);
3467 }
3468 }
3470 &this->drawing_array, &this->drawing_array_num, shrink_num);
3471 }
3472}
3473
3474void GreasePencil::add_empty_drawings(const int add_num)
3475{
3476 BLI_assert(add_num > 0);
3477 const int prev_num = this->drawings().size();
3478 grow_array<GreasePencilDrawingBase *>(&this->drawing_array, &this->drawing_array_num, add_num);
3479 MutableSpan<GreasePencilDrawingBase *> new_drawings = this->drawings().drop_front(prev_num);
3480 for (const int i : new_drawings.index_range()) {
3481 new_drawings[i] = reinterpret_cast<GreasePencilDrawingBase *>(
3482 MEM_new<bke::greasepencil::Drawing>(__func__));
3483 }
3484}
3485
3486void GreasePencil::add_duplicate_drawings(const int duplicate_num,
3487 const bke::greasepencil::Drawing &drawing)
3488{
3489 BLI_assert(duplicate_num > 0);
3490 const int prev_num = this->drawings().size();
3492 &this->drawing_array, &this->drawing_array_num, duplicate_num);
3493 MutableSpan<GreasePencilDrawingBase *> new_drawings = this->drawings().drop_front(prev_num);
3494 for (const int i : new_drawings.index_range()) {
3495 new_drawings[i] = reinterpret_cast<GreasePencilDrawingBase *>(
3496 MEM_new<bke::greasepencil::Drawing>(__func__, drawing));
3497 }
3498}
3499
3500bke::greasepencil::Drawing *GreasePencil::insert_frame(bke::greasepencil::Layer &layer,
3501 const int frame_number,
3502 const int duration,
3503 const eBezTriple_KeyframeType keytype)
3504{
3505 GreasePencilFrame *frame = layer.add_frame(frame_number, duration);
3506 if (frame == nullptr) {
3507 return nullptr;
3508 }
3509 this->add_empty_drawings(1);
3510 frame->drawing_index = this->drawings().index_range().last();
3511 frame->type = int8_t(keytype);
3512
3513 GreasePencilDrawingBase *drawing_base = this->drawings().last();
3514 BLI_assert(drawing_base->type == GP_DRAWING);
3515 GreasePencilDrawing *drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base);
3516 return &drawing->wrap();
3517}
3518
3519void GreasePencil::insert_frames(Span<bke::greasepencil::Layer *> layers,
3520 const int frame_number,
3521 const int duration,
3522 const eBezTriple_KeyframeType keytype)
3523{
3524 if (layers.is_empty()) {
3525 return;
3526 }
3527 Vector<GreasePencilFrame *> frames;
3528 frames.reserve(layers.size());
3529 for (bke::greasepencil::Layer *layer : layers) {
3530 BLI_assert(layer != nullptr);
3531 GreasePencilFrame *frame = layer->add_frame(frame_number, duration);
3532 if (frame != nullptr) {
3533 frames.append(frame);
3534 }
3535 }
3536
3537 if (frames.is_empty()) {
3538 return;
3539 }
3540
3541 this->add_empty_drawings(frames.size());
3542 const IndexRange new_drawings = this->drawings().index_range().take_back(frames.size());
3543 for (const int frame_i : frames.index_range()) {
3544 GreasePencilFrame *frame = frames[frame_i];
3545 frame->drawing_index = new_drawings[frame_i];
3546 frame->type = int8_t(keytype);
3547 }
3548}
3549
3550bool GreasePencil::insert_duplicate_frame(bke::greasepencil::Layer &layer,
3551 const int src_frame_number,
3552 const int dst_frame_number,
3553 const bool do_instance)
3554{
3555 using namespace blender::bke::greasepencil;
3556
3557 if (!layer.frames().contains(src_frame_number)) {
3558 return false;
3559 }
3560
3561 if (layer.is_locked()) {
3562 return false;
3563 }
3564 const GreasePencilFrame src_frame = layer.frames().lookup(src_frame_number);
3565
3566 /* Create the new frame structure, with the same duration.
3567 * If we want to make an instance of the source frame, the drawing index gets copied from the
3568 * source frame. Otherwise, we set the drawing index to the size of the drawings array, since we
3569 * are going to add a new drawing copied from the source drawing. */
3570 const int duration = 0 /* layer.get_frame_duration_at(src_frame_number) */;
3571 GreasePencilFrame *dst_frame = layer.add_frame(dst_frame_number, duration);
3572 if (dst_frame == nullptr) {
3573 return false;
3574 }
3575 dst_frame->drawing_index = do_instance ? src_frame.drawing_index : int(this->drawings().size());
3576 dst_frame->type = src_frame.type;
3577
3578 const GreasePencilDrawingBase *src_drawing_base = this->drawing(src_frame.drawing_index);
3579 switch (src_drawing_base->type) {
3580 case GP_DRAWING: {
3581 const Drawing &src_drawing =
3582 reinterpret_cast<const GreasePencilDrawing *>(src_drawing_base)->wrap();
3583 if (do_instance) {
3584 /* Adds the duplicate frame as a new instance of the same drawing. We thus increase the
3585 * user count of the corresponding drawing. */
3586 src_drawing.add_user();
3587 }
3588 else {
3589 /* Create a copy of the drawing, and add it at the end of the drawings array.
3590 * Note that the frame already points to this new drawing, as the drawing index was set to
3591 * `int(this->drawings().size())`. */
3592 this->add_duplicate_drawings(1, src_drawing);
3593 }
3594 break;
3595 }
3597 /* TODO: Duplicate drawing references is not yet implemented.
3598 * For now, just remove the frame that we inserted. */
3599 layer.remove_frame(dst_frame_number);
3600 return false;
3601 }
3602#ifndef NDEBUG
3603 this->validate_drawing_user_counts();
3604#endif
3605 return true;
3606}
3607
3608bool GreasePencil::remove_frames(bke::greasepencil::Layer &layer, Span<int> frame_numbers)
3609{
3610 using namespace blender::bke::greasepencil;
3611 bool removed_any_drawing_user = false;
3612 for (const int frame_number : frame_numbers) {
3613 if (!layer.frames().contains(frame_number)) {
3614 continue;
3615 }
3616 const GreasePencilFrame frame_to_remove = layer.frames().lookup(frame_number);
3617 const int64_t drawing_index_to_remove = frame_to_remove.drawing_index;
3618 if (!layer.remove_frame(frame_number)) {
3619 /* If removing the frame was not successful, continue. */
3620 continue;
3621 }
3622 if (frame_to_remove.is_end()) {
3623 /* End frames don't reference a drawing, continue. */
3624 continue;
3625 }
3626 GreasePencilDrawingBase *drawing_base = this->drawing(drawing_index_to_remove);
3627 if (drawing_base->type != GP_DRAWING) {
3628 /* If the drawing is referenced from another object, we don't track it's users because we
3629 * cannot delete drawings from another object. */
3630 continue;
3631 }
3632 Drawing &drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base)->wrap();
3633 drawing.remove_user();
3634 removed_any_drawing_user = true;
3635 }
3636 if (removed_any_drawing_user) {
3637 this->remove_drawings_with_no_users();
3638 return true;
3639 }
3640#ifndef NDEBUG
3641 this->validate_drawing_user_counts();
3642#endif
3643 return false;
3644}
3645
3646void GreasePencil::copy_frames_from_layer(bke::greasepencil::Layer &dst_layer,
3647 const GreasePencil &src_grease_pencil,
3648 const bke::greasepencil::Layer &src_layer,
3649 const std::optional<int> frame_select)
3650{
3651 const Span<const GreasePencilDrawingBase *> src_drawings = src_grease_pencil.drawings();
3652 Array<int> drawing_index_map(src_grease_pencil.drawing_array_num, -1);
3653
3654 for (auto [frame_number, src_frame] : src_layer.frames().items()) {
3655 if (frame_select && *frame_select != frame_number) {
3656 continue;
3657 }
3658
3659 const int src_drawing_index = src_frame.drawing_index;
3660 int dst_drawing_index = drawing_index_map[src_drawing_index];
3661 if (dst_drawing_index < 0) {
3662 switch (src_drawings[src_drawing_index]->type) {
3663 case GP_DRAWING: {
3664 const bke::greasepencil::Drawing &src_drawing =
3665 reinterpret_cast<const GreasePencilDrawing *>(src_drawings[src_drawing_index])
3666 ->wrap();
3667 this->add_duplicate_drawings(1, src_drawing);
3668 break;
3669 }
3671 /* Dummy drawing to keep frame reference valid. */
3672 this->add_empty_drawings(1);
3673 break;
3674 }
3675 dst_drawing_index = this->drawings().size() - 1;
3676 drawing_index_map[src_drawing_index] = dst_drawing_index;
3677 }
3678 BLI_assert(this->drawings().index_range().contains(dst_drawing_index));
3679
3680 GreasePencilFrame *dst_frame = dst_layer.add_frame(frame_number);
3681 dst_frame->flag = src_frame.flag;
3682 dst_frame->drawing_index = dst_drawing_index;
3683 }
3684}
3685
3686void GreasePencil::add_layers_with_empty_drawings_for_eval(const int num)
3687{
3688 using namespace blender::bke::greasepencil;
3689 const int old_drawings_num = this->drawing_array_num;
3690 const int old_layers_num = this->layers().size();
3691 this->add_empty_drawings(num);
3692 this->add_layers_for_eval(num);
3693 threading::parallel_for(IndexRange(num), 256, [&](const IndexRange range) {
3694 for (const int i : range) {
3695 const int new_drawing_i = old_drawings_num + i;
3696 const int new_layer_i = old_layers_num + i;
3697 Layer &layer = this->layer(new_layer_i);
3698 GreasePencilFrame *frame = layer.add_frame(this->runtime->eval_frame);
3699 BLI_assert(frame);
3700 frame->drawing_index = new_drawing_i;
3701 }
3702 });
3703}
3704
3705void GreasePencil::remove_drawings_with_no_users()
3706{
3707 using namespace blender::bke::greasepencil;
3708
3709 /* Compress the drawings array by finding unused drawings.
3710 * In every step two indices are found:
3711 * - The next unused drawing from the start
3712 * - The last used drawing from the end
3713 * These two drawings are then swapped. Rinse and repeat until both iterators meet somewhere in
3714 * the middle. At this point the drawings array is fully compressed.
3715 * Then the drawing indices in frame data are remapped. */
3716
3717 const MutableSpan<GreasePencilDrawingBase *> drawings = this->drawings();
3718 if (drawings.is_empty()) {
3719 return;
3720 }
3721
3722 auto is_drawing_used = [&](const int drawing_index) {
3723 GreasePencilDrawingBase *drawing_base = drawings[drawing_index];
3724 /* NOTE: GreasePencilDrawingReference does not have a user count currently, but should
3725 * eventually be counted like GreasePencilDrawing. */
3726 if (drawing_base->type != GP_DRAWING) {
3727 return false;
3728 }
3729 GreasePencilDrawing *drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base);
3730 return drawing->wrap().has_users() || drawing->runtime->fake_user;
3731 };
3732
3733 /* Index map to remap drawing indices in frame data.
3734 * Index -1 indicates that the drawing has not been moved. */
3735 constexpr const int unchanged_index = -1;
3736 Array<int> drawing_index_map(drawings.size(), unchanged_index);
3737
3738 int first_unused_drawing = -1;
3739 int last_used_drawing = drawings.size() - 1;
3740 /* Advance head and tail iterators to the next unused/used drawing respectively.
3741 * Returns true if an index pair was found that needs to be swapped. */
3742 auto find_next_swap_index = [&]() -> bool {
3743 do {
3744 ++first_unused_drawing;
3745 } while (first_unused_drawing <= last_used_drawing && is_drawing_used(first_unused_drawing));
3746 while (last_used_drawing >= 0 && !is_drawing_used(last_used_drawing)) {
3747 --last_used_drawing;
3748 }
3749
3750 return first_unused_drawing < last_used_drawing;
3751 };
3752
3753 while (find_next_swap_index()) {
3754 /* Found two valid iterators, now swap drawings. */
3755 std::swap(drawings[first_unused_drawing], drawings[last_used_drawing]);
3756 drawing_index_map[last_used_drawing] = first_unused_drawing;
3757 }
3758
3759 /* `last_used_drawing` is expected to be exactly the item before the first unused drawing, once
3760 * the loop above is fully done and all unused drawings are supposed to be at the end of the
3761 * array. */
3762 BLI_assert(last_used_drawing == first_unused_drawing - 1);
3763#ifndef NDEBUG
3764 for (const int i : drawings.index_range()) {
3765 if (i < first_unused_drawing) {
3766 BLI_assert(is_drawing_used(i));
3767 }
3768 else {
3769 BLI_assert(!is_drawing_used(i));
3770 }
3771 }
3772#endif
3773
3774 /* Tail range of unused drawings that can be removed. */
3775 const IndexRange drawings_to_remove = (first_unused_drawing > 0) ?
3776 drawings.index_range().drop_front(
3777 first_unused_drawing) :
3778 drawings.index_range();
3779 if (drawings_to_remove.is_empty()) {
3780 return;
3781 }
3782
3783 /* Free the unused drawings. */
3784 for (const int i : drawings_to_remove) {
3785 GreasePencilDrawingBase *unused_drawing_base = drawings[i];
3786 switch (unused_drawing_base->type) {
3787 case GP_DRAWING: {
3788 auto *unused_drawing = reinterpret_cast<GreasePencilDrawing *>(unused_drawing_base);
3789 MEM_delete(&unused_drawing->wrap());
3790 break;
3791 }
3792 case GP_DRAWING_REFERENCE: {
3793 auto *unused_drawing_ref = reinterpret_cast<GreasePencilDrawingReference *>(
3794 unused_drawing_base);
3795 MEM_delete(&unused_drawing_ref->wrap());
3796 break;
3797 }
3798 }
3799 }
3801 &this->drawing_array, &this->drawing_array_num, drawings_to_remove.size());
3802
3803 /* Remap drawing indices in frame data. */
3804 for (Layer *layer : this->layers_for_write()) {
3805 for (auto [key, value] : layer->frames_for_write().items()) {
3806 const int new_drawing_index = drawing_index_map[value.drawing_index];
3807 if (new_drawing_index != unchanged_index) {
3808 value.drawing_index = new_drawing_index;
3809 layer->tag_frames_map_changed();
3810 }
3811 }
3812 }
3813
3814#ifndef NDEBUG
3815 this->validate_drawing_user_counts();
3816#endif
3817}
3818
3819void GreasePencil::update_drawing_users_for_layer(const bke::greasepencil::Layer &layer)
3820{
3821 for (const auto &[key, value] : layer.frames().items()) {
3822 BLI_assert(this->drawings().index_range().contains(value.drawing_index));
3823 GreasePencilDrawingBase *drawing_base = this->drawing(value.drawing_index);
3824 if (drawing_base->type != GP_DRAWING) {
3825 continue;
3826 }
3827 bke::greasepencil::Drawing &drawing =
3828 reinterpret_cast<GreasePencilDrawing *>(drawing_base)->wrap();
3829 if (!drawing.has_users()) {
3830 drawing.add_user();
3831 }
3832 }
3833
3834#ifndef NDEBUG
3835 this->validate_drawing_user_counts();
3836#endif
3837}
3838
3839void GreasePencil::move_frames(bke::greasepencil::Layer &layer,
3840 const Map<int, int> &frame_number_destinations)
3841{
3842 this->move_duplicate_frames(layer, frame_number_destinations, Map<int, GreasePencilFrame>());
3843}
3844
3845void GreasePencil::move_duplicate_frames(bke::greasepencil::Layer &layer,
3846 const Map<int, int> &frame_number_destinations,
3847 const Map<int, GreasePencilFrame> &duplicate_frames)
3848{
3849 Map<int, GreasePencilFrame> layer_frames_copy = layer.frames();
3850
3851 /* Copy frames durations. */
3852 Map<int, int> src_layer_frames_durations;
3853 for (const auto [frame_number, frame] : layer.frames().items()) {
3854 src_layer_frames_durations.add(frame_number, layer.get_frame_duration_at(frame_number));
3855 }
3856
3857 /* Remove original frames for duplicates before inserting any frames.
3858 * This has to be done early to avoid removing frames that may be inserted
3859 * in place of the source frames. */
3860 for (const auto src_frame_number : frame_number_destinations.keys()) {
3861 if (!duplicate_frames.contains(src_frame_number)) {
3862 /* User count not decremented here, the same frame is inserted again later. */
3863 layer.remove_frame(src_frame_number);
3864 }
3865 }
3866
3867 auto get_source_frame = [&](const int frame_number) -> const GreasePencilFrame * {
3868 if (const GreasePencilFrame *ptr = duplicate_frames.lookup_ptr(frame_number)) {
3869 return ptr;
3870 }
3871 return layer_frames_copy.lookup_ptr(frame_number);
3872 };
3873
3874 for (const auto [src_frame_number, dst_frame_number] : frame_number_destinations.items()) {
3875 const GreasePencilFrame *src_frame = get_source_frame(src_frame_number);
3876 if (!src_frame) {
3877 continue;
3878 }
3879 const int duration = 0 /* src_layer_frames_durations.lookup_default(src_frame_number, 0) */;
3880
3881 /* Add and overwrite the frame at the destination number. */
3882 if (layer.frames().contains(dst_frame_number)) {
3883 GreasePencilFrame frame_to_overwrite = layer.frames().lookup(dst_frame_number);
3884 GreasePencilDrawingBase *drawing_base = this->drawing(frame_to_overwrite.drawing_index);
3885 if (drawing_base->type == GP_DRAWING) {
3886 reinterpret_cast<GreasePencilDrawing *>(drawing_base)->wrap().remove_user();
3887 }
3888 layer.remove_frame(dst_frame_number);
3889 }
3890 GreasePencilFrame *frame = layer.add_frame(dst_frame_number, duration);
3891 *frame = *src_frame;
3892 }
3893
3894 /* Remove drawings if they no longer have users. */
3895 this->remove_drawings_with_no_users();
3896}
3897
3898const bke::greasepencil::Drawing *GreasePencil::get_drawing_at(
3899 const bke::greasepencil::Layer &layer, const int frame_number) const
3900{
3901 if (this->drawings().is_empty()) {
3902 return nullptr;
3903 }
3904 const int drawing_index = layer.drawing_index_at(frame_number);
3905 if (drawing_index == -1) {
3906 /* No drawing found. */
3907 return nullptr;
3908 }
3909 const GreasePencilDrawingBase *drawing_base = this->drawing(drawing_index);
3910 if (drawing_base->type != GP_DRAWING) {
3911 /* TODO: Get reference drawing. */
3912 return nullptr;
3913 }
3914 const GreasePencilDrawing *drawing = reinterpret_cast<const GreasePencilDrawing *>(drawing_base);
3915 return &drawing->wrap();
3916}
3917
3918bke::greasepencil::Drawing *GreasePencil::get_drawing_at(const bke::greasepencil::Layer &layer,
3919 const int frame_number)
3920{
3921 if (this->drawings().is_empty()) {
3922 return nullptr;
3923 }
3924 const int drawing_index = layer.drawing_index_at(frame_number);
3925 if (drawing_index == -1) {
3926 /* No drawing found. */
3927 return nullptr;
3928 }
3929 GreasePencilDrawingBase *drawing_base = this->drawing(drawing_index);
3930 if (drawing_base->type != GP_DRAWING) {
3931 /* TODO: Get reference drawing. */
3932 return nullptr;
3933 }
3934 GreasePencilDrawing *drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base);
3935 return &drawing->wrap();
3936}
3937
3938bke::greasepencil::Drawing *GreasePencil::get_editable_drawing_at(
3939 const bke::greasepencil::Layer &layer, const int frame_number)
3940{
3941 if (!layer.is_editable()) {
3942 return nullptr;
3943 }
3944 if (this->drawings().is_empty()) {
3945 return nullptr;
3946 }
3947 const int drawing_index = layer.drawing_index_at(frame_number);
3948 if (drawing_index == -1) {
3949 /* No drawing found. */
3950 return nullptr;
3951 }
3952 GreasePencilDrawingBase *drawing_base = this->drawing(drawing_index);
3953 if (drawing_base->type != GP_DRAWING) {
3954 /* Drawing references are not editable. */
3955 return nullptr;
3956 }
3957 GreasePencilDrawing *drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base);
3958 return &drawing->wrap();
3959}
3960
3961const bke::greasepencil::Drawing *GreasePencil::get_eval_drawing(
3962 const bke::greasepencil::Layer &layer) const
3963{
3964 return this->get_drawing_at(layer, this->runtime->eval_frame);
3965}
3966
3967bke::greasepencil::Drawing *GreasePencil::get_eval_drawing(const bke::greasepencil::Layer &layer)
3968{
3969 return this->get_drawing_at(layer, this->runtime->eval_frame);
3970}
3971
3972std::optional<Bounds<float3>> GreasePencil::bounds_min_max(const int frame,
3973 const bool use_radius) const
3974{
3975 std::optional<Bounds<float3>> bounds;
3976 const Span<const bke::greasepencil::Layer *> layers = this->layers();
3977 for (const int layer_i : layers.index_range()) {
3978 const bke::greasepencil::Layer &layer = *layers[layer_i];
3979 const float4x4 layer_to_object = layer.local_transform();
3980 if (!layer.is_visible()) {
3981 continue;
3982 }
3983 const bke::greasepencil::Drawing *drawing = this->get_drawing_at(layer, frame);
3984 if (!drawing) {
3985 continue;
3986 }
3987 const bke::CurvesGeometry &curves = drawing->strokes();
3988 if (curves.is_empty()) {
3989 continue;
3990 }
3991 if (layer_to_object == float4x4::identity()) {
3992 bounds = bounds::merge(bounds, curves.bounds_min_max(use_radius));
3993 continue;
3994 }
3995 const VArray<float> radius = curves.radius();
3996 Array<float3> positions_world(curves.evaluated_points_num());
3997 math::transform_points(curves.evaluated_positions(), layer_to_object, positions_world);
3998 if (!use_radius) {
3999 const Bounds<float3> drawing_bounds = *bounds::min_max(positions_world.as_span());
4000 bounds = bounds::merge(bounds, drawing_bounds);
4001 continue;
4002 }
4003 if (const std::optional radius_single = radius.get_if_single()) {
4004 Bounds<float3> drawing_bounds = *curves.bounds_min_max(false);
4005 drawing_bounds.pad(*radius_single);
4006 bounds = bounds::merge(bounds, drawing_bounds);
4007 continue;
4008 }
4009 const Span radius_span = radius.get_internal_span();
4010 if (curves.is_single_type(CURVE_TYPE_POLY)) {
4011 const Bounds<float3> drawing_bounds = *bounds::min_max_with_radii(positions_world.as_span(),
4012 radius_span);
4013 bounds = bounds::merge(bounds, drawing_bounds);
4014 continue;
4015 }
4017 Array<float> radii_eval(curves.evaluated_points_num());
4018 curves.interpolate_to_evaluated(radius_span, radii_eval.as_mutable_span());
4019 const Bounds<float3> drawing_bounds = *bounds::min_max_with_radii(positions_world.as_span(),
4020 radii_eval.as_span());
4021 bounds = bounds::merge(bounds, drawing_bounds);
4022 }
4023 return bounds;
4024}
4025
4026std::optional<Bounds<float3>> GreasePencil::bounds_min_max_eval(const bool use_radius) const
4027{
4028 return this->bounds_min_max(this->runtime->eval_frame, use_radius);
4029}
4030
4031void GreasePencil::count_memory(MemoryCounter &memory) const
4032{
4033 using namespace blender::bke;
4034 for (const GreasePencilDrawingBase *base : this->drawings()) {
4035 if (base->type != GP_DRAWING) {
4036 continue;
4037 }
4038 const greasepencil::Drawing &drawing =
4039 reinterpret_cast<const GreasePencilDrawing *>(base)->wrap();
4040 drawing.strokes().count_memory(memory);
4041 }
4042}
4043
4044std::optional<int> GreasePencil::material_index_max() const
4045{
4046 using namespace blender::bke;
4047 std::optional<int> max_index;
4048 for (const GreasePencilDrawingBase *drawing_base : this->drawings()) {
4049 if (drawing_base->type != GP_DRAWING) {
4050 continue;
4051 }
4052 const GreasePencilDrawing *drawing = reinterpret_cast<const GreasePencilDrawing *>(
4053 drawing_base);
4054 const std::optional<int> max_index_in_drawing = drawing->wrap().strokes().material_index_max();
4055 if (max_index) {
4056 if (max_index_in_drawing) {
4057 max_index = std::max(*max_index, *max_index_in_drawing);
4058 }
4059 }
4060 else {
4061 max_index = max_index_in_drawing;
4062 }
4063 }
4064 return max_index;
4065}
4066
4067Span<const bke::greasepencil::Layer *> GreasePencil::layers() const
4068{
4069 BLI_assert(this->runtime != nullptr);
4070 return this->root_group().layers();
4071}
4072
4073Span<bke::greasepencil::Layer *> GreasePencil::layers_for_write()
4074{
4075 BLI_assert(this->runtime != nullptr);
4076 return this->root_group().layers_for_write();
4077}
4078
4079Span<const bke::greasepencil::LayerGroup *> GreasePencil::layer_groups() const
4080{
4081 BLI_assert(this->runtime != nullptr);
4082 return this->root_group().groups();
4083}
4084
4085Span<bke::greasepencil::LayerGroup *> GreasePencil::layer_groups_for_write()
4086{
4087 BLI_assert(this->runtime != nullptr);
4088 return this->root_group().groups_for_write();
4089}
4090
4091Span<const bke::greasepencil::TreeNode *> GreasePencil::nodes() const
4092{
4093 BLI_assert(this->runtime != nullptr);
4094 return this->root_group().nodes();
4095}
4096
4097Span<bke::greasepencil::TreeNode *> GreasePencil::nodes_for_write()
4098{
4099 BLI_assert(this->runtime != nullptr);
4100 return this->root_group().nodes_for_write();
4101}
4102
4103std::optional<int> GreasePencil::get_layer_index(const bke::greasepencil::Layer &layer) const
4104{
4105 const int index = int(this->layers().first_index_try(&layer));
4106 if (index == -1) {
4107 return {};
4108 }
4109 return index;
4110}
4111
4112const bke::greasepencil::Layer *GreasePencil::get_active_layer() const
4113{
4114 if (this->active_node == nullptr) {
4115 return nullptr;
4116 }
4117 const bke::greasepencil::TreeNode &active_node = *this->get_active_node();
4118 if (!active_node.is_layer()) {
4119 return nullptr;
4120 }
4121 return &active_node.as_layer();
4122}
4123
4124bke::greasepencil::Layer *GreasePencil::get_active_layer()
4125{
4126 if (this->active_node == nullptr) {
4127 return nullptr;
4128 }
4129 bke::greasepencil::TreeNode &active_node = *this->get_active_node();
4130 if (!active_node.is_layer()) {
4131 return nullptr;
4132 }
4133 return &active_node.as_layer();
4134}
4135
4136void GreasePencil::set_active_layer(bke::greasepencil::Layer *layer)
4137{
4138 this->active_node = reinterpret_cast<GreasePencilLayerTreeNode *>(&layer->as_node());
4139
4140 if (this->flag & GREASE_PENCIL_AUTOLOCK_LAYERS) {
4141 this->autolock_inactive_layers();
4142 }
4143}
4144
4145bool GreasePencil::is_layer_active(const bke::greasepencil::Layer *layer) const
4146{
4147 if (layer == nullptr) {
4148 return false;
4149 }
4150 return this->get_active_layer() == layer;
4151}
4152
4153void GreasePencil::autolock_inactive_layers()
4154{
4155 using namespace blender::bke::greasepencil;
4156
4157 for (Layer *layer : this->layers_for_write()) {
4158 if (this->is_layer_active(layer)) {
4159 layer->set_locked(false);
4160 continue;
4161 }
4162 layer->set_locked(true);
4163 }
4164}
4165
4166const bke::greasepencil::LayerGroup *GreasePencil::get_active_group() const
4167{
4168 if (this->active_node == nullptr) {
4169 return nullptr;
4170 }
4171 const bke::greasepencil::TreeNode &active_node = *this->get_active_node();
4172 if (!active_node.is_group()) {
4173 return nullptr;
4174 }
4175 return &active_node.as_group();
4176}
4177
4178bke::greasepencil::LayerGroup *GreasePencil::get_active_group()
4179{
4180 if (this->active_node == nullptr) {
4181 return nullptr;
4182 }
4183 bke::greasepencil::TreeNode &active_node = *this->get_active_node();
4184 if (!active_node.is_group()) {
4185 return nullptr;
4186 }
4187 return &active_node.as_group();
4188}
4189
4190const bke::greasepencil::TreeNode *GreasePencil::get_active_node() const
4191{
4192 if (this->active_node == nullptr) {
4193 return nullptr;
4194 }
4195 return &this->active_node->wrap();
4196}
4197
4198bke::greasepencil::TreeNode *GreasePencil::get_active_node()
4199{
4200 if (this->active_node == nullptr) {
4201 return nullptr;
4202 }
4203 return &this->active_node->wrap();
4204}
4205
4206void GreasePencil::set_active_node(bke::greasepencil::TreeNode *node)
4207{
4208 this->active_node = reinterpret_cast<GreasePencilLayerTreeNode *>(node);
4209}
4210
4212{
4214 for (const bke::greasepencil::TreeNode *node : grease_pencil.nodes()) {
4215 names.add(node->name());
4216 }
4217 return names;
4218}
4219
4220static std::string unique_node_name(const GreasePencil &grease_pencil, const StringRef name)
4221{
4222 BLI_assert(!name.is_empty());
4224 return BLI_uniquename_cb(
4225 [&](const StringRef check_name) { return names.contains(check_name); }, '.', name);
4226}
4227
4228std::string GreasePencil::unique_layer_name(StringRef name)
4229{
4230 if (name.is_empty()) {
4231 /* Default name is "Layer". */
4232 name = DATA_("Layer");
4233 }
4234 return unique_node_name(*this, name);
4235}
4236
4238{
4239 if (name.is_empty()) {
4240 /* Default name is "Group". */
4241 name = DATA_("Group");
4242 }
4243 return unique_node_name(grease_pencil, name);
4244}
4245
4246bke::greasepencil::Layer &GreasePencil::add_layer(const StringRef name,
4247 const bool check_name_is_unique)
4248{
4249 std::string unique_name = check_name_is_unique ? unique_layer_name(name) : std::string(name);
4250 const int numLayers = layers().size();
4251 this->attribute_storage.wrap().resize(bke::AttrDomain::Layer, numLayers + 1);
4252 bke::greasepencil::Layer *new_layer = MEM_new<bke::greasepencil::Layer>(__func__, unique_name);
4253 /* Enable Lights by default. */
4255 /* Hide masks by default. */
4257 bke::greasepencil::Layer &layer = root_group().add_node(new_layer->as_node()).as_layer();
4258
4259 /* Initialize the attributes with default values. */
4260 bke::MutableAttributeAccessor attributes = this->attributes_for_write();
4264 IndexRange::from_single(numLayers));
4265
4266 return layer;
4267}
4268
4269bke::greasepencil::Layer &GreasePencil::add_layer(bke::greasepencil::LayerGroup &parent_group,
4270 const StringRef name,
4271 const bool check_name_is_unique)
4272{
4273 bke::greasepencil::Layer &new_layer = this->add_layer(name, check_name_is_unique);
4274 move_node_into(new_layer.as_node(), parent_group);
4275 return new_layer;
4276}
4277
4278void GreasePencil::add_layers_for_eval(const int num_new_layers)
4279{
4280 const int num_layers = this->layers().size();
4281 this->attribute_storage.wrap().resize(bke::AttrDomain::Layer, num_layers + num_new_layers);
4282 for ([[maybe_unused]] const int i : IndexRange(num_new_layers)) {
4283 bke::greasepencil::Layer *new_layer = MEM_new<bke::greasepencil::Layer>(__func__);
4284 /* Hide masks by default. */
4286 this->root_group().add_node(new_layer->as_node());
4287 }
4288}
4289
4290bke::greasepencil::Layer &GreasePencil::duplicate_layer(
4291 const bke::greasepencil::Layer &duplicate_layer,
4292 const bool duplicate_frames,
4293 const bool duplicate_drawings)
4294{
4295 std::string unique_name = unique_layer_name(duplicate_layer.name());
4296 std::optional<int> duplicate_layer_idx = get_layer_index(duplicate_layer);
4297 BLI_assert(duplicate_layer_idx.has_value());
4298 const int numLayers = layers().size();
4299 bke::greasepencil::Layer *new_layer = MEM_new<bke::greasepencil::Layer>(__func__,
4300 duplicate_layer);
4301 root_group().add_node(new_layer->as_node());
4302
4303 this->attribute_storage.wrap().resize(bke::AttrDomain::Layer, numLayers + 1);
4304 bke::MutableAttributeAccessor attributes = this->attributes_for_write();
4305 attributes.foreach_attribute([&](const bke::AttributeIter &iter) {
4307 return;
4308 }
4309 bke::GSpanAttributeWriter attr = attributes.lookup_for_write_span(iter.name);
4310 GMutableSpan span = attr.span;
4311 span.type().copy_assign(span[*duplicate_layer_idx], span[numLayers]);
4312 attr.finish();
4313 });
4314
4315 /* When a layer is duplicated, the frames are shared by default. Clear the frames, to ensure a
4316 * valid state. */
4317 new_layer->frames_for_write().clear();
4318 if (duplicate_frames) {
4319 for (auto [frame_number, frame] : duplicate_layer.frames().items()) {
4320 const int duration = 0 /* duplicate_layer.get_frame_duration_at(frame_number) */;
4321 bke::greasepencil::Drawing *dst_drawing = this->insert_frame(
4322 *new_layer, frame_number, duration, eBezTriple_KeyframeType(frame.type));
4323 if (duplicate_drawings) {
4324 BLI_assert(dst_drawing != nullptr);
4325 /* TODO: This can fail (return `nullptr`) if the drawing is a drawing reference! */
4326 const bke::greasepencil::Drawing &src_drawing = *this->get_drawing_at(duplicate_layer,
4327 frame_number);
4328 /* Duplicate the drawing. */
4329 *dst_drawing = src_drawing;
4330 }
4331 }
4332 }
4333
4334 this->update_drawing_users_for_layer(*new_layer);
4335 new_layer->set_name(unique_name);
4336 return *new_layer;
4337}
4338
4339bke::greasepencil::Layer &GreasePencil::duplicate_layer(
4340 bke::greasepencil::LayerGroup &parent_group,
4341 const bke::greasepencil::Layer &duplicate_layer,
4342 const bool duplicate_frames,
4343 const bool duplicate_drawings)
4344{
4345 bke::greasepencil::Layer &new_layer = this->duplicate_layer(
4346 duplicate_layer, duplicate_frames, duplicate_drawings);
4347 move_node_into(new_layer.as_node(), parent_group);
4348 return new_layer;
4349}
4350
4351bke::greasepencil::LayerGroup &GreasePencil::add_layer_group(const StringRef name,
4352 const bool check_name_is_unique)
4353{
4354 std::string unique_name = check_name_is_unique ? unique_layer_group_name(*this, name) :
4355 std::string(name);
4356 bke::greasepencil::LayerGroup *new_group = MEM_new<bke::greasepencil::LayerGroup>(__func__,
4357 unique_name);
4358 return root_group().add_node(new_group->as_node()).as_group();
4359}
4360
4361bke::greasepencil::LayerGroup &GreasePencil::add_layer_group(
4362 bke::greasepencil::LayerGroup &parent_group,
4363 const StringRef name,
4364 const bool check_name_is_unique)
4365{
4366 bke::greasepencil::LayerGroup &new_group = this->add_layer_group(name, check_name_is_unique);
4367 move_node_into(new_group.as_node(), parent_group);
4368 return new_group;
4369}
4370
4372 const bke::AttrDomain domain,
4373 const Span<int> new_by_old_map)
4374{
4375 for (bke::Attribute &attr : data) {
4376 if (attr.domain() != domain) {
4377 continue;
4378 }
4379 const CPPType &type = bke::attribute_type_to_cpp_type(attr.data_type());
4380 switch (attr.storage_type()) {
4382 const auto &data = std::get<bke::Attribute::ArrayData>(attr.data());
4383 auto new_data = bke::Attribute::ArrayData::from_constructed(type, new_by_old_map.size());
4384 bke::attribute_math::gather(GSpan(type, data.data, data.size),
4385 new_by_old_map,
4386 GMutableSpan(type, new_data.data, new_data.size));
4387 attr.assign_data(std::move(new_data));
4388 break;
4389 }
4391 break;
4392 }
4393 }
4394 }
4395}
4396
4398 const FunctionRef<void()> do_layer_order_changes)
4399{
4401
4402 /* Stash the initial layer order that we can refer back to later */
4403 Map<const bke::greasepencil::Layer *, int> old_layer_index_by_layer;
4404 old_layer_index_by_layer.reserve(layers.size());
4405 for (const int i : layers.index_range()) {
4406 old_layer_index_by_layer.add_new(layers[i], i);
4407 }
4408
4409 /* Execute the callback that changes the order of the layers. */
4410 do_layer_order_changes();
4411 layers = grease_pencil.layers();
4412 BLI_assert(layers.size() == old_layer_index_by_layer.size());
4413
4414 /* Compose the mapping from old layer indices to new layer indices */
4415 Array<int> new_by_old_map(layers.size());
4416 for (const int layer_i_new : layers.index_range()) {
4417 const bke::greasepencil::Layer *layer = layers[layer_i_new];
4418 BLI_assert(old_layer_index_by_layer.contains(layer));
4419 const int layer_i_old = old_layer_index_by_layer.pop(layer);
4420 new_by_old_map[layer_i_new] = layer_i_old;
4421 }
4422 BLI_assert(old_layer_index_by_layer.is_empty());
4423
4424 /* Use the mapping to re-order the custom data */
4426 grease_pencil.attribute_storage.wrap(), bke::AttrDomain::Layer, new_by_old_map);
4427}
4428
4429void GreasePencil::move_node_up(bke::greasepencil::TreeNode &node, const int step)
4430{
4431 if (!node.parent_group()) {
4432 return;
4433 }
4434 reorder_layer_data(*this, [&]() { node.parent_group()->move_node_up(node, step); });
4435}
4436void GreasePencil::move_node_down(bke::greasepencil::TreeNode &node, const int step)
4437{
4438 if (!node.parent_group()) {
4439 return;
4440 }
4441 reorder_layer_data(*this, [&]() { node.parent_group()->move_node_down(node, step); });
4442}
4443void GreasePencil::move_node_top(bke::greasepencil::TreeNode &node)
4444{
4445 if (!node.parent_group()) {
4446 return;
4447 }
4448 reorder_layer_data(*this, [&]() { node.parent_group()->move_node_top(node); });
4449}
4450void GreasePencil::move_node_bottom(bke::greasepencil::TreeNode &node)
4451{
4452 if (!node.parent_group()) {
4453 return;
4454 }
4455 reorder_layer_data(*this, [&]() { node.parent_group()->move_node_bottom(node); });
4456}
4457
4458void GreasePencil::move_node_after(bke::greasepencil::TreeNode &node,
4459 bke::greasepencil::TreeNode &target_node)
4460{
4461 if (!target_node.parent_group() || !node.parent_group()) {
4462 return;
4463 }
4464 reorder_layer_data(*this, [&]() {
4465 node.parent_group()->unlink_node(node);
4466 target_node.parent_group()->add_node_after(node, target_node);
4467 });
4468}
4469
4470void GreasePencil::move_node_before(bke::greasepencil::TreeNode &node,
4471 bke::greasepencil::TreeNode &target_node)
4472{
4473 if (!target_node.parent_group() || !node.parent_group()) {
4474 return;
4475 }
4476 reorder_layer_data(*this, [&]() {
4477 node.parent_group()->unlink_node(node);
4478 target_node.parent_group()->add_node_before(node, target_node);
4479 });
4480}
4481
4482void GreasePencil::move_node_into(bke::greasepencil::TreeNode &node,
4483 bke::greasepencil::LayerGroup &parent_group)
4484{
4485 if (!node.parent_group()) {
4486 return;
4487 }
4488 reorder_layer_data(*this, [&]() {
4489 node.parent_group()->unlink_node(node);
4490 parent_group.add_node(node);
4491 });
4492}
4493
4494const bke::greasepencil::TreeNode *GreasePencil::find_node_by_name(const StringRef name) const
4495{
4496 return this->root_group().find_node_by_name(name);
4497}
4498
4499bke::greasepencil::TreeNode *GreasePencil::find_node_by_name(const StringRef name)
4500{
4501 return this->root_group().find_node_by_name(name);
4502}
4503
4504IndexMask GreasePencil::layer_selection_by_name(const StringRef name,
4505 IndexMaskMemory &memory) const
4506{
4507 using namespace blender::bke::greasepencil;
4508 const TreeNode *node = this->find_node_by_name(name);
4509 if (!node) {
4510 return {};
4511 }
4512
4513 if (node->is_layer()) {
4514 const int index = *this->get_layer_index(node->as_layer());
4515 return IndexMask::from_indices(Span<int>{index}, memory);
4516 }
4517 if (node->is_group()) {
4518 Vector<int64_t> layer_indices;
4519 for (const int64_t layer_index : this->layers().index_range()) {
4520 const Layer &layer = *this->layers()[layer_index];
4521 if (layer.is_child_of(node->as_group())) {
4522 layer_indices.append(layer_index);
4523 }
4524 }
4525 return IndexMask::from_indices(layer_indices.as_span(), memory);
4526 }
4527 return {};
4528}
4529
4531{
4532 switch (md->type) {
4534 auto *amd = reinterpret_cast<GreasePencilArmatureModifierData *>(md);
4535 return &amd->influence;
4536 }
4538 auto *mmd = reinterpret_cast<GreasePencilArrayModifierData *>(md);
4539 return &mmd->influence;
4540 }
4542 auto *bmd = reinterpret_cast<GreasePencilBuildModifierData *>(md);
4543 return &bmd->influence;
4544 }
4546 auto *cmd = reinterpret_cast<GreasePencilColorModifierData *>(md);
4547 return &cmd->influence;
4548 }
4550 auto *dmd = reinterpret_cast<GreasePencilDashModifierData *>(md);
4551 return &dmd->influence;
4552 }
4554 auto *emd = reinterpret_cast<GreasePencilEnvelopeModifierData *>(md);
4555 return &emd->influence;
4556 }
4558 auto *hmd = reinterpret_cast<GreasePencilHookModifierData *>(md);
4559 return &hmd->influence;
4560 }
4562 auto *lmd = reinterpret_cast<GreasePencilLatticeModifierData *>(md);
4563 return &lmd->influence;
4564 }
4566 auto *lmd = reinterpret_cast<GreasePencilLengthModifierData *>(md);
4567 return &lmd->influence;
4568 }
4570 auto *mmd = reinterpret_cast<GreasePencilMirrorModifierData *>(md);
4571 return &mmd->influence;
4572 }
4574 auto *mmd = reinterpret_cast<GreasePencilMultiModifierData *>(md);
4575 return &mmd->influence;
4576 }
4578 auto *nmd = reinterpret_cast<GreasePencilNoiseModifierData *>(md);
4579 return &nmd->influence;
4580 }
4582 auto *omd = reinterpret_cast<GreasePencilOffsetModifierData *>(md);
4583 return &omd->influence;
4584 }
4586 auto *omd = reinterpret_cast<GreasePencilOpacityModifierData *>(md);
4587 return &omd->influence;
4588 }
4590 auto *omd = reinterpret_cast<GreasePencilOutlineModifierData *>(md);
4591 return &omd->influence;
4592 }
4594 auto *smd = reinterpret_cast<GreasePencilShrinkwrapModifierData *>(md);
4595 return &smd->influence;
4596 }
4598 auto *smd = reinterpret_cast<GreasePencilSimplifyModifierData *>(md);
4599 return &smd->influence;
4600 }
4602 auto *smd = reinterpret_cast<GreasePencilSmoothModifierData *>(md);
4603 return &smd->influence;
4604 }
4606 auto *smd = reinterpret_cast<GreasePencilSubdivModifierData *>(md);
4607 return &smd->influence;
4608 }
4610 auto *tmd = reinterpret_cast<GreasePencilTextureModifierData *>(md);
4611 return &tmd->influence;
4612 }
4614 auto *tmd = reinterpret_cast<GreasePencilThickModifierData *>(md);
4615 return &tmd->influence;
4616 }
4618 auto *tmd = reinterpret_cast<GreasePencilTimeModifierData *>(md);
4619 return &tmd->influence;
4620 }
4622 auto *tmd = reinterpret_cast<GreasePencilTintModifierData *>(md);
4623 return &tmd->influence;
4624 }
4626 auto *wmd = reinterpret_cast<GreasePencilWeightAngleModifierData *>(md);
4627 return &wmd->influence;
4628 }
4630 auto *wmd = reinterpret_cast<GreasePencilWeightProximityModifierData *>(md);
4631 return &wmd->influence;
4632 }
4635 default:
4636 return nullptr;
4637 }
4638 return nullptr;
4639}
4640
4641void GreasePencil::rename_node(Main &bmain,
4643 const StringRef new_name)
4644{
4645 if (node.name() == new_name) {
4646 return;
4647 }
4648
4649 /* Rename the node. */
4650 std::string old_name = node.name();
4651 if (node.is_layer()) {
4652 node.set_name(unique_layer_name(new_name));
4653 }
4654 else if (node.is_group()) {
4655 node.set_name(unique_layer_group_name(*this, new_name));
4656 }
4657
4658 /* Update layer name dependencies. */
4659 if (node.is_layer()) {
4660 BKE_animdata_fix_paths(this->id,
4661 "layers",
4662 RNA_path_name_to_infix(old_name),
4664 /*verify_paths=*/true,
4665 bmain);
4666 /* Update names in layer masks. */
4667 for (bke::greasepencil::Layer *layer : this->layers_for_write()) {
4668 for (GreasePencilLayerMask &mask : layer->masks) {
4669 if (STREQ(mask.layer_name, old_name.c_str())) {
4670 mask.layer_name = BLI_strdup(node.name().c_str());
4671 }
4672 }
4673 }
4674 }
4675
4676 /* Update name dependencies outside of the ID. */
4677 for (Object &object : bmain.objects) {
4678 if (object.data != id_cast<ID *>(this)) {
4679 continue;
4680 }
4681
4682 /* Update the layer name of the influence data of the modifiers. */
4683 for (ModifierData &md : object.modifiers) {
4684 char *dst_layer_name = nullptr;
4685 size_t dst_layer_name_maxncpy = 0;
4686 /* LineArt doesn't use the `GreasePencilModifierInfluenceData` struct. */
4687 if (md.type == eModifierType_GreasePencilLineart) {
4688 auto *lmd = reinterpret_cast<GreasePencilLineartModifierData *>(&md);
4689 dst_layer_name = lmd->target_layer;
4690 dst_layer_name_maxncpy = sizeof(lmd->target_layer);
4691 }
4692 else if (GreasePencilModifierInfluenceData *influence_data = influence_data_from_modifier(
4693 &md))
4694 {
4695 dst_layer_name = influence_data->layer_name;
4696 dst_layer_name_maxncpy = sizeof(influence_data->layer_name);
4697 }
4698 if (dst_layer_name && STREQ(dst_layer_name, old_name.c_str())) {
4699 BLI_strncpy(dst_layer_name, node.name().c_str(), dst_layer_name_maxncpy);
4700 }
4701 }
4702 }
4703}
4704
4706 const int index_to_remove,
4707 const int size)
4708{
4709 const IndexRange range_before(index_to_remove);
4710 const IndexRange range_after(index_to_remove + 1, size - index_to_remove - 1);
4711
4712 for (bke::Attribute &attr : storage) {
4713 const CPPType &type = bke::attribute_type_to_cpp_type(attr.data_type());
4714 switch (attr.storage_type()) {
4716 const auto &data = std::get<bke::Attribute::ArrayData>(attr.data());
4717
4718 auto new_data = bke::Attribute::ArrayData::from_uninitialized(type, size - 1);
4719 type.copy_construct_n(data.data, new_data.data, range_before.size());
4720 type.copy_construct_n(POINTER_OFFSET(data.data, type.size * range_after.start()),
4721 POINTER_OFFSET(new_data.data, type.size * index_to_remove),
4722 range_after.size());
4723
4724 attr.assign_data(std::move(new_data));
4725 break;
4726 }
4728 break;
4729 }
4730 }
4731 }
4732}
4733
4736{
4737 using namespace blender::bke::greasepencil;
4738 /* 1. Try setting the node below (within the same group) to be active. */
4739 if (node.prev != nullptr) {
4740 grease_pencil.set_active_node(reinterpret_cast<TreeNode *>(node.prev));
4741 }
4742 /* 2. If there is no node below, try setting the node above (within the same group) to be the
4743 * active one. */
4744 else if (node.next != nullptr) {
4745 grease_pencil.set_active_node(reinterpret_cast<TreeNode *>(node.next));
4746 }
4747 /* 3. If this is the only node within its parent group and the parent group is not the root
4748 * group, try setting the parent to be active. */
4749 else if (node.parent != grease_pencil.root_group_ptr) {
4750 grease_pencil.set_active_node(&node.parent->wrap().as_node());
4751 }
4752 /* 4. Otherwise, clear the active node. */
4753 else {
4754 grease_pencil.set_active_node(nullptr);
4755 }
4756}
4757
4758void GreasePencil::remove_layer(bke::greasepencil::Layer &layer)
4759{
4760 using namespace blender::bke::greasepencil;
4761 /* If the layer is active, update the active layer. */
4762 if (&layer.as_node() == this->get_active_node()) {
4764 }
4765
4766 /* Remove all the layer attributes and shrink the `CustomData`. */
4767 const int layer_index = *this->get_layer_index(layer);
4768 shrink_attribute_storage(this->attribute_storage.wrap(), layer_index, this->layers().size());
4769
4770 /* Unlink the layer from the parent group. */
4771 layer.parent_group().unlink_node(layer.as_node());
4772
4773 /* Remove drawings. */
4774 for (const GreasePencilFrame frame : layer.frames().values()) {
4775 GreasePencilDrawingBase *drawing_base = this->drawing(frame.drawing_index);
4776 if (drawing_base->type != GP_DRAWING) {
4777 /* TODO: Remove drawing reference. */
4778 continue;
4779 }
4780 GreasePencilDrawing *drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base);
4781 drawing->wrap().remove_user();
4782 }
4783 this->remove_drawings_with_no_users();
4784
4785 /* Delete the layer. */
4786 MEM_delete(&layer);
4787}
4788
4789void GreasePencil::remove_group(bke::greasepencil::LayerGroup &group, const bool keep_children)
4790{
4791 using namespace blender::bke::greasepencil;
4792 /* If the group is active, update the active layer. */
4793 if (&group.as_node() == this->get_active_node()) {
4794 /* If we keep the children and there is at least one child, make it the active node. */
4795 if (keep_children && !group.is_empty()) {
4796 this->set_active_node(reinterpret_cast<TreeNode *>(group.children.last()));
4797 }
4798 else {
4800 }
4801 }
4802
4803 if (!keep_children) {
4804 /* Recursively remove groups and layers. */
4805 for (GreasePencilLayerTreeNode &child : group.children.items_mutable()) {
4806 switch (child.type) {
4807 case GP_LAYER_TREE_LEAF: {
4808 this->remove_layer(reinterpret_cast<GreasePencilLayer *>(&child)->wrap());
4809 break;
4810 }
4811 case GP_LAYER_TREE_GROUP: {
4812 this->remove_group(reinterpret_cast<GreasePencilLayerTreeGroup *>(&child)->wrap(),
4813 false);
4814 break;
4815 }
4816 default:
4818 }
4819 }
4820 BLI_assert(group.children.is_empty());
4821 }
4822
4823 /* Unlink then delete active group node. */
4824 group.as_node().parent_group()->unlink_node(group.as_node(), true);
4825 MEM_delete(&group);
4826}
4827
4828void GreasePencil::print_layer_tree()
4829{
4830 using namespace blender::bke::greasepencil;
4831 this->root_group().print_nodes("Layer Tree:");
4832}
4833
4834Array<int> GreasePencil::count_frame_users_for_drawings() const
4835{
4836 using namespace blender::bke::greasepencil;
4837 Array<int> user_counts(this->drawings().size(), 0);
4838 for (const Layer *layer : this->layers()) {
4839 for (const auto &[frame, value] : layer->frames().items()) {
4840 BLI_assert(this->drawings().index_range().contains(value.drawing_index));
4841 user_counts[value.drawing_index]++;
4842 }
4843 }
4844 return user_counts;
4845}
4846
4847void GreasePencil::validate_drawing_user_counts()
4848{
4849#ifndef NDEBUG
4850 using namespace blender::bke::greasepencil;
4851 Array<int> actual_user_counts = this->count_frame_users_for_drawings();
4852 for (const int drawing_i : this->drawings().index_range()) {
4853 const GreasePencilDrawingBase *drawing_base = this->drawing(drawing_i);
4854 if (drawing_base->type != GP_DRAWING_REFERENCE) {
4855 const Drawing &drawing = reinterpret_cast<const GreasePencilDrawing *>(drawing_base)->wrap();
4856 /* Ignore `fake_user` flag. */
4857 BLI_assert(drawing.user_count() == actual_user_counts[drawing_i]);
4858 }
4859 }
4860#endif
4861}
4862
4863bke::AttributeAccessor GreasePencil::attributes() const
4864{
4865 return bke::AttributeAccessor(this, bke::greasepencil::get_attribute_accessor_functions());
4866}
4867
4868bke::MutableAttributeAccessor GreasePencil::attributes_for_write()
4869{
4870 return bke::MutableAttributeAccessor(this,
4872}
4873
4875
4876/* ------------------------------------------------------------------- */
4879
4881{
4882 switch (type) {
4883 case GP_DRAWING:
4884 return sizeof(GreasePencilDrawing);
4886 return sizeof(GreasePencilDrawingReference);
4887 }
4888 return sizeof(GreasePencilDrawingBase);
4889}
4890
4892{
4894 reader, &grease_pencil.drawing_array, &grease_pencil.drawing_array_num);
4895 for (int i = 0; i < grease_pencil.drawing_array_num; i++) {
4897 reader, &grease_pencil.drawing_array[i], [](const GreasePencilDrawingBase &drawing) {
4898 return drawing_struct_size(GreasePencilDrawingType(drawing.type));
4899 });
4900 GreasePencilDrawingBase *drawing_base = grease_pencil.drawing_array[i];
4901
4902 /* Replace drawings that failed to read from corrupt files by an empty drawing, since further
4903 * reading code expects valid drawings. */
4904 if (drawing_base == nullptr) {
4905 grease_pencil.drawing_array[i] = reinterpret_cast<GreasePencilDrawingBase *>(
4906 MEM_new<bke::greasepencil::Drawing>(__func__));
4907 continue;
4908 }
4909
4910 switch (GreasePencilDrawingType(drawing_base->type)) {
4911 case GP_DRAWING: {
4912 GreasePencilDrawing *drawing = reinterpret_cast<GreasePencilDrawing *>(drawing_base);
4913 drawing->wrap().strokes_for_write().blend_read(*reader);
4914 /* Initialize runtime data. */
4915 drawing->runtime = MEM_new<bke::greasepencil::DrawingRuntime>(__func__);
4916 break;
4917 }
4918 case GP_DRAWING_REFERENCE: {
4919 break;
4920 }
4921 }
4922 }
4923}
4924
4926 ResourceScope &scope,
4927 BlendWriter *writer)
4928{
4929 writer->write_pointer_array(grease_pencil.drawing_array_num, grease_pencil.drawing_array);
4930 for (int i = 0; i < grease_pencil.drawing_array_num; i++) {
4931 GreasePencilDrawingBase *drawing_base = grease_pencil.drawing_array[i];
4932 switch (GreasePencilDrawingType(drawing_base->type)) {
4933 case GP_DRAWING: {
4934 GreasePencilDrawing &drawing_copy = scope.construct<GreasePencilDrawing>();
4935 drawing_copy = *reinterpret_cast<GreasePencilDrawing *>(drawing_base);
4936 bke::CurvesGeometry &curves = drawing_copy.geometry.wrap();
4937
4938 bke::CurvesGeometry::BlendWriteData write_data(writer, scope);
4939 curves.blend_write_prepare(write_data, !writer->is_undo());
4940 drawing_copy.runtime = nullptr;
4941
4943 drawing_base,
4944 &drawing_copy,
4945 [](BlendStructWriter<GreasePencilDrawing> &struct_writer) {
4946 struct_writer.generated_ptr(
4947 offsetof(GreasePencilDrawing, geometry.attribute_storage.dna_attributes));
4948 });
4949 curves.blend_write(*writer, grease_pencil.id, write_data);
4950 break;
4951 }
4952 case GP_DRAWING_REFERENCE: {
4953 GreasePencilDrawingReference *drawing_reference =
4954 reinterpret_cast<GreasePencilDrawingReference *>(drawing_base);
4955 writer->write_struct(drawing_reference);
4956 break;
4957 }
4958 }
4959 }
4960}
4961
4963{
4964 grease_pencil.resize_drawings(0);
4965}
4966
4968
4969/* ------------------------------------------------------------------- */
4972
4973static void read_layer(BlendDataReader *reader,
4976{
4977 BLO_read_string(reader, &node->base.name);
4978 node->base.parent = parent;
4979 BLO_read_string(reader, &node->parsubstr);
4980 BLO_read_string(reader, &node->viewlayername);
4981
4982 /* Read frames storage. */
4983 {
4984 bool ok = true;
4985 ok &= BLO_read_array(reader, &node->frames_storage.keys, node->frames_storage.num);
4986 ok &= BLO_read_array(reader, &node->frames_storage.values, node->frames_storage.num);
4987 if (!ok) {
4988 node->frames_storage.num = 0;
4989 }
4990 }
4991
4992 /* Read layer masks. */
4994 for (GreasePencilLayerMask &mask : node->masks) {
4995 BLO_read_string(reader, &mask.layer_name);
4996 }
4997
4998 /* NOTE: Ideally this should be cleared on write, to reduce false 'changes' detection in memfile
4999 * undo system. This is not easily doable currently though, since modifying to actual data during
5000 * write is not an option (a shallow copy of the #Layer data would be needed then). */
5001 node->runtime = nullptr;
5002 node->wrap().update_from_dna_read();
5003}
5004
5006{
5007 switch (type) {
5008 case GP_LAYER_TREE_LEAF:
5009 return sizeof(GreasePencilLayer);
5011 return sizeof(GreasePencilLayerTreeGroup);
5012 }
5013 return sizeof(GreasePencilLayerTreeNode);
5014}
5015
5019{
5020 BLO_read_string(reader, &node->base.name);
5021 node->base.parent = parent;
5022 /* Read list of children. */
5024 reader, &node->children, [](const GreasePencilLayerTreeNode &child) {
5025 return layer_tree_node_struct_size(child.type);
5026 });
5027 for (GreasePencilLayerTreeNode &child : node->children) {
5028 switch (child.type) {
5029 case GP_LAYER_TREE_LEAF: {
5030 GreasePencilLayer *layer = reinterpret_cast<GreasePencilLayer *>(&child);
5031 read_layer(reader, layer, node);
5032 break;
5033 }
5034 case GP_LAYER_TREE_GROUP: {
5035 GreasePencilLayerTreeGroup *group = reinterpret_cast<GreasePencilLayerTreeGroup *>(&child);
5036 read_layer_tree_group(reader, group, node);
5037 break;
5038 }
5039 }
5040 }
5041
5042 node->wrap().runtime = MEM_new<bke::greasepencil::LayerGroupRuntime>(__func__);
5043}
5044
5046{
5047 /* Read root group. */
5049 /* This shouldn't normally happen, but for files that were created before the root group became a
5050 * pointer, this address will not exist. In this case, we clear the pointer to the active layer
5051 * and create an empty root group to avoid crashes. */
5052 if (grease_pencil.root_group_ptr == nullptr) {
5053 grease_pencil.root_group_ptr = MEM_new<bke::greasepencil::LayerGroup>(__func__);
5054 grease_pencil.set_active_node(nullptr);
5055 return;
5056 }
5057 read_layer_tree_group(reader, grease_pencil.root_group_ptr, nullptr);
5058 /* Read active layer after the tree, so it is null if its node failed to read. */
5060
5061 grease_pencil.root_group_ptr->wrap().update_from_dna_read();
5062}
5063
5065{
5066 writer->write_struct(node);
5067 writer->write_string(node->base.name);
5068 writer->write_string(node->parsubstr);
5069 writer->write_string(node->viewlayername);
5070
5071 writer->write_int32_array(node->frames_storage.num, node->frames_storage.keys);
5072 writer->write_struct_array(node->frames_storage.num, node->frames_storage.values);
5073
5074 writer->write_struct_list(&node->masks);
5075 for (GreasePencilLayerMask &mask : node->masks) {
5076 writer->write_string(mask.layer_name);
5077 }
5078}
5079
5081{
5082 writer->write_struct(node);
5083 writer->write_string(node->base.name);
5084 for (GreasePencilLayerTreeNode &child : node->children) {
5085 switch (child.type) {
5086 case GP_LAYER_TREE_LEAF: {
5087 GreasePencilLayer *layer = reinterpret_cast<GreasePencilLayer *>(&child);
5088 write_layer(writer, layer);
5089 break;
5090 }
5091 case GP_LAYER_TREE_GROUP: {
5092 GreasePencilLayerTreeGroup *group = reinterpret_cast<GreasePencilLayerTreeGroup *>(&child);
5093 write_layer_tree_group(writer, group);
5094 break;
5095 }
5096 }
5097 }
5098}
5099
5101{
5102 grease_pencil.root_group_ptr->wrap().prepare_for_dna_write();
5103 write_layer_tree_group(writer, grease_pencil.root_group_ptr);
5104}
5105
5107
5108} // namespace blender
Blender kernel action and pose functionality.
Low-level operations for curves.
CustomData interface, see also DNA_customdata_types.h.
support for deformation groups and hooks.
Low-level operations for grease pencil that cannot be defined in the C++ header yet.
Low-level operations for grease pencil.
#define BKE_LIB_FOREACHID_PROCESS_IDSUPER(data_, id_super_, cb_flag_)
General operations, lookup, etc. for materials.
General operations, lookup, etc. for blender objects.
#define ATTR_FALLTHROUGH
#define BLI_MEMARENA_STD_BUFSIZE
#define STRNCPY_UTF8(dst, src)
#define BLO_read_struct_list(reader, struct_name, list)
#define BLO_read_struct(reader, struct_name, ptr_p)
#define BLT_I18NCONTEXT_ID_GPENCIL
#define DATA_(msgid)
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
ID and Library types, which are fundamental for SDNA.
#define FILTER_ID_OB
Definition DNA_ID.h:1216
#define FILTER_ID_MA
Definition DNA_ID.h:1210
#define FILTER_ID_GP
Definition DNA_ID.h:1238
Enumerations for DNA_ID.h.
Read Blender memory allocation and freeing.
#define BLI_assert_unreachable()
#define UNUSED_VARS_NDEBUG(...)
#define SET_FLAG_FROM_TEST(value, test, flag)
#define BLI_assert(a)
#define INIT_DEFAULT_STRUCT_AFTER(struct_dst, member)
#define ELEM(...)
#define POINTER_OFFSET(v, ofs)
#define BLI_assert_msg(a, msg)
#define STREQ(a, b)
static DBVT_INLINE btScalar size(const btDbvtVolume &a)
Definition btDbvt.cpp:52
constexpr Span()=default
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr bool is_empty() const
Definition BLI_span.hh:264
int64_t size() const
Definition BLI_array.hh:267
Span< T > as_span() const
Definition BLI_array.hh:254
MutableSpan< T > as_mutable_span()
Definition BLI_array.hh:259
IndexRange index_range() const
Definition BLI_array.hh:371
void generated_ptr(int64_t offset)
Definition writefile.cc:986
void copy_construct_n(const void *src, void *dst, int64_t n) const
void copy_assign(const void *src, void *dst) const
void ensure(const FunctionRef< void()> compute_cache)
std::optional< GroupedSpan< int3 > > triangles() const
const CPPType & type() const
GSpan()=default
static IndexMask from_predicate(const IndexMask &universe, LinearAllocator<> &memory, Fn &&predicate, exec_mode::Mode mode=exec_mode::parallel)
static IndexMask from_indices(Span< T > indices, LinearAllocator<> &memory)
constexpr int64_t first() const
constexpr IndexRange drop_back(int64_t n) const
constexpr int64_t last(const int64_t n=0) const
constexpr int64_t size() const
constexpr bool is_empty() const
constexpr IndexRange()=default
constexpr int64_t start() const
constexpr IndexRange take_back(int64_t n) const
static constexpr IndexRange from_single(const int64_t index)
constexpr IndexRange index_range() const
constexpr IndexRange drop_front(int64_t n) const
const Value * lookup_ptr(const Key &key) const
Definition BLI_map.hh:508
Value pop(const Key &key)
Definition BLI_map.hh:402
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
const Value & lookup(const Key &key) const
Definition BLI_map.hh:545
void foreach_item(const FuncT &func) const
Definition BLI_map.hh:687
void add_new(const Key &key, const Value &value)
Definition BLI_map.hh:265
int64_t size() const
Definition BLI_map.hh:976
KeyIterator keys() const &
Definition BLI_map.hh:875
bool is_empty() const
Definition BLI_map.hh:986
void reserve(int64_t n)
Definition BLI_map.hh:1028
bool contains(const Key &key) const
Definition BLI_map.hh:353
ItemIterator items() const &
Definition BLI_map.hh:902
constexpr MutableSpan()=default
constexpr int64_t size() const
Definition BLI_span.hh:499
constexpr bool is_empty() const
Definition BLI_span.hh:515
constexpr T * data() const
Definition BLI_span.hh:545
constexpr MutableSpan drop_front(const int64_t n) const
Definition BLI_span.hh:613
constexpr IndexRange index_range() const
Definition BLI_span.hh:676
constexpr T & last(const int64_t n=0) const
Definition BLI_span.hh:695
IndexRange index_range() const
T & construct(Args &&...args)
bool add(const Key &key)
Definition BLI_set.hh:248
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr Span()=default
constexpr const T & first() const
Definition BLI_span.hh:319
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr const T & last(const int64_t n=0) const
Definition BLI_span.hh:329
constexpr const T * end() const
Definition BLI_span.hh:228
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
constexpr const T * begin() const
Definition BLI_span.hh:224
constexpr bool is_empty() const
Definition BLI_span.hh:264
bool is_empty() const
Definition BLI_stack.hh:310
void push(const T &value)
Definition BLI_stack.hh:215
constexpr StringRefNull()
bool add(const Key &key)
bool contains(const Key &key) const
int64_t size() const
void append(const T &value)
bool is_empty() const
IndexRange index_range() const
void resize(const int64_t new_size)
MutableSpan< T > as_mutable_span()
void reserve(const int64_t min_capacity)
void reinitialize(const int64_t new_size)
Span< T > as_span() const
GAttributeReader lookup_or_default(StringRef name, AttrDomain domain, AttrType data_type, const void *default_value=nullptr) const
void foreach_attribute(const FunctionRef< void(const AttributeIter &)> fn) const
bool contains(StringRef name) const
GAttributeReader lookup(const StringRef name) const
std::optional< AttrStorageType > storage_type
void ensure_can_interpolate_to_evaluated() const
std::optional< Bounds< float3 > > bounds_min_max(bool use_radius=true) const
AttributeAccessor attributes() const
bool is_single_type(CurveType type) const
void interpolate_to_evaluated(int curve_index, GSpan src, GMutableSpan dst) const
Span< float3 > evaluated_positions() const
VArray< float > radius() const
void count_memory(MemoryCounter &memory) const
MutableAttributeAccessor attributes_for_write()
std::unique_ptr< GreasePencilEditHints > grease_pencil_edit_hints_
std::optional< MutableSpan< float3 > > positions_for_write()
std::optional< Span< float3 > > positions() const
GSpanAttributeWriter lookup_or_add_for_write_span(StringRef name, AttrDomain domain, AttrType data_type, const AttributeInit &initializer=AttributeInitDefaultValue())
GSpanAttributeWriter lookup_for_write_span(StringRef name)
SharedCache< std::optional< FillCache > > fill_cache
SharedCache< Vector< float3 > > curve_plane_normals_cache
SharedCache< Vector< float4x2 > > curve_texture_matrices
SharedCache< std::optional< TriangleCache > > triangle_cache
VArray< ColorGeometry4f > vertex_colors() const
Drawing & operator=(const Drawing &other)
Span< float3 > curve_plane_normals() const
std::optional< GroupedSpan< int > > fills() const
MutableSpan< float > opacities_for_write()
Span< float4x2 > texture_matrices() const
MutableSpan< float > radii_for_write()
bke::CurvesGeometry & strokes_for_write()
const bke::CurvesGeometry & strokes() const
VArray< ColorGeometry4f > fill_colors() const
MutableSpan< ColorGeometry4f > fill_colors_for_write()
MutableSpan< ColorGeometry4f > vertex_colors_for_write()
void set_texture_matrices(Span< float4x2 > matrices, const IndexMask &selection)
GroupedSpan< float3 > intersection_points() const
TreeNode & add_node(TreeNode &node)
void move_node_down(TreeNode &node, int step=1)
bool unlink_node(TreeNode &link, bool keep_children=false)
const TreeNode * find_node_by_name(StringRef name) const
Span< const Layer * > layers() const
void add_node_before(TreeNode &node, TreeNode &link)
void add_node_after(TreeNode &node, TreeNode &link)
void move_node_up(TreeNode &node, int step=1)
void print_nodes(StringRef header) const
LayerGroup & operator=(const LayerGroup &other)
Span< const LayerGroup * > groups() const
Span< const TreeNode * > nodes() const
SharedCache< Vector< FramesMapKeyT > > sorted_keys_cache_
Map< FramesMapKeyT, GreasePencilFrame > frames_
SortedKeysIterator sorted_keys_iterator_at(int frame_number) const
StringRefNull parent_bone_name() const
int sorted_keys_index_at(int frame_number) const
float4x4 to_world_space(const Object &object) const
StringRefNull view_layer_name() const
void set_local_transform(const float4x4 &transform)
void set_view_layer_name(StringRef new_name)
bool remove_frame(FramesMapKeyT key)
const Map< FramesMapKeyT, GreasePencilFrame > & frames() const
GreasePencilFrame * add_frame(FramesMapKeyT key, int duration=0)
const GreasePencilFrame * frame_at(const int frame_number) const
bool has_drawing_at(const int frame_number) const
int drawing_index_at(const int frame_number) const
int get_frame_duration_at(const int frame_number) const
std::optional< int > start_frame_at(int frame_number) const
float4x4 to_object_space(const Object &object) const
Span< FramesMapKeyT > sorted_keys() const
Map< FramesMapKeyT, GreasePencilFrame > & frames_for_write()
void set_parent_bone_name(StringRef new_name)
const TreeNode * parent_node() const
const LayerGroup & as_group() const
const LayerGroup * parent_group() const
constexpr bool contains(const T &value) const
constexpr bool is_empty() const
constexpr int64_t size() const
constexpr const char * data() const
void foreach_segment(Fn &&fn, Mode mode=exec_mode::serial) const
void foreach_index(Fn &&fn, Mode mode=exec_mode::serial) const
IndexMask complement(const IndexMask &universe, LinearAllocator<> &memory) const
void to_bools(MutableSpan< bool > r_bools) const
void resize(const int64_t new_size)
MutableSpan< T > as_mutable_span()
#define offsetof(t, d)
#define rot(x, k)
#define storage(slot, qualifiers)
#define index(i)
#define layer
#define sin
#define cos
VecBase< float, D > normalize(VecOp< float, D >) RET
float dot(VecOp< float, D >, VecOp< float, D >) RET
VecBase< float, D > step(VecOp< float, D >, VecOp< float, D >) RET
MatBase< R, C > transpose(MatBase< C, R >) RET
VecBase< float, 3 > cross(VecOp< float, 3 >, VecOp< float, 3 >) RET
float length(VecOp< float, D >) RET
float2x2 from_scale(float2 scale)
float safe_rcp(float a)
float length_squared(VecT a)
#define T
void gather(const GVArray &src, const IndexMask &indices, GMutableSpan dst, exec_mode::Mode mode=exec_mode::parallel)
void copy_group_to_group(OffsetIndices< int > src_offsets, OffsetIndices< int > dst_offsets, const IndexMask &selection, GSpan src, GMutableSpan dst)
void scatter(const Span< T > src, const Span< IndexT > indices, MutableSpan< T > dst, const Mode mode={})
bool contains(const VArray< bool > &varray, const IndexMask &indices_to_check, bool value)
bool prop_is_animated(const AnimData *adt, StringRefNull rna_path, int array_index)
void gather(GSpan src, Span< int > map, GMutableSpan dst)
void ensure_non_empty_layer_names(Main &bmain, GreasePencil &grease_pencil)
static void update_curve_plane_normal_cache(const Span< float3 > positions, const OffsetIndices< int > points_by_curve, const IndexMask &curve_mask, MutableSpan< float3 > normals)
static void update_triangle_and_offsets_changed(const Span< float3 > positions, const Span< float3 > normals, const OffsetIndices< int > dst_points_by_curve, const IndexMask &changed_curves, const std::optional< GroupedSpan< int > > fills, const GroupedSpan< int3 > src_triangles, const GroupedSpan< float3 > src_intersection_points, Vector< int3 > &r_triangles, MutableSpan< int > r_triangle_offsets, Vector< float3 > &r_intersection_points, MutableSpan< int > r_intersection_point_offsets)
constexpr StringRef ATTR_RADIUS
std::optional< FillCache > fill_cache_from_fill_ids(const VArray< int > &fill_ids)
static void ensure_fill_cache(const Drawing &drawing)
static float4x2 get_local_to_stroke_matrix(const Span< float3 > positions, const float3 normal)
constexpr StringRef ATTR_VERTEX_COLOR
static float3x2 get_stroke_to_texture_matrix(const float uv_rotation, const float2 uv_translation, const float2 uv_scale)
const AttributeAccessorFunctions & get_attribute_accessor_functions()
static void ensure_triangle_cache(const Drawing &drawing)
constexpr StringRef ATTR_OPACITY
constexpr StringRef ATTR_FILL_COLOR
static IndexMask curves_to_fills_mask(const IndexMask &curve_mask, const std::optional< GroupedSpan< int > > fills, const int num_curves, IndexMaskMemory &memory)
static float4x3 expand_4x2_mat(const float4x2 &strokemat)
static void update_triangle_and_offsets_cache(const Span< float3 > positions, const Span< float3 > normals, const OffsetIndices< int > points_by_curve, const IndexMask &fill_mask, const GroupedSpan< int > fills, Vector< int3 > &r_triangles, MutableSpan< int > r_triangle_offsets, Vector< float3 > &r_intersection_points, MutableSpan< int > r_intersection_point_offsets)
void copy_drawing_array(Span< const GreasePencilDrawingBase * > src_drawings, MutableSpan< GreasePencilDrawingBase * > dst_drawings)
GMutableSpan get_mutable_attribute(AttributeStorage &storage, const AttrDomain domain, const CPPType &cpp_type, const StringRef name, const int64_t domain_size, const void *custom_default_value)
auto attribute_filter_from_skip_ref(const Span< StringRef > skip)
void fill_attribute_range_default(MutableAttributeAccessor dst_attributes, AttrDomain domain, const AttributeFilter &attribute_filter, IndexRange range)
ID * asset_edit_id_find_local(Main &global_main, ID &id)
void attribute_storage_blend_write_prepare(AttributeStorage &data, bool use_5_0_compatibility, FunctionRef< int(AttrDomain)> get_domain_size, AttributeStorage::BlendWriteData &write_data)
ID * asset_edit_id_ensure_local(Main &global_main, ID &id)
const CPPType & attribute_type_to_cpp_type(AttrType type)
Bounds< T > merge(const Bounds< T > &a, const Bounds< T > &b)
Definition BLI_bounds.hh:27
std::optional< Bounds< T > > min_max_with_radii(const Span< T > values, const Span< RadiusT > radii)
std::optional< Bounds< T > > min_max(const std::optional< Bounds< T > > &a, const T &b)
Definition BLI_bounds.hh:56
int size(const AssetLibraryReference *library_reference)
constexpr ParallelGrainSize grain_size(int grain_size)
const MultiFunction & lookup(UString id)
BLI_INLINE Texture * wrap(MTLTexture *texture)
T length_squared(const VecBase< T, Size > &a)
MatBase< T, NumCol, NumRow > transpose(const MatBase< T, NumRow, NumCol > &mat)
T safe_rcp(const T &a)
T sign(const T &a)
T distance(const T &a, const T &b)
T length(const VecBase< T, Size > &a)
QuaternionBase< T > normalize_and_get_length(const QuaternionBase< T > &q, T &out_length)
EulerXYZBase< float > EulerXYZ
CartesianBasis invert(const CartesianBasis &basis)
T atan2(const T &y, const T &x)
MatBase< T, NumCol, NumRow > normalize(const MatBase< T, NumCol, NumRow > &a)
T max(const T &a, const T &b)
void to_loc_rot_scale_safe(const MatBase< T, 4, 4 > &mat, VecBase< T, 3 > &r_location, RotationT &r_rotation, VecBase< T, 3 > &r_scale)
T determinant(const MatBase< T, Size, Size > &mat)
void transform_points(const float4x4 &transform, MutableSpan< float3 > points, bool use_threading=true)
MatT from_loc_rot_scale(const typename MatT::loc_type &location, const RotationT &rotation, const VecBase< typename MatT::base_type, ScaleDim > &scale)
VecBase< T, 3 > transform_point(const CartesianBasis &basis, const VecBase< T, 3 > &v)
OffsetIndices< int > accumulate_counts_to_offsets(MutableSpan< int > counts_to_offsets, int start_offset=0)
int sum_group_sizes(OffsetIndices< int > offsets, const IndexMask &mask)
OffsetIndices< int > gather_selected_offsets(OffsetIndices< int > src_offsets, const IndexMask &selection, int start_offset, MutableSpan< int > dst_offsets)
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
auto isolate_task(const Function &function)
Definition BLI_task.hh:224
BMesh Iterators.
void BLO_read_struct_with_type_size(BlendDataReader *reader, T **ptr_p, FunctionRef< size_t(const T &data)> type_size_fn)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
static void delete_drawing(GreasePencilDrawingBase *drawing_base)
__int64 int64_t
Definition BKE_text.h:90
void BKE_defbase_blend_write(BlendWriter *writer, const ListBaseT< bDeformGroup > *defbase)
Definition deform.cc:1597
MemArena * BLI_memarena_new(size_t bufsize, const char *name) ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL ATTR_NONNULL(2) ATTR_MALLOC
static void reorder_layer_data(GreasePencil &grease_pencil, const FunctionRef< void()> do_layer_order_changes)
bool BKE_grease_pencil_has_curve_with_type(const GreasePencil &grease_pencil, CurveType type)
void BKE_object_eval_grease_pencil(Depsgraph *depsgraph, Scene *scene, Object *object)
MINLINE void copy_v3_v3(float r[3], const float a[3])
unsigned int uint
Definition BKE_text.h:55
static void write_layer(BlendWriter *writer, GreasePencilLayer *node)
static Material * grease_pencil_object_material_ensure_from_brush_pinned(Main *bmain, Object *ob, Brush *brush)
short * BKE_object_material_len_p(Object *ob)
static void grease_pencil_replace_end_frames_after_read(GreasePencil &grease_pencil)
GreasePencil * BKE_grease_pencil_copy_for_eval(const GreasePencil *grease_pencil_src)
void BLO_read_pointer_array_and_validate_size(BlendDataReader *reader, T **ptr_p, SizeT *array_size)
static void grease_pencil_set_runtime_visibilities(ID &id_dst, GreasePencil &grease_pencil)
void id_us_plus(ID *id)
Definition lib_id.cc:433
Material * BKE_gpencil_material_add(Main *bmain, const char *name)
std::optional< std::string > RNA_path_from_ID_to_property(const PointerRNA *ptr, PropertyRNA *prop)
Definition rna_path.cc:1237
void(*) BKE_grease_pencil_batch_cache_dirty_tag_cb(GreasePencil *grease_pencil, int mode)
BLI_INLINE void BLI_listbase_clear(ListBase *lb)
void void void void void void BLI_duplicatelist(ListBase *dst, const ListBase *src) ATTR_NONNULL(1
Definition listbase.cc:834
float mat4_to_scale(const float mat[4][4])
bool BKE_object_material_slot_add(Main *bmain, Object *ob, bool set_active=true)
Material * BKE_object_material_get(Object *ob, short act)
MatBase< double, 4, 2 > double4x2
void BKE_grease_pencil_copy_layer_group_parameters(const bke::greasepencil::LayerGroup &src, bke::greasepencil::LayerGroup &dst)
static void write_drawing_array(GreasePencil &grease_pencil, ResourceScope &scope, BlendWriter *writer)
void BKE_object_eval_assign_data(Object *object, ID *data, bool is_owned)
Definition object.cc:1786
bool BKE_grease_pencil_drawing_attribute_required(const GreasePencilDrawing *, StringRef name)
MatBase< float, 2, 2 > float2x2
@ CDT_INSIDE_WITH_HOLES
std::string RNA_path_name_to_infix(const StringRefNull string)
Definition rna_path.cc:1419
@ eModifierType_GreasePencilOffset
@ eModifierType_GreasePencilMultiply
@ eModifierType_GreasePencilArray
@ eModifierType_GreasePencilThickness
@ eModifierType_GreasePencilSubdiv
@ eModifierType_GreasePencilShrinkwrap
@ eModifierType_GreasePencilDash
@ eModifierType_GreasePencilBuild
@ eModifierType_GreasePencilWeightAngle
@ eModifierType_GreasePencilColor
@ eModifierType_GreasePencilLineart
@ eModifierType_GreasePencilHook
@ eModifierType_GreasePencilMirror
@ eModifierType_GreasePencilLattice
@ eModifierType_GreasePencilSmooth
@ eModifierType_GreasePencilTexture
@ eModifierType_GreasePencilArmature
@ eModifierType_GreasePencilTime
@ eModifierType_GreasePencilOpacity
@ eModifierType_GreasePencilOutline
@ eModifierType_GreasePencilTint
@ eModifierType_GreasePencilNoise
@ eModifierType_GreasePencilSimplify
@ eModifierType_GreasePencilLength
@ eModifierType_GreasePencilEnvelope
@ eModifierType_GreasePencilWeightProximity
VecBase< double, 2 > double2
void mul_v2_m3v3(float r[2], const float M[3][3], const float a[3])
static std::string unique_node_name(const GreasePencil &grease_pencil, const StringRef name)
void * BLI_findstring(const ListBase *listbase, const char *id, int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:615
static void read_layer_tree_group(BlendDataReader *reader, GreasePencilLayerTreeGroup *node, GreasePencilLayerTreeGroup *parent)
char * BLI_strdupn(const char *str, size_t len) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
void BKE_grease_pencil_point_coords_get(const GreasePencil &grease_pencil, MutableSpan< float3 > all_positions, MutableSpan< float > all_radii)
void BLI_polyfill_calc_arena(const float(*coords)[2], unsigned int coords_num, int coords_sign, unsigned int(*r_tris)[3], struct MemArena *arena)
void BKE_object_material_assign(Main *bmain, Object *ob, Material *ma, short act, int assign_type)
void BLO_read_data_invalidate(BlendDataReader *reader, const char *message)
Definition readfile.cc:6839
static size_t drawing_struct_size(const GreasePencilDrawingType type)
static void write_layer_tree(GreasePencil &grease_pencil, BlendWriter *writer)
MatBase< float, 4, 4 > float4x4
const char * BKE_id_name(const ID &id)
Material * BKE_material_default_gpencil()
static void shrink_array(T **array, int *num, const int shrink_num)
MatBase< float, 2, 4 > float2x4
void BKE_id_blend_write(BlendWriter *writer, ID *id)
Definition lib_id.cc:2890
void BKE_grease_pencil_copy_layer_parameters(const bke::greasepencil::Layer &src, bke::greasepencil::Layer &dst)
GreasePencil * BKE_grease_pencil_add(Main *bmain, const char *name)
@ LIB_ID_COPY_LOCALIZE
static size_t layer_tree_node_struct_size(const GreasePencilLayerTreeNodeType type)
static bool grease_pencil_initialize_drawing_user_counts(GreasePencil &grease_pencil)
bool BKE_grease_pencil_material_index_used(GreasePencil *grease_pencil, int index)
void BKE_animdata_fix_paths(ID &id, StringRef prefix, StringRef old_infix, StringRef new_infix, bool verify_paths, const DriverMap &driver_map)
void BKE_brush_tag_unsaved_changes(Brush *brush)
Definition brush.cc:843
VecBase< float, 4 > float4
static void shrink_attribute_storage(bke::AttributeStorage &storage, const int index_to_remove, const int size)
MatBase< double, 3, 4 > double3x4
void BKE_grease_pencil_point_coords_apply_with_mat4(GreasePencil &grease_pencil, Span< float3 > all_positions, Span< float > all_radii, const float4x4 &mat)
static void read_drawing_array(GreasePencil &grease_pencil, BlendDataReader *reader)
size_t void BLI_uniquename_cb(FunctionRef< bool(StringRefNull)> unique_check, const char *defname, char delim, char *name, size_t name_maxncpy) ATTR_NONNULL(2
Material * BKE_grease_pencil_object_material_new(Main *bmain, Object *ob, const char *name, int *r_index)
unsigned int uint32_t
Definition BKE_text.h:81
static void grow_array(T **array, int *num, const int add_num)
void BKE_grease_pencil_eval_geometry(Depsgraph *depsgraph, GreasePencil *grease_pencil)
void BKE_grease_pencil_nomain_to_grease_pencil(GreasePencil *grease_pencil_src, GreasePencil *grease_pencil_dst)
int BLI_findindex(const ListBase *listbase, const void *vlink) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
Definition listbase.cc:593
void BKE_grease_pencil_batch_cache_dirty_tag(GreasePencil *grease_pencil, int mode)
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
MatView< float, 4, 4, 4, 4, 0, 0, alignof(float)> float4x4_view
VecBase< float, 2 > float2
VecBase< int32_t, 3 > int3
static void read_layer_tree(GreasePencil &grease_pencil, BlendDataReader *reader)
void BKE_grease_pencil_duplicate_drawing_array(const GreasePencil *grease_pencil_src, GreasePencil *grease_pencil_dst)
int BKE_grease_pencil_object_material_index_get_by_name(Object *ob, const char *name)
static void grease_pencil_foreach_id(ID *id, LibraryForeachIDData *data)
void BKE_object_free_derived_caches(Object *ob)
Definition object.cc:1810
void CustomData_reset(CustomData *data)
void BLI_remlink(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:138
void DEG_id_tag_update(ID *id, unsigned int flags)
@ OB_MODE_VERTEX_GREASE_PENCIL
@ OB_MODE_SCULPT_GREASE_PENCIL
@ OB_MODE_WEIGHT_GREASE_PENCIL
BMesh const char void * data
void BLI_insertlinkafter(ListBase *listbase, void *vprevlink, void *vnewlink) ATTR_NONNULL(1)
Definition listbase.cc:339
void BKE_grease_pencil_brush_material_set(struct Brush *brush, struct Material *material)
static std::string unique_layer_group_name(const GreasePencil &grease_pencil, StringRef name)
void BKE_animdata_free(ID *id, bool do_id_user)
Definition anim_data.cc:174
IDTypeInfo IDType_ID_GP
@ MOD_APPLY_USECACHE
void BLI_memarena_clear(MemArena *ma) ATTR_NONNULL(1)
MatBase< float, 4, 2 > float4x2
static GreasePencilModifierInfluenceData * influence_data_from_modifier(ModifierData *md)
BLI_INLINE void IMB_colormanagement_srgb_to_scene_linear_v3(float scene_linear[3], const float srgb[3])
@ BKE_MAT_ASSIGN_USERPREF
void BKE_grease_pencil_material_index_remove(GreasePencil *grease_pencil, int index)
void(*) BKE_grease_pencil_batch_cache_free_cb(GreasePencil *grease_pencil)
void BKE_grease_pencil_copy_parameters(const GreasePencil &src, GreasePencil &dst)
static void grease_pencil_evaluate_layers(GreasePencil &grease_pencil)
ModifierData * BKE_modifiers_get_virtual_modifierlist(const Object *ob, VirtualModifierData *data)
Material * BKE_grease_pencil_object_material_ensure_by_name(Main *bmain, Object *ob, const char *name, int *r_index)
void BLO_read_struct_list_with_type_size(BlendDataReader *reader, size_t base_size, ListBase *list, FunctionRef< size_t(const void *data)> type_size_fn)
Definition readfile.cc:6591
MatBase< float, 3, 2 > float3x2
static void grease_pencil_do_layer_adjustments(GreasePencil &grease_pencil)
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
void BKE_grease_pencil_vgroup_name_update(Object *ob, const char *old_name, const char *new_name)
void unit_m4(float m[4][4])
PointerRNA RNA_pointer_create_discrete(ID *id, StructRNA *type, void *data)
PropertyRNA * RNA_struct_type_find_property(StructRNA *srna, const char *identifier)
static void reorder_attribute_domain(bke::AttributeStorage &data, const bke::AttrDomain domain, const Span< int > new_by_old_map)
bool BKE_grease_pencil_references_cyclic_check(const GreasePencil *id_reference, const GreasePencil *grease_pencil)
int BKE_object_material_index_get(Object *ob, const Material *ma)
void BKE_modifiers_clear_errors(Object *ob)
MatBase< float, 4, 3 > float4x3
ATTR_WARN_UNUSED_RESULT const size_t num
MINLINE void zero_v3(float r[3])
MatBase< float, 3, 3 > float3x3
void BKE_id_free(Main *bmain, void *idv)
eEvaluationMode DEG_get_mode(const Depsgraph *graph)
void BLI_insertlinkbefore(ListBase *listbase, void *vnextlink, void *vnewlink) ATTR_NONNULL(1)
Definition listbase.cc:378
bool BLO_read_array(BlendDataReader *reader, T **ptr_p, const SizeT array_size, const int elems=1)
PaletteColor * BKE_palette_color_add(Palette *palette)
bool BKE_object_is_in_editmode(const Object *ob)
Definition object.cc:1898
void * BKE_id_new_nomain(short type, const char *name)
Definition lib_id.cc:1617
void * BLI_memarena_alloc(MemArena *ma, size_t size) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1) ATTR_MALLOC ATTR_ALLOC_SIZE(2)
static void grease_pencil_foreach_working_space_color(ID *id, const IDTypeForeachColorFunctionCallback &fn)
static void read_layer(BlendDataReader *reader, GreasePencilLayer *node, GreasePencilLayerTreeGroup *parent)
static void write_layer_tree_group(BlendWriter *writer, GreasePencilLayerTreeGroup *node)
T * DEG_get_original(T *id)
void BLI_addtail(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:118
void BKE_grease_pencil_point_coords_apply(GreasePencil &grease_pencil, Span< float3 > all_positions, Span< float > all_radii)
char * BLI_strdup(const char *str) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1) ATTR_MALLOC
MINLINE void copy_v3_fl(float r[3], float f)
static VectorSet< StringRef > get_node_names(const GreasePencil &grease_pencil)
@ INDEX_ID_GP
Definition DNA_ID.h:1338
iter begin(iter)
static void free_drawing_array(GreasePencil &grease_pencil)
MINLINE void add_newell_cross_v3_v3v3(float n[3], const float v_prev[3], const float v_curr[3])
static void grease_pencil_init_data(ID *id)
short BKE_object_material_slot_find_index(Object *ob, Material *ma)
void hex_to_rgb(const char *hexcol, float *r_r, float *r_g, float *r_b)
static void update_active_node_from_node_to_remove(GreasePencil &grease_pencil, const bke::greasepencil::TreeNode &node)
Material * BKE_grease_pencil_object_material_from_brush_get(Object *ob, const Brush *brush)
@ ID_RECALC_GEOMETRY
Definition DNA_ID.h:1074
void BKE_defgroup_copy_list(ListBaseT< bDeformGroup > *outbase, const ListBaseT< bDeformGroup > *inbase)
Definition deform.cc:75
static CLG_LogRef LOG
Definition logging.cpp:12
Material * BKE_grease_pencil_object_material_ensure_from_brush(Main *bmain, Object *ob, Brush *brush)
static void grease_pencil_evaluate_modifiers(Depsgraph *depsgraph, Scene *scene, Object *object, bke::GeometrySet &geometry_set)
bool BLI_remlink_safe(ListBase *listbase, void *vlink) ATTR_NONNULL(1)
Definition listbase.cc:161
void uninitialized_relocate_n(T *src, int64_t n, T *dst)
static void grease_pencil_blend_read_data(BlendDataReader *reader, ID *id)
char * BLI_strdup_null(const char *str) ATTR_WARN_UNUSED_RESULT ATTR_MALLOC
ColorSceneLinear4f< eAlpha::Premultiplied > ColorGeometry4f
static const char * ATTR_POSITION
ID * BKE_id_copy_ex(Main *bmain, const ID *id, ID **new_id_p, int flag)
Definition lib_id.cc:851
void copy_m4_m4(float m1[4][4], const float m2[4][4])
VecBase< float, 3 > float3
static bool grease_pencil_references_cyclic_check_internal(const GreasePencil *id_reference, const GreasePencil *grease_pencil)
MatBase< double, 4, 3 > double4x3
bool DEG_is_evaluated(const T *id)
@ GP_BRUSH_MATERIAL_PINNED
void BKE_grease_pencil_material_remap(GreasePencil *grease_pencil, const uint *remap, int totcol)
static void grease_pencil_blend_write(BlendWriter *writer, ID *id, const void *id_address)
bool BKE_modifier_is_enabled(const Scene *scene, ModifierData *md, int required_mode)
static void grease_pencil_free_data(ID *id)
void id_us_min(ID *id)
Definition lib_id.cc:441
float DEG_get_ctime(const Depsgraph *graph)
const ModifierTypeInfo * BKE_modifier_get_info(ModifierType type)
void * BKE_id_new(Main *bmain, short type, const char *name)
Definition lib_id.cc:1612
void BKE_paint_palette_set(Paint *paint, Palette *palette)
bPoseChannel * BKE_pose_channel_find_name(const bPose *pose, const char *name)
GreasePencil * BKE_grease_pencil_new_nomain()
void BLO_read_string(BlendDataReader *reader, char **ptr_p)
Definition readfile.cc:6653
static void grease_pencil_copy_data(Main *, std::optional< Library * >, ID *id_dst, const ID *id_src, const int)
signed char int8_t
Definition BKE_text.h:76
int BKE_grease_pencil_stroke_point_count(const GreasePencil &grease_pencil)
void axis_dominant_v3_to_m3(float r_mat[3][3], const float normal[3])
Normal to x,y matrix.
void BLI_memarena_free(MemArena *ma) ATTR_NONNULL(1)
void uninitialized_move_n(T *src, int64_t n, T *dst)
Material * BKE_grease_pencil_object_material_alt_ensure_from_brush(Main *bmain, Object *ob, Brush *brush)
void void void bool BLI_listbase_link_move(ListBase *listbase, void *vlink, int step) ATTR_NONNULL()
Definition listbase.cc:443
void * MEM_new_array_zeroed(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
Palette * BKE_palette_add(Main *bmain, const char *name)
void CustomData_blend_read(BlendDataReader *reader, CustomData *data, int count)
void BKE_grease_pencil_batch_cache_free(GreasePencil *grease_pencil)
void BKE_grease_pencil_palette_ensure(Main *bmain, Scene *scene)
@ IDTYPE_FLAGS_APPEND_IS_REUSABLE
Definition BKE_idtype.hh:50
void mask(PageMask &srt, TileMaps &tilemaps, const uint3 global_id, const uint local_tile_index)
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
void write_pointer_array(int64_t num, const void *data)
void generated_pointer_tag(const void *data)
void write_string(const char *data)
void write_struct_at_address_cast(const void *address, const void *data, BlendStructWriterTypedFn< T > fn=nullptr)
void write_id_struct(const void *id_address, const T *id, BlendStructWriterTypedFn< T > fn=nullptr)
void write_struct_list(const ListBaseT< T > *list, BlendStructWriterTypedFn< T > fn=nullptr)
void write_struct(const T *data, BlendStructWriterTypedFn< T > fn=nullptr)
bool is_undo() const
void write_struct_array(const int64_t array_size, const T *data, BlendStructWriterTypedFn< T > fn=nullptr)
void write_int32_array(int64_t num, const int32_t *data)
void pad(const PaddingT &padding)
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
bke::greasepencil::DrawingRuntime * runtime
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilLayerFramesMapStorageFlag flag
bke::greasepencil::LayerGroupRuntime * runtime
ListBaseT< GreasePencilLayerTreeNode > children
struct GreasePencilLayerTreeNode * next
struct GreasePencilLayerTreeNode * prev
struct GreasePencilLayerTreeGroup * parent
GreasePencilLayerTreeNode base
ListBaseT< GreasePencilLayerMask > masks
GreasePencilLayerFramesMapStorage frames_storage
bke::greasepencil::LayerRuntime * runtime
GreasePencilLayerBlendMode blend_mode
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
GreasePencilModifierInfluenceData influence
ListBaseT< Palette > palettes
Definition BKE_main.hh:412
ListBaseT< Object > objects
Definition BKE_main.hh:388
const c_style_mat & ptr() const
struct ModifierData * next
void(*) modify_geometry_set(ModifierData *md, const ModifierEvalContext *ctx, bke::GeometrySet *geometry_set)
struct bPose * pose
struct Palette * palette
struct ToolSettings * toolsettings
GpVertexPaint * gp_vertexpaint
static ArrayData from_uninitialized(const CPPType &type, int64_t domain_size)
static ArrayData from_constructed(const CPPType &type, int64_t domain_size)
GeometryComponent & get_component_for_write(GeometryComponent::Type component_type)
static GeometrySet from_grease_pencil(GreasePencil *grease_pencil, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
const GreasePencil * get_grease_pencil() const
GreasePencil * get_grease_pencil_for_write()
void replace_grease_pencil(GreasePencil *grease_pencil, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
float w
Definition sky_math.h:225
#define N_(msgid)