Blender V5.3
node_geo_xpbd_solver.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
5#include <fmt/format.h>
6
7#include "BKE_bvh.hh"
8#include "BKE_bvhutils.hh"
9#include "BKE_curves.hh"
11#include "BKE_grease_pencil.hh"
12#include "BKE_instances.hh"
13#include "BKE_lib_id.hh"
14#include "BKE_mesh.h"
15#include "BKE_mesh_mapping.hh"
16#include "BKE_mesh_sample.hh"
17#include "BKE_pointcloud.hh"
18
19#include "BLI_math_geom_c.hh"
20#include "BLI_stack.hh"
21#include "BLI_string_utf8.hh"
23
24#include "DNA_curves_types.h"
25#include "DNA_mesh_types.h"
26
38
39#include "NOD_geo_tag_filter.hh"
43
44#include "node_geometry_util.hh"
45
47
48using namespace physics_bundles;
49
50namespace attribute_names {
51
52constexpr StringRefNull position = "position";
53constexpr StringRefNull velocity = "velocity";
54constexpr StringRefNull rotation = "rotation";
55constexpr StringRefNull angular_velocity = "angular_velocity";
56constexpr StringRefNull external_force = "external_force";
57constexpr StringRefNull external_torque = "external_torque";
58constexpr StringRefNull mass = "mass";
59constexpr StringRefNull moment_of_inertia = "moment_of_inertia";
60constexpr StringRefNull static_friction = "static_friction";
61constexpr StringRefNull dynamic_friction = "dynamic_friction";
62constexpr StringRefNull radius = "radius";
63
64} // namespace attribute_names
65
67 public:
68 static constexpr StringRefNull name = "Blender.XPBDSolverData";
69 static const FlatBundleTypePtr &get_bundle_type();
70};
71
73{
74 static const FlatBundleTypePtr bundle_type = []() {
76 b.add<decl::Float>("residual_error"_ustr)
77 .min(0.0f)
78 .description(
79 "Average remaining relative error, values smaller than one are below the constraint "
80 "threshold.");
81 const FlatBundleTypePtr bundle_type = b.build();
83 return bundle_type;
84 }();
85 return bundle_type;
86}
87
112
114{
115 b.use_custom_socket_order();
116 b.allow_any_socket_order();
117
118 static NestedBundleTypePtr world_type = make_world_type();
119 b.add_input<decl::Bundle>("World"_ustr)
120 .bundle_type(world_type)
121 .evaluated_geometry_field()
122 .structure_type(StructureType::Single)
123 .description("World state that is updated by the solver");
124 b.add_output<decl::Bundle>("World"_ustr).pass_through_input_index(0).align_with_previous();
125 b.add_input<decl::Float>("Delta Time"_ustr)
126 .min(0)
127 .default_value(1 / 25.0f)
128 .subtype(PROP_TIME_ABSOLUTE);
129
130 b.add_input<decl::String>("Filter"_ustr)
131 .optional_label()
132 .description("Filters the geometry sets to process based on their tags");
133
134 b.add_input<decl::Matrix>("Simulation to World"_ustr);
135
136 {
137 auto &solver_panel = b.add_panel("Solver"_ustr).default_closed(true);
138 solver_panel.add_input<decl::Int>("Substeps"_ustr).default_value(10).min(1);
139 solver_panel.add_input<decl::Int>("Constraint Iterations"_ustr).default_value(1).min(1);
140 solver_panel.add_input<decl::String>("Solver Path"_ustr)
141 .default_value("")
142 .description("Optional output path in the world bundle for solver data");
143 }
144 {
145 auto &p = b.add_panel("Interpolation Range"_ustr).default_closed(true);
146 p.add_input<decl::Float>("Begin"_ustr).default_value(0.0).min(0.0);
147 p.add_input<decl::Float>("End"_ustr).default_value(1.0).min(0.0);
148 }
149}
150
151struct DataKey {
154 std::optional<int> layer_i;
155
157 {
158 return get_default_hash(this->geo_bundle_i, this->type, this->layer_i.value_or(0));
159 }
160
161 friend bool operator==(const DataKey &a, const DataKey &b) = default;
162};
163
168 std::optional<IndexRange> curves_range;
169};
170
172 std::string path;
173};
182
184 std::string path;
186 std::string lambda_pos_attr;
187 std::string lambda_rot_attr;
188};
198
200 std::string path;
202};
210
212 std::string path;
214 std::string lambda_attr;
215};
233
235 std::string path;
237};
255
257 std::string path;
259};
270
272 std::string path;
274};
286
292
303
305 std::string path;
307 std::variant<StaticMeshInfo, DeformingMeshInfo> mesh;
310 float margin;
311 float friction;
317};
322
324 std::string path;
325};
326
331
335 int size;
336 bool uses_rotation = false;
339
346
351
358
361
364
368
373
376
378
387
389
391};
392
402
426
431
432 SubstepInterval(const int substeps,
433 const int current_i,
434 const float interpolation_begin,
435 const float interpolation_end)
437 interpolate_begin(float(current_i) / substeps * (interpolation_end - interpolation_begin) +
438 interpolation_begin),
439 interpolate_end(float(current_i + 1) / substeps *
440 (interpolation_end - interpolation_begin) +
441 interpolation_begin)
442 {
443 }
444};
445
449
451 {
452 return get_default_hash(this->mesh_collider_i, this->point_i);
453 }
454
455 friend bool operator==(const MeshContactId &a, const MeshContactId &b) = default;
456};
457
460
464 /* The movement of the collider in the current substep. */
473
477
479 const std::optional<int> &prev_i)
480 {
481 if (prev_i) {
482 this->active_states.append(prev_contacts.active_states[*prev_i]);
483 this->lambdas_normal.append(prev_contacts.lambdas_normal[*prev_i]);
484 this->lambdas_friction.append(prev_contacts.lambdas_friction[*prev_i]);
485 }
486 else {
487 this->active_states.append(false);
488 this->lambdas_normal.append(0.0f);
489 this->lambdas_friction.append(0.0f);
490 }
491 }
492};
493
496
500 /* The movement of the collider in the current substep. */
510
515
517 const std::optional<int> &prev_i)
518 {
519 if (prev_i) {
520 this->active_states.append(prev_contacts.active_states[*prev_i]);
521 this->point_mix_factors.append(prev_contacts.point_mix_factors[*prev_i]);
522 this->lambdas_normal.append(prev_contacts.lambdas_normal[*prev_i]);
523 this->lambdas_friction.append(prev_contacts.lambdas_friction[*prev_i]);
524 }
525 else {
526 this->active_states.append(false);
527 this->point_mix_factors.append(0.0f);
528 this->lambdas_normal.append(0.0f);
529 this->lambdas_friction.append(0.0f);
530 }
531 }
532};
533
544
556
558 public:
559 struct Result {
560 /* Average relative residual error of all constraints. The average absolute error of a specific
561 * constraint type is scaled by a threshold value, anything below the threshold is considered
562 * "solved". This allows combining constraint residuals of different types into a single value.
563 */
565 };
566
567 private:
568 struct TLS {
569 ResourceScope scope;
570 LinearAllocator<> &allocator;
571
572 TLS() : scope(1024), allocator(scope.allocator()) {}
573 };
574
576
578 Bundle &world_;
579
580 const int substeps_;
581 const float sub_delta_time_;
582 float substep_compliance_factor_;
583
584 const float interpolation_begin_;
585 const float interpolation_end_;
586
587 const float4x4 world_to_simulation_;
588
589 std::string geometry_tag_filter_;
590
591 int constraint_iterations_;
592
593 Geometries geometries_;
594 ConstraintsInfo constraints_;
595 Array<ChunkData> chunks_data_;
596
597 Result result_;
598 Mutex warnings_mutex_;
600
601 MultiValueMap<std::string, std::string> nested_bundle_paths_;
602
603 public:
605 const float total_delta_time,
606 const int substeps,
607 const int constraint_iterations,
608 const float interpolation_begin,
609 const float interpolation_end,
610 const StringRef geometry_tag_filter,
611 const float4x4 &simulation_to_world)
612 : world_(world),
613 substeps_(substeps),
614 sub_delta_time_(total_delta_time / substeps_),
615 interpolation_begin_(interpolation_begin),
616 interpolation_end_(interpolation_end),
617 world_to_simulation_(math::invert(simulation_to_world)),
618 geometry_tag_filter_(geometry_tag_filter),
619 constraint_iterations_(constraint_iterations)
620 {
621 substep_compliance_factor_ = math::safe_rcp(pow2f(sub_delta_time_));
622 }
623
624 void do_step()
625 {
626 this->gather_nested_bundle_paths();
627 this->gather_from_world__geometries();
628 this->prepare_geometry_chunks();
629 this->prepare_inverse_masses();
630 this->prepare_inverse_moments_of_inertia();
631
632 this->gather_from_world__mesh_colliders();
633 this->gather_from_world__stretch_shear_constraints();
634 this->gather_from_world__bend_twist_constraints();
635 this->gather_from_world__edge_length_constraints();
636 this->gather_from_world__cross_edge_length_constraints();
637 this->gather_from_world__damping();
638 this->gather_from_world__pin_positions();
639 this->gather_from_world__pin_rotations();
640 this->gather_from_world__collision_contacts();
641
642 this->parallel_for_each_chunk(32, [&](const int chunk_i) {
643 TLS &tls = tls_.local();
644 this->create_chunk_constraints__rod_stretch_shear(tls, chunk_i);
645 this->create_chunk_constraints__rod_bend_twist(tls, chunk_i);
646 this->create_chunk_constraints__damping(tls, chunk_i);
647 this->create_chunk_constraints__pin_positions(tls, chunk_i);
648 this->create_chunk_constraints__pin_rotations(tls, chunk_i);
649 });
650
651 result_ = this->do_simulation();
652
653 this->write_back__pin_positions();
654 this->write_back__rod_stretch_shear();
655
656 this->finish_common_attribute_writers();
657 this->write_back_geometries_to_world();
658
659 this->write_back__contacts();
660 }
661
662 const Result &result() const
663 {
664 return result_;
665 }
666
668 {
669 return warnings_;
670 }
671
672 private:
673 static float error_scale_from_threshold(const float error_threshold)
674 {
675 return 1.0f / std::max(math::square(error_threshold), 1e-12f);
676 }
677
678 void gather_nested_bundle_paths()
679 {
681 [&](const Span<BundleKey> path, const BundleItemValue &value) {
682 const BundlePtr *bundle_ptr = value.as_pointer<BundlePtr>();
683 if (!bundle_ptr || !*bundle_ptr) {
684 return;
685 }
686 const Bundle &bundle = **bundle_ptr;
687 const std::optional<StringRef> type = bundle.type();
688 if (!type.has_value()) {
689 return;
690 }
691 nested_bundle_paths_.add_as(*type, Bundle::combine_path(path));
692 });
693 /* Ensure the order is deterministic. */
694 for (MutableSpan<std::string> paths : nested_bundle_paths_.values()) {
695 std::ranges::sort(paths);
696 }
697 }
698
699 void gather_from_world__geometries()
700 {
701 TLS &tls = tls_.local();
702 /* Gather geometry sets to process from the world. */
703 Vector<std::string> paths = gather_bundle_paths_by_data_type(world_, SOCK_GEOMETRY);
704 /* Ensure the order is deterministic. */
705 std::ranges::sort(paths);
706 for (const StringRef path : paths) {
707 GeometrySet &geometry = *world_.lookup_path_for_write_ptr<GeometrySet>(path);
708 Set<std::string> tags;
709 if (geometry.has_bundle()) {
710 const Bundle &bundle_in_geo = *geometry.bundle();
711 if (const std::optional<GListPtr> tags_list_ptr = bundle_in_geo.lookup_path<GListPtr>(
712 "tags"))
713 {
714 if (*tags_list_ptr) {
715 const GList &tags_list = **tags_list_ptr;
716 if (tags_list.cpp_type().is<std::string>()) {
717 tags_list.typed<std::string>().foreach(
718 [&](const std::string &tag) { tags.add(tag); });
719 }
720 }
721 }
722 }
723 if (!tag_filter_matches(geometry_tag_filter_, tags)) {
724 continue;
725 }
726
727 GeometrySetData geo_set_data;
728 geo_set_data.path = path;
729 geo_set_data.geometry = std::move(geometry);
730 geo_set_data.tags = std::move(tags);
731 geometries_.geometry_sets.append(std::move(geo_set_data));
732 }
733
734 /* Gather individual components that should be simulated. There may be more than geometry sets
735 * because each geometry set could contain e.g. a mesh and curves. */
736 for (const int geo_bundle_i : geometries_.geometry_sets.index_range()) {
737 GeometrySetData &geo_set_data = geometries_.geometry_sets[geo_bundle_i];
738 GeometrySet &geometry = geo_set_data.geometry;
743 {
744 if (!geometry.has(type)) {
745 continue;
746 }
747 bke::GeometryComponent &component = geometry.get_component_for_write(type);
748 geometries_.data_keys.add_new({geo_bundle_i, type, std::nullopt});
749 GeometryData &geo_data = tls.scope.construct<GeometryData>(
750 *component.attributes_for_write());
751 geo_data.curves = type == bke::GeometryComponent::Type::Curve ?
752 &geometry.get_curves_for_write()->geometry.wrap() :
753 nullptr;
754 geo_data.domain = type == bke::GeometryComponent::Type::Instance ? AttrDomain::Instance :
755 AttrDomain::Point;
756 geometries_.data.append(&geo_data);
757 }
758 if (geometry.has_grease_pencil()) {
759 using namespace blender::bke::greasepencil;
760 GreasePencil &grease_pencil = *geometry.get_grease_pencil_for_write();
761 for (const int layer_i : grease_pencil.layers().index_range()) {
762 Layer &layer = grease_pencil.layer(layer_i);
763 Drawing *drawing = grease_pencil.get_eval_drawing(layer);
764 if (!drawing) {
765 continue;
766 }
767 bke::CurvesGeometry &curves = drawing->strokes_for_write();
768 geometries_.data_keys.add_new(
769 {geo_bundle_i, bke::GeometryComponent::Type::Curve, layer_i});
770 GeometryData &geo_data = tls.scope.construct<GeometryData>(
771 curves.attributes_for_write());
772 geo_data.domain = AttrDomain::Point;
773 geo_data.curves = &curves;
774 geometries_.data.append(&geo_data);
775 }
776 }
777 }
778 geometries_.total_points_num = 0;
779 for (const int data_key_i : geometries_.data_keys.index_range()) {
780 GeometryData &geo_data = *geometries_.data[data_key_i];
781 const AttrDomain domain = geo_data.domain;
782 geo_data.size = geo_data.attributes.domain_size(domain);
783 geometries_.total_points_num += geo_data.size;
784 geo_data.temp_positions.reinitialize(geo_data.size);
785 geo_data.temp_rotations.reinitialize(geo_data.size);
786 geo_data.position_attr = this->ensure_attribute<float3>(
787 geo_data.attributes, attribute_names::position, domain);
788 geo_data.velocity_attr = this->ensure_attribute<float3>(
789 geo_data.attributes, attribute_names::velocity, domain);
790 geo_data.external_force_attr = this->lookup_attribute_default<float3>(
791 data_key_i, attribute_names::external_force, domain, float3(0, 0, 0));
792 geo_data.masses = this->lookup_attribute_default<float>(
793 data_key_i, attribute_names::mass, domain, 1.0f);
794
795 geo_data.is_hard_pinned.reinitialize(geo_data.size);
796 geo_data.is_hard_pinned.fill(false);
797 if (geo_data.attributes.contains(attribute_names::rotation)) {
798 geo_data.uses_rotation = true;
799 geo_data.rotation_attr = this->ensure_attribute<math::Quaternion>(
800 geo_data.attributes, attribute_names::rotation, domain);
801 geo_data.angular_velocity_attr = this->ensure_attribute<float3>(
802 geo_data.attributes, attribute_names::angular_velocity, domain);
803 geo_data.external_torque_attr = this->lookup_attribute_default<float3>(
804 data_key_i, attribute_names::external_torque, domain, float3(0, 0, 0));
805 geo_data.moments_of_inertia = this->lookup_attribute_default<float3>(
806 data_key_i, attribute_names::moment_of_inertia, domain, float3(1.0f));
807 }
808 }
809 }
810
811 void ensure_friction_loaded(const int data_key_i)
812 {
813 GeometryData &geo_data = *geometries_.data[data_key_i];
814 geo_data.load_friction_mutex.ensure([&]() {
815 geo_data.static_frictions = this->lookup_attribute_default<float>(
816 data_key_i, attribute_names::static_friction, geo_data.domain, 0.0f);
817 geo_data.dynamic_frictions = this->lookup_attribute_default<float>(
818 data_key_i, attribute_names::dynamic_friction, geo_data.domain, 0.0f);
819 });
820 }
821
822 void ensure_radius_loaded(const int data_key_i)
823 {
824 GeometryData &geo_data = *geometries_.data[data_key_i];
825 geo_data.load_radius_mutex.ensure([&]() {
826 geo_data.radii = this->lookup_attribute_default<float>(
827 data_key_i, attribute_names::radius, geo_data.domain, 0.0f);
828 geo_data.prev_radii = geo_data.radii;
829 });
830 }
831
832 void gather_from_world__mesh_colliders()
833 {
834 const Span<std::string> paths = nested_bundle_paths_.lookup_as(MeshColliderBundle::name);
835 for (const StringRef path : paths) {
836 const BundlePtr *bundle_ptr = world_.lookup_path_ptr<BundlePtr>(path);
837 if (!bundle_ptr || !*bundle_ptr) {
838 continue;
839 }
840 const Bundle &bundle = **bundle_ptr;
841 const Bundle *previous_bundle = this->get_previous_bundle(bundle);
842 const bke::GeometrySet *geometry = bundle.lookup_ptr<bke::GeometrySet>(
843 *BundleKey::from_str("geometry"));
844 const float margin = bundle.lookup<float>(*BundleKey::from_str("margin")).value_or(0.0f);
845 const float friction = bundle.lookup<float>(*BundleKey::from_str("friction")).value_or(0.0f);
846 const float compliance =
847 bundle.lookup<float>(*BundleKey::from_str("compliance")).value_or(0.0f);
848 const bool deforming =
849 bundle.lookup<bool>(*BundleKey::from_str("deforming")).value_or(false);
850 const bool use_edge_contacts =
851 bundle.lookup<bool>(*BundleKey::from_str("use_edge_contacts")).value_or(false);
852 const bool is_boundary =
853 bundle.lookup<bool>(*BundleKey::from_str("is_boundary")).value_or(false);
854 const float error_threshold =
855 bundle.lookup<float>(*BundleKey::from_str("error_threshold")).value_or(1e-3f);
856 const bke::GeometrySet *prev_geometry = previous_bundle ?
857 previous_bundle->lookup_ptr<bke::GeometrySet>(
858 *BundleKey::from_str("geometry")) :
859 nullptr;
860 if (!geometry) {
861 continue;
862 }
863 Vector<int> affected_data;
864 for (const int data_key_i : geometries_.data_keys.index_range()) {
865 if (this->effector_applies_to_geometry(path, bundle, data_key_i)) {
866 affected_data.append(data_key_i);
867 this->ensure_friction_loaded(data_key_i);
868 this->ensure_radius_loaded(data_key_i);
869 }
870 }
871 Vector<int> instance_id_stack;
872 this->gather_colliders_in_geometry(path,
873 world_to_simulation_,
874 world_to_simulation_,
875 *geometry,
876 prev_geometry,
877 margin,
878 friction,
879 compliance,
880 deforming,
881 use_edge_contacts,
882 is_boundary,
883 error_threshold,
884 affected_data,
885 instance_id_stack);
886 }
887 }
888
889 void gather_contacts__mesh_colliders(const int chunk_i,
890 const float max_distance,
891 const int solver_refs_i,
892 const SubstepInterval &substep,
893 const ExternalFaceContacts &prev_face_contacts,
894 const ExternalEdgeContacts &prev_edge_contacts,
895 ExternalFaceContacts &r_face_contacts,
896 ExternalEdgeContacts &r_edge_contacts)
897 {
898 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
899 const GeometryData &geo_data = *geometries_.data[chunk.data_key_i];
900 for (const MeshColliderUsage &collider_usage : geo_data.mesh_colliders) {
901 const MeshCollider &collider = constraints_.mesh_colliders[collider_usage.constraint_i];
902 const float4x4 &mesh_to_local = math::interpolate(
903 collider.begin_transform, collider.end_transform, substep.interpolate_end);
904 const float4x4 &prev_mesh_to_local = math::interpolate(
905 collider.begin_transform, collider.end_transform, substep.interpolate_begin);
906 const float4x4 local_to_mesh = math::invert(mesh_to_local);
907
908 if (std::holds_alternative<StaticMeshInfo>(collider.mesh)) {
909 this->gather_contacts__mesh_collider(chunk_i,
910 max_distance,
911 solver_refs_i,
912 false,
913 substep,
914 collider,
915 collider_usage,
916 mesh_to_local,
917 prev_mesh_to_local,
918 local_to_mesh,
919 prev_face_contacts,
920 prev_edge_contacts,
921 r_face_contacts,
922 r_edge_contacts);
923 }
924 else if (std::holds_alternative<DeformingMeshInfo>(collider.mesh)) {
925 this->gather_contacts__mesh_collider(chunk_i,
926 max_distance,
927 solver_refs_i,
928 true,
929 substep,
930 collider,
931 collider_usage,
932 mesh_to_local,
933 prev_mesh_to_local,
934 local_to_mesh,
935 prev_face_contacts,
936 prev_edge_contacts,
937 r_face_contacts,
938 r_edge_contacts);
939 }
940 }
941 }
942
943 void gather_contacts__mesh_collider(const int chunk_i,
944 const float max_distance,
945 const int solver_refs_i,
946 const bool is_deforming,
947 const SubstepInterval &substep,
948 const MeshCollider &collider,
949 const MeshColliderUsage &collider_usage,
950 const float4x4 &mesh_to_local,
951 const float4x4 &prev_mesh_to_local,
952 const float4x4 &local_to_mesh,
953 const ExternalFaceContacts &prev_face_contacts,
954 const ExternalEdgeContacts &prev_edge_contacts,
955 ExternalFaceContacts &r_face_contacts,
956 ExternalEdgeContacts &r_edge_contacts)
957 {
958 const Mesh *mesh;
959 const bke::bvh::Tree *corner_tris_bvh;
960 const bke::BVHTreeFromMesh *edges_bvh;
961 Span<float3> prev_vert_positions;
962 if (is_deforming) {
963 BLI_assert(std::holds_alternative<DeformingMeshInfo>(collider.mesh));
964 const auto &deforming_mesh = std::get<DeformingMeshInfo>(collider.mesh);
965 mesh = deforming_mesh.substep_meshes[substep.current_i + 1];
966 corner_tris_bvh = deforming_mesh.substep_corner_tris_bvh_trees[substep.current_i];
967 edges_bvh = &deforming_mesh.substep_edges_bvh_trees[substep.current_i];
968 prev_vert_positions = deforming_mesh.substep_meshes[substep.current_i]->vert_positions();
969 }
970 else {
971 BLI_assert(std::holds_alternative<StaticMeshInfo>(collider.mesh));
972 const auto &static_mesh = std::get<StaticMeshInfo>(collider.mesh);
973 mesh = static_mesh.mesh;
974 corner_tris_bvh = static_mesh.corner_tris_bvh;
975 edges_bvh = &static_mesh.edges_bvh;
976 }
977 const Span<float3> vert_positions = mesh->vert_positions();
978 const Span<int2> edge_verts = mesh->edges();
979 const Span<float3> vert_normals = mesh->vert_normals();
980 const Span<int> corner_verts = mesh->corner_verts();
981 const Span<int3> corner_tris = mesh->corner_tris();
982
983 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
984 const GeometryData &geo_data = *geometries_.data[chunk.data_key_i];
985 const Span<float3> positions =
986 geometries_.solver_refs[solver_refs_i][chunk.data_key_i].positions;
987
988 /* Only uniform scaling is correctly handled here. For non-uniform scaling, just the max
989 * scale along one axis is used. */
990 const float3 mesh_to_local_radius_scale = math::abs(math::to_scale(local_to_mesh));
991 const float local_to_mesh_radius_factor = std::max({mesh_to_local_radius_scale.x,
992 mesh_to_local_radius_scale.y,
993 mesh_to_local_radius_scale.z});
994 const float mesh_to_local_radius_factor = math::safe_rcp(local_to_mesh_radius_factor);
995 const float margin_local = mesh_to_local_radius_factor * collider.margin;
996
997 for (const int point_i : chunk.points_range) {
998 if (geo_data.is_hard_pinned[point_i]) {
999 continue;
1000 }
1001 const float3 &pos_local = positions[point_i];
1002 const float3 pos_mesh = math::transform_point(local_to_mesh, pos_local);
1003 const float radius_local = math::interpolate(
1004 geo_data.prev_radii[point_i], geo_data.radii[point_i], substep.interpolate_end);
1005 const float radius_mesh = local_to_mesh_radius_factor * radius_local;
1006 const std::optional<ClosestMeshFaceContact> contact = this->get_closest_mesh_face_contact(
1007 pos_mesh,
1008 *corner_tris_bvh,
1009 corner_tris,
1010 corner_verts,
1011 vert_positions,
1012 max_distance + radius_mesh);
1013 if (!contact) {
1014 continue;
1015 }
1016
1017 const float3 contact_pos_local = math::transform_point(mesh_to_local, contact->nearest_pos);
1018 float3 prev_contact_pos_mesh;
1019 if (is_deforming) {
1020 const int3 &tri = corner_tris[contact->tri_i];
1021 prev_contact_pos_mesh = bke::attribute_math::mix3(
1022 contact->bary_coords,
1023 prev_vert_positions[corner_verts[tri[0]]],
1024 prev_vert_positions[corner_verts[tri[1]]],
1025 prev_vert_positions[corner_verts[tri[2]]]);
1026 }
1027 else {
1028 prev_contact_pos_mesh = contact->nearest_pos;
1029 }
1030 const float3 prev_contact_pos_local = math::transform_point(prev_mesh_to_local,
1031 prev_contact_pos_mesh);
1032
1033 /* Separating axis to move self out of penetration. */
1034 const float3 collision_axis = (pos_local - contact_pos_local) *
1035 (contact->is_inside ? -1.0f : 1.0f) *
1036 (collider.is_boundary ? -1.0f : 1.0f);
1037 const float3 valid_axis = math::normalize(math::is_zero(collision_axis, 1e-6f) ?
1038 math::transpose(float3x3(local_to_mesh)) *
1039 contact->face_nor *
1040 (collider.is_boundary ? -1.0f : 1.0f) :
1041 collision_axis);
1042
1043 const float static_friction = this->compute_contact_friction(
1044 geo_data.static_frictions[point_i], collider.friction);
1045 const float dynamic_friction = this->compute_contact_friction(
1046 geo_data.dynamic_frictions[point_i], collider.friction);
1047
1048 const int contact_i = r_face_contacts.points.append_and_get_index(point_i);
1049 r_face_contacts.point_radii.append(radius_local);
1050 r_face_contacts.positions_on_face.append(contact_pos_local);
1051 r_face_contacts.collider_motion.append(contact_pos_local - prev_contact_pos_local);
1052 r_face_contacts.face_normals.append(valid_axis);
1053 r_face_contacts.face_margins.append(margin_local);
1054 r_face_contacts.static_frictions.append(static_friction);
1055 r_face_contacts.dynamic_frictions.append(dynamic_friction);
1056 r_face_contacts.compliance_terms.append(
1057 std::max(0.0f, substep_compliance_factor_ * collider.compliance));
1058 r_face_contacts.error_scales.append(error_scale_from_threshold(collider.error_threshold));
1059
1060 const MeshContactId contact_id{collider_usage.constraint_i, point_i};
1061 r_face_contacts.mesh_contact_indices.add(contact_id, contact_i);
1062 r_face_contacts.init_or_preserve_state(
1063 prev_face_contacts, prev_face_contacts.mesh_contact_indices.lookup_try(contact_id));
1064 }
1065
1066 if (collider.use_edge_contacts) {
1067 auto handle_edge = [&](const int geo_contact_id, const int point0, const int point1) {
1068 if (geo_data.is_hard_pinned[point0] && geo_data.is_hard_pinned[point1]) {
1069 return;
1070 }
1071 const float3 &pos_local0 = positions[point0];
1072 const float3 &pos_local1 = positions[point1];
1073 const float3 pos_mesh0 = math::transform_point(local_to_mesh, pos_local0);
1074 const float3 pos_mesh1 = math::transform_point(local_to_mesh, pos_local1);
1075 const float radius_local0 = math::interpolate(
1076 geo_data.prev_radii[point0], geo_data.radii[point0], substep.interpolate_end);
1077 const float radius_local1 = math::interpolate(
1078 geo_data.prev_radii[point1], geo_data.radii[point1], substep.interpolate_end);
1079 /* Use max radius for collision detection. */
1080 const float max_radius_mesh = local_to_mesh_radius_factor *
1081 std::max(radius_local0, radius_local1);
1082 const std::optional<ClosestMeshEdgeContact> contact = this->get_closest_mesh_edge_contact(
1083 pos_mesh0,
1084 pos_mesh1,
1085 *edges_bvh,
1086 edge_verts,
1087 vert_positions,
1088 max_distance + max_radius_mesh);
1089 if (!contact) {
1090 return;
1091 }
1092
1093 /* Add a contact for each face adjacent to the closest edge. */
1094 const int2 &edge = edge_verts[contact->edge_i];
1095
1096 const float3 contact_pos_local = math::transform_point(mesh_to_local,
1097 contact->nearest_pos);
1098 float3 prev_contact_pos_mesh;
1099 if (is_deforming) {
1100 prev_contact_pos_mesh = bke::attribute_math::mix2(
1101 contact->edge_factor, prev_vert_positions[edge[0]], prev_vert_positions[edge[1]]);
1102 }
1103 else {
1104 prev_contact_pos_mesh = contact->nearest_pos;
1105 }
1106 const float3 prev_contact_pos_local = math::transform_point(prev_mesh_to_local,
1107 prev_contact_pos_mesh);
1108
1109 const float3 edge_direction_mesh = math::normalize(vert_positions[edge[1]] -
1110 vert_positions[edge[0]]);
1111 const float3 edge_direction_local = math::normalize(
1112 math::transform_direction(mesh_to_local, edge_direction_mesh));
1113 /* Contact with the closest edge is active if the segment intersects with the
1114 * half-plane defined by the edge normal. A segment intersecting with any of the
1115 * adjacent faces would need to be moved along a tangent of the respective face to
1116 * resolve the collision, but since in combination with point-face collisions it is
1117 * sufficient to define a single edge normal, as long as the half-plane it defines is
1118 * inside both of the half-planes of the adjacent faces, i.e. between the two normal
1119 * directions. */
1120 const float3 averaged_vert_normal_mesh = math::midpoint(vert_normals[edge[0]],
1121 vert_normals[edge[1]]);
1122 /* Transforming normal with transpose of inverse. */
1123 const float3 averaged_vert_normal_local = math::transform_direction(
1124 math::transpose(local_to_mesh), averaged_vert_normal_mesh);
1125 const float3 edge_normal_local = math::normalize(math::cross(
1126 math::cross(edge_direction_local, averaged_vert_normal_local), edge_direction_local));
1127 BLI_assert(math::is_unit(math::cross(edge_direction_local, edge_normal_local)));
1128
1129 /* Use geometric average as edge friction coefficient. */
1130 const float static_friction = math::sqrt(
1131 math::square(this->compute_contact_friction(geo_data.static_frictions[point0],
1132 collider.friction)) +
1133 math::square(this->compute_contact_friction(geo_data.static_frictions[point1],
1134 collider.friction)));
1135 const float dynamic_friction = math::sqrt(
1136 math::square(this->compute_contact_friction(geo_data.dynamic_frictions[point0],
1137 collider.friction)) +
1138 math::square(this->compute_contact_friction(geo_data.dynamic_frictions[point1],
1139 collider.friction)));
1140
1141 const int contact_i = r_edge_contacts.point_pairs.append_and_get_index({point0, point1});
1142 r_edge_contacts.point_radii.append({radius_local0, radius_local1});
1143 r_edge_contacts.positions_on_edge.append(contact_pos_local);
1144 r_edge_contacts.collider_motion.append(contact_pos_local - prev_contact_pos_local);
1145 r_edge_contacts.edge_directions.append(edge_direction_local);
1146 r_edge_contacts.edge_normals.append(edge_normal_local *
1147 (collider.is_boundary ? -1.0f : 1.0f));
1148 r_edge_contacts.edge_margins.append(margin_local);
1149 r_edge_contacts.static_frictions.append(static_friction);
1150 r_edge_contacts.dynamic_frictions.append(dynamic_friction);
1151 r_edge_contacts.compliance_terms.append(
1152 std::max(0.0f, substep_compliance_factor_ * collider.compliance));
1153 r_edge_contacts.error_scales.append(error_scale_from_threshold(collider.error_threshold));
1154
1155 const MeshContactId contact_id{collider_usage.constraint_i, geo_contact_id};
1156 r_edge_contacts.mesh_contact_indices.add(contact_id, contact_i);
1157 r_edge_contacts.init_or_preserve_state(
1158 prev_edge_contacts, prev_edge_contacts.mesh_contact_indices.lookup_try(contact_id));
1159 };
1160
1161 if (chunk.curves_range) {
1162 const OffsetIndices points_by_curve = geo_data.curves->points_by_curve();
1163 for (const int curve : *chunk.curves_range) {
1164 for (const int point0 : points_by_curve[curve].drop_back(1)) {
1165 const int geo_contact_id = point0;
1166 handle_edge(geo_contact_id, point0, point0 + 1);
1167 }
1168 }
1169 }
1170 }
1171 }
1172
1173 void gather_from_world__collision_contacts()
1174 {
1175 const Span<std::string> paths = nested_bundle_paths_.lookup(CollisionContactsBundle::name);
1176 for (const StringRef path : paths) {
1177 const BundlePtr *bundle_ptr = world_.lookup_path_ptr<BundlePtr>(path);
1178 if (!bundle_ptr || !*bundle_ptr) {
1179 continue;
1180 }
1181
1182 constraints_.collision_contacts.append({path});
1183 }
1184 }
1185
1186 struct ClosestMeshFaceContact {
1188 float3 nearest_pos;
1189 float3 face_nor;
1190 float3 bary_coords;
1192 bool is_inside;
1193 int tri_i;
1194 };
1195
1196 struct ClosestMeshEdgeContact {
1198 float3 nearest_pos;
1199 float edge_factor;
1200 int edge_i;
1201 };
1202
1203 std::optional<ClosestMeshFaceContact> get_closest_mesh_face_contact(
1204 const float3 &sample_pos,
1205 const bke::bvh::Tree &corner_tris_bvh,
1206 const Span<int3> corner_tris,
1207 const Span<int> corner_verts,
1208 const Span<float3> vert_positions,
1209 const float max_distance) const
1210 {
1211 const std::optional<bke::bvh::ClosestPointResult> nearest = corner_tris_bvh.closest_point(
1212 sample_pos, max_distance);
1213 if (!nearest) {
1214 return std::nullopt;
1215 }
1216 const int tri_i = nearest->index;
1217 const int3 &tri = corner_tris[tri_i];
1218 const float3 &contact_pos = float3(nearest->position);
1219 const float3 contact_nor = math::normal_tri(
1220 vert_positions[corner_verts[corner_tris[tri_i][0]]],
1221 vert_positions[corner_verts[corner_tris[tri_i][1]]],
1222 vert_positions[corner_verts[corner_tris[tri_i][2]]]);
1224 vert_positions, corner_verts, tri, contact_pos);
1225 const float3 direction_to_mesh = contact_pos - sample_pos;
1226 bool is_inside;
1227 if (this->is_bary_coord_close_to_edge(bary_coords)) {
1228 /* The nearest point is on an edge, so its normal is unreliable, use a more robust test. */
1229 is_inside = this->is_inside_ray_using_rays(sample_pos, corner_tris_bvh, direction_to_mesh);
1230 }
1231 else {
1232 is_inside = math::dot(direction_to_mesh, contact_nor) > 0.0f;
1233 }
1234 return ClosestMeshFaceContact{contact_pos, contact_nor, bary_coords, is_inside, tri_i};
1235 }
1236
1241 std::optional<ClosestMeshEdgeContact> get_closest_mesh_edge_contact(
1242 const float3 &sample_pos0,
1243 const float3 &sample_pos1,
1244 const bke::BVHTreeFromMesh &edges_bvh,
1245 const Span<int2> edges,
1246 const Span<float3> vert_positions,
1247 const float max_distance) const
1248 {
1249 struct UserData {
1250 Span<int2> edges;
1251 Span<float3> vert_positions;
1252 float3 sample_pos0;
1253 float3 sample_pos1;
1254 };
1255
1256 const auto closest_edge_cb =
1257 [](void *user_data, int index, const BVHTreeRay * /*ray*/, BVHTreeRayHit *hit) {
1258 const auto &data = *static_cast<const UserData *>(user_data);
1259
1260 const int2 &edge = data.edges[index];
1261 const float3 &v0 = data.vert_positions[edge[0]];
1262 const float3 &v1 = data.vert_positions[edge[1]];
1263
1264 float3 closest_on_ray, closest_on_edge;
1266 data.sample_pos0, data.sample_pos1, v0, v1, closest_on_ray, closest_on_edge);
1267 const float dist_squared = math::distance_squared(closest_on_ray, closest_on_edge);
1268 if (dist_squared <= math::square(hit->dist)) {
1269 hit->dist = math::sqrt(dist_squared);
1270 hit->index = index;
1271 copy_v3_v3(hit->co, closest_on_edge);
1272 }
1273 };
1274
1275 float ray_len;
1276 const float3 ray_dir = math::normalize_and_get_length(sample_pos1 - sample_pos0, ray_len);
1277
1278 UserData user_data = {edges, vert_positions, sample_pos0, sample_pos1};
1279 /* Needs to be initialized. */
1280 BVHTreeRayHit hit;
1281 hit.index = -1;
1282 hit.dist = ray_len;
1284 edges_bvh.tree, sample_pos0, ray_dir, max_distance, &hit, closest_edge_cb, &user_data, 0);
1285 if (hit.index == -1) {
1286 return std::nullopt;
1287 }
1288
1289 const int edge_i = hit.index;
1290 const int2 &edge = edges[edge_i];
1291 const float3 &contact_pos = float3(hit.co);
1292 const float3 v0 = vert_positions[edge[0]];
1293 const float3 v1 = vert_positions[edge[1]];
1294 const float edge_factor = math::sqrt(math::safe_divide(math::distance_squared(contact_pos, v0),
1295 math::distance_squared(v1, v0)));
1296 return ClosestMeshEdgeContact{contact_pos, edge_factor, edge_i};
1297 }
1298
1299 bool is_bary_coord_close_to_edge(const float3 &bary_coords) const
1300 {
1301 constexpr float epsilon = 1e-3f;
1302 return math::abs(bary_coords[0]) < epsilon || math::abs(bary_coords[1]) < epsilon ||
1303 math::abs(bary_coords[2]) < epsilon;
1304 }
1305
1306 bool is_inside_ray_using_rays(const float3 &pos,
1307 const bke::bvh::Tree &bvh,
1308 const float3 &approx_ray_direction) const
1309 {
1310 /* Shoot rays in the approximate direction of where the nearest point is. This is a heuristic
1311 * for better performance to make the rays shorter. */
1312 const float3 approx_ray_direction_normalized = math::normalize(approx_ray_direction);
1313 const std::array<float3, 3> dirs = {
1314 {math::normalize(approx_ray_direction_normalized + float3{0.125f, -0.164f, 0.172f}),
1315 math::normalize(approx_ray_direction_normalized + float3{0.176f, 0.197f, -0.176f}),
1316 math::normalize(approx_ray_direction_normalized + float3{-0.140f, 0.151f, -0.126f})}};
1317 int inside_count = 0;
1318 for (const float3 &dir : dirs) {
1319 const bke::bvh::Ray ray(pos, dir);
1320 const std::optional<bke::bvh::RayHit> hit = bvh.ray_intersect(ray);
1321 if (hit) {
1322 const float3 dir = hit->position(ray) - pos;
1323 const bool is_inside = math::dot(dir, math::normalize(hit->normal)) > 0.0f;
1324 inside_count += is_inside ? 1 : -1;
1325 if (std::abs(inside_count) >= 2) {
1326 break;
1327 }
1328 }
1329 else {
1330 return false;
1331 }
1332 }
1333 return inside_count > 0;
1334 }
1335
1336 void gather_colliders_in_geometry(const StringRef path,
1337 const float4x4 &transform,
1338 const float4x4 &prev_transform,
1339 const GeometrySet &collider_geo,
1340 const GeometrySet *prev_collider_geo,
1341 const float margin,
1342 const float friction,
1343 const float compliance,
1344 const bool deforming,
1345 const bool use_edge_contacts,
1346 const bool is_boundary,
1347 const float error_threshold,
1348 const Span<int> affected_data,
1349 Vector<int> &instance_id_stack)
1350 {
1351 if (const Mesh *mesh = collider_geo.get_mesh()) {
1352 if (mesh->faces_num > 0) {
1353 MeshCollider mesh_collider;
1354 mesh_collider.path = path;
1355 mesh_collider.instance_ids = instance_id_stack;
1356 mesh_collider.margin = margin;
1357 mesh_collider.friction = friction;
1358 mesh_collider.compliance = compliance;
1359 mesh_collider.use_edge_contacts = use_edge_contacts;
1360 mesh_collider.is_boundary = is_boundary;
1361 mesh_collider.error_threshold = error_threshold;
1362 mesh_collider.begin_transform = prev_transform;
1363 mesh_collider.end_transform = transform;
1364 const Mesh *prev_mesh = prev_collider_geo ? prev_collider_geo->get_mesh() : nullptr;
1365 mesh_collider.mesh = this->make_collider_mesh_info(*mesh, prev_mesh, deforming);
1366
1367 const int collider_i = constraints_.mesh_colliders.append_and_get_index(
1368 std::move(mesh_collider));
1369 for (const int data_key_i : affected_data) {
1370 geometries_.data[data_key_i]->mesh_colliders.append({collider_i});
1371 }
1372 }
1373 }
1374 if (const bke::Instances *instances = collider_geo.get_instances()) {
1375 struct PrevInstanceItem {
1376 const float4x4 *transform;
1377 const bke::InstanceReference *reference;
1378 };
1379 Map<int, PrevInstanceItem> prev_instance_by_id;
1380 if (prev_collider_geo) {
1381 const bke::Instances *prev_instances = prev_collider_geo->get_instances();
1382 if (prev_instances) {
1383 const Span<float4x4> prev_instance_transforms = prev_instances->transforms();
1384 const Span<int> prev_instance_ids = prev_instances->unique_ids();
1385 const Span<int> prev_handles = prev_instances->reference_handles();
1386 const Span<bke::InstanceReference> prev_references = prev_instances->references();
1387 for (const int i : prev_instance_transforms.index_range()) {
1388 const int prev_instance_id = prev_instance_ids[i];
1389 const float4x4 &prev_instance_transform = prev_instance_transforms[i];
1390 const bke::InstanceReference &prev_reference = prev_references[prev_handles[i]];
1391 prev_instance_by_id.add(prev_instance_id, {&prev_instance_transform, &prev_reference});
1392 }
1393 }
1394 }
1395
1396 const Span<float4x4> instance_transforms = instances->transforms();
1397 const Span<bke::InstanceReference> references = instances->references();
1398 const Span<int> handles = instances->reference_handles();
1399 const Span<int> instance_ids = instances->unique_ids();
1400 for (const int instance_i : instance_transforms.index_range()) {
1401 const int handle = handles[instance_i];
1402 if (!references.index_range().contains(handle)) {
1403 continue;
1404 }
1405 const int instance_id = instance_ids[instance_i];
1406 const float4x4 instance_transform = instance_transforms[instance_i];
1407 const PrevInstanceItem *prev_instance_item = prev_instance_by_id.lookup_ptr(instance_id);
1408 const bke::InstanceReference &reference = references[handle];
1409 GeometrySet reference_geo;
1410 reference.to_geometry_set(reference_geo);
1411 GeometrySet prev_reference_geo;
1412 float4x4 prev_instance_transform = instance_transform;
1413 if (prev_instance_item) {
1414 prev_instance_item->reference->to_geometry_set(prev_reference_geo);
1415 prev_instance_transform = *prev_instance_item->transform;
1416 }
1417
1418 instance_id_stack.append(instance_id);
1419 BLI_SCOPED_DEFER([&]() { instance_id_stack.pop_last(); });
1420 this->gather_colliders_in_geometry(path,
1421 transform * instance_transform,
1422 prev_transform * prev_instance_transform,
1423 reference_geo,
1424 prev_instance_item ? &prev_reference_geo : nullptr,
1425 margin,
1426 friction,
1427 compliance,
1428 deforming,
1429 use_edge_contacts,
1430 is_boundary,
1431 error_threshold,
1432 affected_data,
1433 instance_id_stack);
1434 }
1435 }
1436 }
1437
1438 std::variant<StaticMeshInfo, DeformingMeshInfo> make_collider_mesh_info(const Mesh &mesh,
1439 const Mesh *prev_mesh,
1440 const bool deforming)
1441 {
1442 if (!deforming || !prev_mesh) {
1443 return StaticMeshInfo{&mesh, &mesh.bvh_tris(), mesh.bvh_edges_legacy()};
1444 }
1445 if (mesh.verts_num != prev_mesh->verts_num) {
1446 return StaticMeshInfo{&mesh, &mesh.bvh_tris(), mesh.bvh_edges_legacy()};
1447 }
1448 const int verts_num = mesh.verts_num;
1449 DeformingMeshInfo result;
1450 result.substep_meshes.resize(substeps_ + 1);
1451 result.substep_corner_tris_bvh_trees.resize(substeps_);
1452 result.substep_edges_bvh_trees.resize(substeps_);
1453
1454 const Span<float3> begin_positions = prev_mesh->vert_positions();
1455 const Span<float3> end_positions = mesh.vert_positions();
1456
1458 IndexRange(substeps_ + 1), std::max(1024 / verts_num, 1), [&](const IndexRange range) {
1459 TLS &tls = tls_.local();
1460 for (const int mesh_i : range) {
1461 const float mix_factor = (mesh_i - 1) / float(substeps_) *
1462 (interpolation_end_ - interpolation_begin_) +
1463 interpolation_begin_;
1464 const Mesh *substep_mesh = nullptr;
1465 if (mix_factor == 0.0f && mesh_i == 0) {
1466 substep_mesh = prev_mesh;
1467 }
1468 else if (mix_factor == 1.0f) {
1469 substep_mesh = &mesh;
1470 }
1471 else {
1472 Mesh *interpolated_mesh = BKE_mesh_copy_for_eval(mesh);
1473 tls.scope.add_destruct_call(
1474 [interpolated_mesh]() { BKE_id_free(nullptr, interpolated_mesh); });
1475 MutableSpan<float3> substep_positions =
1476 interpolated_mesh->vert_positions_for_write();
1477 for (const int i : IndexRange(verts_num)) {
1478 substep_positions[i] = math::interpolate(
1479 begin_positions[i], end_positions[i], mix_factor);
1480 }
1481 interpolated_mesh->tag_positions_changed();
1482 substep_mesh = interpolated_mesh;
1483 }
1484 result.substep_meshes[mesh_i] = substep_mesh;
1485 if (mesh_i > 0) {
1486 /* The bvh tree is not needed for the first substep. */
1487 result.substep_corner_tris_bvh_trees[mesh_i - 1] = &substep_mesh->bvh_tris();
1488 result.substep_edges_bvh_trees[mesh_i - 1] = substep_mesh->bvh_edges_legacy();
1489 }
1490 }
1491 });
1492 return result;
1493 }
1494
1495 void prepare_geometry_chunks()
1496 {
1497 constexpr int approx_points_per_chunk = 256;
1498 for (const int data_key_i : geometries_.data_keys.index_range()) {
1499 GeometryData &geo_data = *geometries_.data[data_key_i];
1500 if (geo_data.size == 0) {
1501 continue;
1502 }
1503 const int old_chunks_num = geometries_.chunks.size();
1504
1505 if (geo_data.curves) {
1506 /* For curve data, align the ranges with curve boundaries. */
1507 const bke::CurvesGeometry &curves = *geo_data.curves;
1508 const OffsetIndices<int> points_by_curve = curves.points_by_curve();
1509 Stack<IndexRange> curve_ranges_to_check;
1510 curve_ranges_to_check.push(curves.curves_range());
1511 while (!curve_ranges_to_check.is_empty()) {
1512 const IndexRange curves_range = curve_ranges_to_check.pop();
1513 const IndexRange points_range = points_by_curve[curves_range];
1514 if (points_range.is_empty()) {
1515 continue;
1516 }
1517 if (curves_range.size() == 1 || points_range.size() <= approx_points_per_chunk) {
1518 geometries_.chunks.append({data_key_i, points_range, curves_range});
1519 continue;
1520 }
1521 const int split_pos = curves_range.size() / 2;
1522 const IndexRange curves_range_left = curves_range.take_front(split_pos);
1523 const IndexRange curves_range_right = curves_range.drop_front(split_pos);
1524 /* Pushing in this order ensures that the chunks are sorted in the end. */
1525 curve_ranges_to_check.push(curves_range_right);
1526 curve_ranges_to_check.push(curves_range_left);
1527 }
1528 }
1529 else {
1530 const IndexRange points_range = IndexRange(geo_data.size);
1531 Stack<IndexRange> ranges_to_check;
1532 ranges_to_check.push(points_range);
1533 while (!ranges_to_check.is_empty()) {
1534 const IndexRange points_range = ranges_to_check.pop();
1535 if (points_range.is_empty()) {
1536 continue;
1537 }
1538 if (points_range.size() <= approx_points_per_chunk) {
1539 geometries_.chunks.append({data_key_i, points_range});
1540 continue;
1541 }
1542 const int split_pos = points_range.size() / 2;
1543 const IndexRange points_range_left = points_range.take_front(split_pos);
1544 const IndexRange points_range_right = points_range.drop_front(split_pos);
1545 /* Pushing in this order ensures that the chunks are sorted in the end. */
1546 ranges_to_check.push(points_range_right);
1547 ranges_to_check.push(points_range_left);
1548 }
1549 }
1550 geo_data.chunks = IndexRange::from_begin_end(old_chunks_num, geometries_.chunks.size());
1551
1552 /* Create mapping from points to chunks. */
1553 geo_data.point_to_chunk.reinitialize(geo_data.size);
1554 for (const int chunk_i : geo_data.chunks) {
1555 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
1556 geo_data.point_to_chunk.as_mutable_span().slice(chunk.points_range).fill(chunk_i);
1557 }
1558 }
1559 chunks_data_.reinitialize(geometries_.chunks.size());
1560 for (const int chunk_i : geometries_.chunks.index_range()) {
1561 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
1562 geometries_.max_chunk_size = std::max<int>(geometries_.max_chunk_size,
1563 chunk.points_range.size());
1564 }
1565 }
1566
1567 void prepare_inverse_masses()
1568 {
1569 for (const int data_key_i : geometries_.data_keys.index_range()) {
1570 GeometryData &geo_data = *geometries_.data[data_key_i];
1571 geo_data.inv_masses.reinitialize(geo_data.size);
1572 MutableSpan<float> inv_masses = geo_data.inv_masses;
1573
1574 if (const std::optional<float> mass = geo_data.masses.get_if_single()) {
1575 inv_masses.fill(math::safe_rcp(*mass));
1576 }
1577 else {
1578 const VArraySpan<float> masses = geo_data.masses;
1579 threading::parallel_for(IndexRange(geo_data.size), 2048, [&](const IndexRange range) {
1580 for (const int i : range) {
1581 const float mass = masses[i];
1582 inv_masses[i] = math::safe_rcp(mass);
1583 }
1584 });
1585 }
1586 }
1587 }
1588
1589 void prepare_inverse_moments_of_inertia()
1590 {
1591 for (const int data_key_i : geometries_.data_keys.index_range()) {
1592 GeometryData &geo_data = *geometries_.data[data_key_i];
1593 if (!geo_data.uses_rotation) {
1594 continue;
1595 }
1596 geo_data.inv_moments_of_inertia.reinitialize(geo_data.size);
1597 MutableSpan<float3> inv_moments_of_inertia = geo_data.inv_moments_of_inertia;
1598
1599 threading::parallel_for(IndexRange(geo_data.size), 2048, [&](const IndexRange range) {
1600 for (const int i : range) {
1601 const float3 &moment_of_inertia = geo_data.moments_of_inertia[i];
1602 if (math::is_zero(moment_of_inertia)) {
1603 inv_moments_of_inertia[i] = float3(0.0f);
1604 }
1605 else {
1606 inv_moments_of_inertia[i] = math::safe_rcp(moment_of_inertia);
1607 }
1608 }
1609 });
1610 }
1611 }
1612
1613 void gather_from_world__stretch_shear_constraints()
1614 {
1615 TLS &tls = tls_.local();
1616 const Span<std::string> paths = nested_bundle_paths_.lookup(RodStretchShearBundle::name);
1617 for (const StringRef path : paths) {
1618 const Bundle &bundle = **world_.lookup_path_ptr<BundlePtr>(path);
1619 RodStretchShearConstraint constraint;
1620 constraint.path = path;
1621 constraint.error_threshold =
1622 bundle.lookup<float>(*BundleKey::from_str("error_threshold")).value_or(1e-3f);
1623 constraint.lambda_pos_attr = bundle
1624 .lookup<std::string>(
1625 *BundleKey::from_str("lambda_position_attribute"))
1626 .value_or("");
1627 constraint.lambda_rot_attr = bundle
1628 .lookup<std::string>(
1629 *BundleKey::from_str("lambda_rotation_attribute"))
1630 .value_or("");
1631
1632 const int constraint_i = constraints_.rod_stretch_shear_constraints.append_and_get_index(
1633 std::move(constraint));
1634
1635 for (const int data_key_i : geometries_.data_keys.index_range()) {
1636 GeometryData &geo_data = *geometries_.data[data_key_i];
1637 if (!geo_data.curves) {
1638 continue;
1639 }
1640 if (!geo_data.uses_rotation) {
1641 this->report(NodeWarningType::Error,
1642 TIP_("Rod stretch/shear constraint requires \"rotation\" attribute"));
1643 continue;
1644 }
1645 if (!this->effector_applies_to_geometry(path, bundle, data_key_i)) {
1646 continue;
1647 }
1648 geo_data.rod_stretch_shear_constraints.append({constraint_i});
1649 }
1650 }
1651 for (const int data_key_i : geometries_.data_keys.index_range()) {
1652 GeometryData &geo_data = *geometries_.data[data_key_i];
1653 for (RodStretchShearConstraintUsage &constraint_usage :
1654 geo_data.rod_stretch_shear_constraints)
1655 {
1656 const RodStretchShearConstraint &constraint =
1657 constraints_.rod_stretch_shear_constraints[constraint_usage.constraint_i];
1658 VArray<float> rest_lengths = this->lookup_attribute_required<float>(
1659 data_key_i, this->prop_attr_name(constraint.path, "rest_length"), geo_data.domain);
1660 if (!rest_lengths) {
1661 continue;
1662 }
1663
1664 constraint_usage.compliances = this->make_range_spans(
1665 tls,
1666 this->lookup_attribute_default<float>(
1667 data_key_i,
1668 this->prop_attr_name(constraint.path, "compliance"),
1669 geo_data.domain,
1670 0.0f));
1671 constraint_usage.rest_lengths = std::move(rest_lengths);
1672 constraint_usage.is_valid = true;
1673
1674 constraint_usage.lambdas_pos = tls.allocator.allocate_array<float3>(geo_data.size);
1675 constraint_usage.lambdas_rot = tls.allocator.allocate_array<float3>(geo_data.size);
1676 }
1677 }
1678 }
1679
1680 void create_chunk_constraints__rod_stretch_shear(TLS &tls, const int chunk_i)
1681 {
1682 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
1683 ChunkData &chunk_data = chunks_data_[chunk_i];
1684 const GeometryData &geo_data = *geometries_.data[chunk.data_key_i];
1685 if (geo_data.rod_stretch_shear_constraints.is_empty()) {
1686 return;
1687 }
1688 const bke::CurvesGeometry &curves = *geo_data.curves;
1689 const OffsetIndices<int> points_by_curve = curves.points_by_curve();
1690 for (const RodStretchShearConstraintUsage &constraint_usage :
1691 geo_data.rod_stretch_shear_constraints)
1692 {
1693 if (!constraint_usage.is_valid) {
1694 continue;
1695 }
1696 const RodStretchShearConstraint &constraint =
1697 constraints_.rod_stretch_shear_constraints[constraint_usage.constraint_i];
1698 chunk_data.static_constraints.append(
1699 &tls.scope.construct<xpbd::RodStretchAndShearConstraintSet>(
1700 chunk.data_key_i,
1701 *chunk.curves_range,
1702 points_by_curve,
1703 constraint_usage.rest_lengths,
1704 constraint_usage.compliances.get_span_for_range(chunk.points_range),
1705 error_scale_from_threshold(constraint.error_threshold),
1706 constraint_usage.lambdas_pos,
1707 constraint_usage.lambdas_rot));
1708 }
1709 }
1710
1711 void write_back__rod_stretch_shear()
1712 {
1713 for (const int data_key_i : geometries_.data_keys.index_range()) {
1714 GeometryData &geo_data = *geometries_.data[data_key_i];
1715 for (const RodStretchShearConstraintUsage &constraint_usage :
1716 geo_data.rod_stretch_shear_constraints)
1717 {
1718 if (!constraint_usage.is_valid) {
1719 continue;
1720 }
1721 const RodStretchShearConstraint &constraint =
1722 constraints_.rod_stretch_shear_constraints[constraint_usage.constraint_i];
1723 geo_data.attributes.remove(constraint.lambda_pos_attr);
1724 geo_data.attributes.remove(constraint.lambda_rot_attr);
1725 if (bke::SpanAttributeWriter<float3> lambda_pos_attr =
1726 this->get_output_attribute_writer<float3>(
1727 data_key_i, constraint.lambda_pos_attr, geo_data.domain))
1728 {
1729 lambda_pos_attr.span.copy_from(constraint_usage.lambdas_pos);
1730 lambda_pos_attr.finish();
1731 }
1732 if (bke::SpanAttributeWriter<float3> lambda_rot_attr =
1733 this->get_output_attribute_writer<float3>(
1734 data_key_i, constraint.lambda_rot_attr, geo_data.domain))
1735 {
1736 lambda_rot_attr.span.copy_from(constraint_usage.lambdas_rot);
1737 lambda_rot_attr.finish();
1738 }
1739 }
1740 }
1741 }
1742
1743 void gather_from_world__bend_twist_constraints()
1744 {
1745 TLS &tls = tls_.local();
1746 const Span<std::string> paths = nested_bundle_paths_.lookup(RodBendTwistBundle::name);
1747 for (const StringRef path : paths) {
1748 const Bundle &bundle = **world_.lookup_path_ptr<BundlePtr>(path);
1749
1750 RodBendTwistConstraint constraint;
1751 constraint.path = path;
1752 constraint.error_threshold =
1753 bundle.lookup<float>(*BundleKey::from_str("error_threshold")).value_or(1e-2f);
1754
1755 const int constraint_i = constraints_.rod_bend_twist_constraints.append_and_get_index(
1756 std::move(constraint));
1757
1758 for (const int data_key_i : geometries_.data.index_range()) {
1759 GeometryData &geo_data = *geometries_.data[data_key_i];
1760 if (!geo_data.curves) {
1761 continue;
1762 }
1763 if (!geo_data.uses_rotation) {
1764 this->report(NodeWarningType::Error,
1765 TIP_("Rod stretch/shear constraint requires \"rotation\" attribute"));
1766 continue;
1767 }
1768 if (!this->effector_applies_to_geometry(path, bundle, data_key_i)) {
1769 continue;
1770 }
1771 geo_data.rod_bend_twist_constraints.append({constraint_i});
1772 }
1773 }
1774 for (const int data_key_i : geometries_.data_keys.index_range()) {
1775 GeometryData &geo_data = *geometries_.data[data_key_i];
1776 for (RodBendTwistConstraintUsage &constraint_usage : geo_data.rod_bend_twist_constraints) {
1777 const RodBendTwistConstraint &constraint =
1778 constraints_.rod_bend_twist_constraints[constraint_usage.constraint_i];
1779 constraint_usage.lambdas = tls.allocator.allocate_array<float4>(geo_data.size);
1780 constraint_usage.compliances = this->make_range_spans(
1781 tls,
1782 this->lookup_attribute_default<float>(
1783 data_key_i,
1784 this->prop_attr_name(constraint.path, "compliance"),
1785 geo_data.domain,
1786 0.0f));
1787 constraint_usage.rest_bend_rotations = this->lookup_attribute_default<math::Quaternion>(
1788 data_key_i,
1789 this->prop_attr_name(constraint.path, "rest_bend_rotation"),
1790 geo_data.domain,
1792 }
1793 }
1794 }
1795
1796 void create_chunk_constraints__rod_bend_twist(TLS &tls, const int chunk_i)
1797 {
1798 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
1799 ChunkData &chunk_data = chunks_data_[chunk_i];
1800 const GeometryData &geo_data = *geometries_.data[chunk.data_key_i];
1801 if (geo_data.rod_bend_twist_constraints.is_empty()) {
1802 return;
1803 }
1804 const bke::CurvesGeometry &curves = *geo_data.curves;
1805 const OffsetIndices<int> points_by_curve = curves.points_by_curve();
1806 for (const RodBendTwistConstraintUsage &constraint_usage : geo_data.rod_bend_twist_constraints)
1807 {
1808 const RodBendTwistConstraint &constraint =
1809 constraints_.rod_bend_twist_constraints[constraint_usage.constraint_i];
1810 chunk_data.static_constraints.append(
1811 &tls.scope.construct<xpbd::RodBendAndTwistConstraintSet>(
1812 chunk.data_key_i,
1813 *chunk.curves_range,
1814 points_by_curve,
1815 constraint_usage.rest_bend_rotations,
1816 constraint_usage.compliances.get_span_for_range(chunk.points_range),
1817 error_scale_from_threshold(constraint.error_threshold),
1818 constraint_usage.lambdas));
1819 }
1820 }
1821
1822 void gather_from_world__edge_length_constraints()
1823 {
1824 TLS &tls = tls_.local();
1825 const Span<std::string> paths = nested_bundle_paths_.lookup(EdgeLengthConstraintBundle::name);
1826 for (const StringRef path : paths) {
1827 const Bundle &bundle = **world_.lookup_path_ptr<BundlePtr>(path);
1828
1829 const float error_threshold =
1830 bundle.lookup<float>(*BundleKey::from_str("error_threshold")).value_or(1e-3f);
1831 const int constraint_i = constraints_.edge_length_constraints.append_and_get_index(
1832 {path, error_threshold});
1833
1834 for (const int data_key_i : geometries_.data.index_range()) {
1835 const DataKey &data_key = geometries_.data_keys[data_key_i];
1836 GeometryData &geo_data = *geometries_.data[data_key_i];
1837 if (data_key.type != GeometryComponent::Type::Mesh) {
1838 continue;
1839 }
1840 if (this->effector_applies_to_geometry(path, bundle, data_key_i)) {
1841 EdgeLengthConstraintUsage constraint_usage;
1842 constraint_usage.constraint_i = constraint_i;
1843 geo_data.edge_length_constraints.append(std::move(constraint_usage));
1844 }
1845 }
1846 }
1847
1848 for (const int data_key_i : geometries_.data_keys.index_range()) {
1849 const DataKey &data_key = geometries_.data_keys[data_key_i];
1850 GeometryData &geo_data = *geometries_.data[data_key_i];
1851 for (EdgeLengthConstraintUsage &constraint_usage : geo_data.edge_length_constraints) {
1852 const EdgeLengthConstraint &constraint =
1853 constraints_.edge_length_constraints[constraint_usage.constraint_i];
1854 const Mesh &mesh = *geometries_.geometry_sets[data_key.geo_bundle_i].geometry.get_mesh();
1855 const Span<int2> edges = mesh.edges();
1856 const int edge_num = edges.size();
1857
1858 VArray<float> rest_lengths = this->lookup_attribute_required<float>(
1859 data_key_i, this->prop_attr_name(constraint.path, "rest_length"), AttrDomain::Edge);
1860 if (!rest_lengths) {
1861 continue;
1862 }
1863
1864 constraint_usage.lambdas = tls.allocator.allocate_array<float>(edge_num);
1865 constraint_usage.rest_lengths = rest_lengths;
1866 constraint_usage.compliances = this->lookup_attribute_default<float>(
1867 data_key_i,
1868 this->prop_attr_name(constraint.path, "compliance"),
1869 AttrDomain::Edge,
1870 0.0f);
1871 constraint_usage.is_valid = true;
1872
1873 auto &constraint_set = tls.scope.construct<xpbd::DistanceConstraintSet>(
1874 data_key_i,
1875 edges,
1876 constraint_usage.rest_lengths,
1877 constraint_usage.compliances,
1878 error_scale_from_threshold(constraint.error_threshold),
1879 constraint_usage.lambdas);
1880 xpbd::ConstraintColoring coloring = constraint_set.color_constraints(tls.allocator);
1881 geo_data.static_constraints.append({&constraint_set, std::move(coloring)});
1882 }
1883 }
1884 }
1885
1886 void gather_from_world__cross_edge_length_constraints()
1887 {
1888 TLS &tls = tls_.local();
1889 const Span<std::string> paths = nested_bundle_paths_.lookup_as(
1890 CrossEdgeLengthConstraintBundle::name);
1891 for (const StringRef path : paths) {
1892 const Bundle &bundle = **world_.lookup_path_ptr<BundlePtr>(path);
1893 const float error_threshold =
1894 bundle.lookup<float>(*BundleKey::from_str("error_threshold")).value_or(1e-3f);
1895 const int constraint_i = constraints_.cross_edge_length_constraints.append_and_get_index(
1896 {path, error_threshold});
1897 for (const int data_key_i : geometries_.data.index_range()) {
1898 const DataKey &data_key = geometries_.data_keys[data_key_i];
1899 GeometryData &geo_data = *geometries_.data[data_key_i];
1900 if (data_key.type != GeometryComponent::Type::Mesh) {
1901 continue;
1902 }
1903 if (this->effector_applies_to_geometry(path, bundle, data_key_i)) {
1904 CrossEdgeLengthConstraintUsage constraint_usage;
1905 constraint_usage.constraint_i = constraint_i;
1906 geo_data.cross_edge_length_constraints.append(std::move(constraint_usage));
1907 }
1908 }
1909 }
1910
1911 for (const int data_key_i : geometries_.data_keys.index_range()) {
1912 const DataKey &data_key = geometries_.data_keys[data_key_i];
1913 GeometryData &geo_data = *geometries_.data[data_key_i];
1914 for (CrossEdgeLengthConstraintUsage &constraint_usage :
1915 geo_data.cross_edge_length_constraints)
1916 {
1917 const CrossEdgeLengthConstraint &constraint =
1918 constraints_.cross_edge_length_constraints[constraint_usage.constraint_i];
1919 const Mesh &mesh = *geometries_.geometry_sets[data_key.geo_bundle_i].geometry.get_mesh();
1920 const VArraySpan<float3> rest_positions = this->lookup_attribute_required<float3>(
1921 data_key_i, this->prop_attr_name(constraint.path, "rest_position"), AttrDomain::Point);
1922 if (rest_positions.is_empty()) {
1923 continue;
1924 }
1925 const VArray<float> edge_compliances = this->lookup_attribute_default<float>(
1926 data_key_i,
1927 this->prop_attr_name(constraint.path, "compliance"),
1928 AttrDomain::Edge,
1929 0.0f);
1930
1931 Vector<int2> &cross_edges = constraint_usage.cross_edge_points;
1932 Vector<float> &cross_edge_rest_lengths = constraint_usage.distances;
1933 Vector<float> &cross_edge_compliances = constraint_usage.compliances;
1934
1935 this->foreach_cross_edge(mesh, [&](const int edge_i, const int v0, const int v1) {
1936 const float3 &rest_position0 = rest_positions[v0];
1937 const float3 &rest_position1 = rest_positions[v1];
1938 const float rest_length = math::distance(rest_position0, rest_position1);
1939 const float compliance = edge_compliances[edge_i];
1940 cross_edges.append({v0, v1});
1941 cross_edge_rest_lengths.append(rest_length);
1942 cross_edge_compliances.append(compliance);
1943 });
1944
1945 constraint_usage.lambdas = tls.allocator.allocate_array<float>(cross_edges.size());
1946
1947 auto &constraint_set = tls.scope.construct<xpbd::DistanceConstraintSet>(
1948 data_key_i,
1949 cross_edges,
1950 cross_edge_rest_lengths,
1951 cross_edge_compliances,
1952 error_scale_from_threshold(constraint.error_threshold),
1953 constraint_usage.lambdas);
1954 xpbd::ConstraintColoring coloring = constraint_set.color_constraints(tls.allocator);
1955 geo_data.static_constraints.append({&constraint_set, std::move(coloring)});
1956 }
1957 }
1958 }
1959
1960 void foreach_cross_edge(const Mesh &mesh,
1961 std::invocable<int /*edge_i*/, int /*v0*/, int /*v1*/> auto &&fn)
1962 {
1963 /* Don't use triangulated mesh because the triangulation depends on vertex positions which
1964 * change during the simulation which introduces instability. */
1965 const Span<int2> edges = mesh.edges();
1966 const Span<int> corner_verts = mesh.corner_verts();
1967 const OffsetIndices<int> faces = mesh.faces();
1968
1969 Array<int> offsets;
1970 Array<int> indices;
1971 const GroupedSpan<int> edge_to_faces = bke::mesh::build_edge_to_face_map(
1972 faces, mesh.corner_edges(), mesh.edges_num, offsets, indices);
1973
1974 for (const int edge_i : edges.index_range()) {
1975 const int2 &edge = edges[edge_i];
1976 const int edge_v0 = edge[0];
1977 const int edge_v1 = edge[1];
1978 const Span<int> incident_faces = edge_to_faces[edge_i];
1979 if (incident_faces.size() != 2) {
1980 continue;
1981 }
1982 int face0 = incident_faces[0];
1983 int face1 = incident_faces[1];
1984 if (faces[face0].size() > faces[face1].size()) {
1985 std::swap(face0, face1);
1986 }
1987 const IndexRange face0_corners = faces[face0];
1988 const IndexRange face1_corners = faces[face1];
1989 const int face0_size = face0_corners.size();
1990 const int face1_size = face1_corners.size();
1991 if (face0_size == 3 && face1_size == 3) {
1992 const int face0_v0 = corner_verts[face0_corners[0]];
1993 const int face0_v1 = corner_verts[face0_corners[1]];
1994 const int face0_v2 = corner_verts[face0_corners[2]];
1995
1996 const int face1_v0 = corner_verts[face1_corners[0]];
1997 const int face1_v1 = corner_verts[face1_corners[1]];
1998 const int face1_v2 = corner_verts[face1_corners[2]];
1999
2000 /* Create a cross edge between opposite corners of the two faces. */
2001 const int cross_edge_v0 = edge_v0 ^ edge_v1 ^ face0_v0 ^ face0_v1 ^ face0_v2;
2002 const int cross_edge_v1 = edge_v0 ^ edge_v1 ^ face1_v0 ^ face1_v1 ^ face1_v2;
2003 fn(edge_i, cross_edge_v0, cross_edge_v1);
2004 }
2005 else if (face0_size == 3 && face1_size == 4) {
2006 const int face0_v0 = corner_verts[face0_corners[0]];
2007 const int face0_v1 = corner_verts[face0_corners[1]];
2008 const int face0_v2 = corner_verts[face0_corners[2]];
2009
2010 /* Create two cross edges between the triangle and quad. */
2011 const int cross_edge_v0 = edge_v0 ^ edge_v1 ^ face0_v0 ^ face0_v1 ^ face0_v2;
2012 for (const int face1_corner : face1_corners) {
2013 const int face1_v = corner_verts[face1_corner];
2014 if (!ELEM(face1_v, edge_v0, edge_v1)) {
2015 fn(edge_i, cross_edge_v0, face1_v);
2016 }
2017 }
2018 }
2019 else {
2020 /* Create cross edges between "diagonal" corners. */
2021 const Span<int> face0_verts = corner_verts.slice(face0_corners);
2022 const Span<int> face1_verts = corner_verts.slice(face1_corners);
2023 const int face0_i0 = face0_verts.first_index(edge_v0);
2024 const int face0_dir = face0_verts[(face0_i0 + 1) % face0_size] == edge_v1 ? 1 : -1;
2025 const int face1_i1 = face1_verts.first_index(edge_v1);
2026 const int face1_dir = face1_verts[(face1_i1 + 1) % face1_size] == edge_v0 ? 1 : -1;
2027 /* Some corners may be ignored if they if both faces have a different number of
2028 * corners. */
2029 const int cross_edge_num = std::max(face0_size, face1_size) - 2;
2030 for (const int i : IndexRange(cross_edge_num)) {
2031 const int cross_edge_v0 = face0_verts[mod_i(face0_i0 - face0_dir * (i + 1), face0_size)];
2032 const int cross_edge_v1 = face1_verts[mod_i(face1_i1 - face1_dir * (i + 1), face1_size)];
2033 fn(edge_i, cross_edge_v0, cross_edge_v1);
2034 }
2035 }
2036 }
2037 }
2038
2039 void gather_from_world__damping()
2040 {
2041 TLS &tls = tls_.local();
2042 const Span<std::string> paths = nested_bundle_paths_.lookup(DampingBundle::name);
2043 for (const StringRef path : paths) {
2044 const BundlePtr *bundle_ptr = world_.lookup_path_ptr<BundlePtr>(path);
2045 if (!bundle_ptr || !*bundle_ptr) {
2046 continue;
2047 }
2048 const Bundle &bundle = **bundle_ptr;
2049
2050 const int constraint_i = constraints_.damping_constraints.append_and_get_index({path});
2051
2052 for (const int data_key_i : geometries_.data_keys.index_range()) {
2053 GeometryData &geo_data = *geometries_.data[data_key_i];
2054 if (this->effector_applies_to_geometry(path, bundle, data_key_i)) {
2055 geo_data.damping_constraints.append({constraint_i});
2056 }
2057 }
2058 }
2059
2060 for (const int data_key_i : geometries_.data_keys.index_range()) {
2061 GeometryData &geo_data = *geometries_.data[data_key_i];
2062 for (DampingConstraintUsage &constraint_usage : geo_data.damping_constraints) {
2063 const DampingConstraint &constraint =
2064 constraints_.damping_constraints[constraint_usage.constraint_i];
2065 constraint_usage.linear_dampings = this->make_range_spans(
2066 tls,
2067 this->lookup_attribute_default<float>(data_key_i,
2068 this->prop_attr_name(constraint.path, "linear"),
2069 geo_data.domain,
2070 0.0f));
2071 constraint_usage.angular_dampings = this->make_range_spans(
2072 tls,
2073 this->lookup_attribute_default<float>(data_key_i,
2074 this->prop_attr_name(constraint.path, "angular"),
2075 geo_data.domain,
2076 0.0f));
2077
2078 constraint_usage.linear_damping_lambdas = tls.allocator.allocate_array<float>(
2079 geo_data.size);
2080 constraint_usage.angular_damping_lambdas = tls.allocator.allocate_array<float>(
2081 geo_data.size);
2082 }
2083 }
2084 }
2085
2086 void create_chunk_constraints__damping(TLS &tls, const int chunk_i)
2087 {
2088 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
2089 ChunkData &chunk_data = chunks_data_[chunk_i];
2090 const GeometryData &geo_data = *geometries_.data[chunk.data_key_i];
2091
2092 for (const DampingConstraintUsage &constraint_usage : geo_data.damping_constraints) {
2093 chunk_data.static_velocity_constraints.append(
2094 &tls.scope.construct<xpbd::LinearDampingConstraintSet>(
2095 chunk.data_key_i,
2096 chunk.points_range,
2097 constraint_usage.linear_dampings.get_span_for_range(chunk.points_range),
2098 constraint_usage.linear_damping_lambdas.slice(chunk.points_range)));
2099 if (geo_data.uses_rotation) {
2100 chunk_data.static_velocity_constraints.append(
2101 &tls.scope.construct<xpbd::AngularDampingConstraintSet>(
2102 chunk.data_key_i,
2103 chunk.points_range,
2104 constraint_usage.angular_dampings.get_span_for_range(chunk.points_range),
2105 constraint_usage.angular_damping_lambdas.slice(chunk.points_range)));
2106 }
2107 }
2108 }
2109
2110 void gather_from_world__pin_positions()
2111 {
2112 TLS &tls = tls_.local();
2113 const Span<std::string> paths = nested_bundle_paths_.lookup(PinPositionBundle::name);
2114 for (const StringRef path : paths) {
2115 const Bundle &bundle = **world_.lookup_path_ptr<BundlePtr>(path);
2116 PinPositionConstraint constraint;
2117 constraint.path = path;
2118 constraint.error_threshold =
2119 bundle.lookup<float>(*BundleKey::from_str("error_threshold")).value_or(1e-3f);
2120 constraint.lambda_attr =
2121 bundle.lookup<std::string>(*BundleKey::from_str("lambda_attribute")).value_or("");
2122 const int constraint_i = constraints_.pin_position_constraints.append_and_get_index(
2123 std::move(constraint));
2124
2125 for (const int data_key_i : geometries_.data_keys.index_range()) {
2126 GeometryData &geo_data = *geometries_.data[data_key_i];
2127 if (this->effector_applies_to_geometry(path, bundle, data_key_i)) {
2128 geo_data.pin_position_constraints.append({constraint_i});
2129 }
2130 }
2131 }
2132 for (const int data_key_i : geometries_.data_keys.index_range()) {
2133 GeometryData &geo_data = *geometries_.data[data_key_i];
2134 for (PinPositionConstraintUsage &constraint_usage : geo_data.pin_position_constraints) {
2135 const PinPositionConstraint &constraint =
2136 constraints_.pin_position_constraints[constraint_usage.constraint_i];
2137
2138 const VArray<bool> selection_attr = this->lookup_attribute_required<bool>(
2139 data_key_i, this->prop_attr_name(constraint.path, "selection"), geo_data.domain);
2140 const VArray<float3> positions_attr = this->lookup_attribute_required<float3>(
2141 data_key_i, this->prop_attr_name(constraint.path, "position"), geo_data.domain);
2142 if (!positions_attr || !selection_attr) {
2143 continue;
2144 }
2145 const IndexMask pin_selection = IndexMask::from_bools(selection_attr, tls.allocator);
2146 if (pin_selection.is_empty()) {
2147 continue;
2148 }
2149 const VArray<float> compliances_attr = this->lookup_attribute_default<float>(
2150 data_key_i,
2151 this->prop_attr_name(constraint.path, "compliance"),
2152 geo_data.domain,
2153 0.0f);
2154 VArray<bool> prev_selection_attr;
2155 VArray<float3> prev_positions_attr;
2156 if (sub_delta_time_ > 0.0f) {
2157 prev_selection_attr = this->lookup_attribute_optional<bool>(
2158 data_key_i,
2159 this->prev_prop_attr_name(constraint.path, "selection"),
2160 geo_data.domain);
2161 prev_positions_attr = this->lookup_attribute_optional<float3>(
2162 data_key_i, this->prev_prop_attr_name(constraint.path, "position"), geo_data.domain);
2163 }
2164
2165 const int pin_num = pin_selection.size();
2166 MutableSpan<int> points = tls.allocator.allocate_array<int>(pin_num);
2167 pin_selection.to_indices(points);
2168
2169 MutableSpan<float3> end_positions = tls.allocator.allocate_array<float3>(pin_num);
2170 MutableSpan<float> compliances = tls.allocator.allocate_array<float>(pin_num);
2171
2172 positions_attr.materialize_compressed_to_uninitialized(pin_selection, end_positions);
2173 compliances_attr.materialize_compressed_to_uninitialized(pin_selection, compliances);
2174
2175 constraint_usage.points = points;
2176 constraint_usage.end_positions = end_positions;
2177 constraint_usage.compliances = compliances;
2178 /* These will be initialized later. */
2179 constraint_usage.lambdas = tls.allocator.allocate_array<float>(pin_num);
2180 constraint_usage.current_positions = tls.allocator.allocate_array<float3>(pin_num);
2181
2182 /* Initialize the previous pin position. */
2183 if (prev_selection_attr && prev_positions_attr) {
2184 MutableSpan<float3> begin_positions = tls.allocator.allocate_array<float3>(pin_num);
2185 threading::parallel_for(pin_selection.index_range(), 1024, [&](const IndexRange range) {
2186 for (const int pin_i : range) {
2187 const int point_i = points[pin_i];
2188 const bool was_pinned = prev_selection_attr[point_i];
2189 if (was_pinned) {
2190 begin_positions[pin_i] = prev_positions_attr[point_i];
2191 }
2192 else {
2193 begin_positions[pin_i] = geo_data.position_attr.span[point_i];
2194 }
2195 }
2196 });
2197 constraint_usage.begin_positions = begin_positions;
2198 }
2199 else {
2200 constraint_usage.begin_positions = end_positions;
2201 }
2202 }
2203 }
2204 }
2205
2206 void create_chunk_constraints__pin_positions(TLS &tls, const int chunk_i)
2207 {
2208 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
2209 ChunkData &chunk_data = chunks_data_[chunk_i];
2210 GeometryData &geo_data = *geometries_.data[chunk.data_key_i];
2211 for (const int constraint_usage_i : geo_data.pin_position_constraints.index_range()) {
2212 const PinPositionConstraintUsage &constraint_usage =
2213 geo_data.pin_position_constraints[constraint_usage_i];
2214 const PinPositionConstraint &constraint =
2215 constraints_.pin_position_constraints[constraint_usage.constraint_i];
2216
2217 /* Detect hard pinned points. */
2218 for (const int pin_i : constraint_usage.points.index_range()) {
2219 const int point_i = constraint_usage.points[pin_i];
2220 const float compliance = constraint_usage.compliances[pin_i];
2221 if (compliance <= 0.0f) {
2222 geo_data.is_hard_pinned[point_i] = true;
2223 }
2224 }
2225
2226 const IndexRange pin_range = unique_sorted_indices::find_content_range<int>(
2227 constraint_usage.points, chunk.points_range);
2228 if (pin_range.is_empty()) {
2229 continue;
2230 }
2231 chunk_data.pin_position_constraints.append({constraint_usage_i, pin_range});
2232 chunk_data.static_constraints.append(&tls.scope.construct<xpbd::PinPositionConstraintSet>(
2233 chunk.data_key_i,
2234 constraint_usage.points.slice(pin_range),
2235 constraint_usage.current_positions.slice(pin_range),
2236 constraint_usage.compliances.slice(pin_range),
2237 error_scale_from_threshold(constraint.error_threshold),
2238 constraint_usage.lambdas.slice(pin_range)));
2239 }
2240 }
2241
2242 void write_back__pin_positions()
2243 {
2244 for (const int data_key_i : geometries_.data_keys.index_range()) {
2245 GeometryData &geo_data = *geometries_.data[data_key_i];
2246 for (const PinPositionConstraintUsage &constraint_usage : geo_data.pin_position_constraints)
2247 {
2248 const PinPositionConstraint &constraint =
2249 constraints_.pin_position_constraints[constraint_usage.constraint_i];
2250 geo_data.attributes.remove(constraint.lambda_attr);
2251 }
2252 for (const PinPositionConstraintUsage &constraint_usage : geo_data.pin_position_constraints)
2253 {
2254 if (constraint_usage.points.is_empty()) {
2255 /* If there is nothing pinned, these attributes don't need to exist. */
2256 continue;
2257 }
2258 const PinPositionConstraint &constraint =
2259 constraints_.pin_position_constraints[constraint_usage.constraint_i];
2260 if (bke::SpanAttributeWriter<float> lambda_attr = this->get_output_attribute_writer<float>(
2261 data_key_i, constraint.lambda_attr, geo_data.domain))
2262 {
2263 for (const int pin_i : constraint_usage.points.index_range()) {
2264 const int point_i = constraint_usage.points[pin_i];
2265 lambda_attr.span[point_i] = constraint_usage.lambdas[pin_i];
2266 }
2267 lambda_attr.finish();
2268 }
2269 }
2270 }
2271 }
2272
2273 void gather_from_world__pin_rotations()
2274 {
2275 TLS &tls = tls_.local();
2276 const Span<std::string> paths = nested_bundle_paths_.lookup(PinRotationBundle::name);
2277 for (const StringRef path : paths) {
2278 const Bundle &bundle = **world_.lookup_path_ptr<BundlePtr>(path);
2279
2280 PinRotationConstraint constraint;
2281 constraint.path = path;
2282 constraint.error_threshold =
2283 bundle.lookup<float>(*BundleKey::from_str("error_threshold")).value_or(1e-2f);
2284 const int constraint_i = constraints_.pin_rotation_constraints.append_and_get_index(
2285 std::move(constraint));
2286
2287 for (const int data_key_i : geometries_.data_keys.index_range()) {
2288 GeometryData &geo_data = *geometries_.data[data_key_i];
2289 if (!geo_data.uses_rotation) {
2290 continue;
2291 }
2292 if (this->effector_applies_to_geometry(path, bundle, data_key_i)) {
2293 geo_data.pin_rotation_constraints.append({constraint_i});
2294 }
2295 }
2296 }
2297 for (const int data_key_i : geometries_.data_keys.index_range()) {
2298 GeometryData &geo_data = *geometries_.data[data_key_i];
2299 for (PinRotationConstraintUsage &constraint_usage : geo_data.pin_rotation_constraints) {
2300 const PinRotationConstraint &constraint =
2301 constraints_.pin_rotation_constraints[constraint_usage.constraint_i];
2302
2303 const VArray<bool> selection_attr = this->lookup_attribute_required<bool>(
2304 data_key_i, this->prop_attr_name(constraint.path, "selection"), geo_data.domain);
2305 const VArray<math::Quaternion> rotation_attr =
2306 this->lookup_attribute_required<math::Quaternion>(
2307 data_key_i, this->prop_attr_name(constraint.path, "rotation"), geo_data.domain);
2308 if (!selection_attr || !rotation_attr) {
2309 continue;
2310 }
2311 const IndexMask pin_selection = IndexMask::from_bools(selection_attr, tls.allocator);
2312 if (pin_selection.is_empty()) {
2313 continue;
2314 }
2315 const VArray<float> compliances_attr = this->lookup_attribute_default<float>(
2316 data_key_i,
2317 this->prop_attr_name(constraint.path, "compliance"),
2318 geo_data.domain,
2319 0.0f);
2320 VArray<bool> prev_selection_attr;
2321 VArray<math::Quaternion> prev_rotations_attr;
2322 if (sub_delta_time_ > 0.0f) {
2323 prev_selection_attr = this->lookup_attribute_optional<bool>(
2324 data_key_i,
2325 this->prev_prop_attr_name(constraint.path, "selection"),
2326 geo_data.domain);
2327 prev_rotations_attr = this->lookup_attribute_optional<math::Quaternion>(
2328 data_key_i, this->prev_prop_attr_name(constraint.path, "rotation"), geo_data.domain);
2329 }
2330
2331 const int pin_num = pin_selection.size();
2332 MutableSpan<int> points = tls.allocator.allocate_array<int>(pin_num);
2333 pin_selection.to_indices(points);
2334
2335 MutableSpan<math::Quaternion> end_rotations =
2336 tls.allocator.allocate_array<math::Quaternion>(pin_num);
2337 MutableSpan<float> compliances = tls.allocator.allocate_array<float>(pin_num);
2338
2339 rotation_attr.materialize_compressed_to_uninitialized(pin_selection, end_rotations);
2340 compliances_attr.materialize_compressed_to_uninitialized(pin_selection, compliances);
2341
2342 constraint_usage.points = points;
2343 constraint_usage.end_rotations = end_rotations;
2344 constraint_usage.compliances = compliances;
2345 /* These will be initialized later. */
2346 constraint_usage.lambdas = tls.allocator.allocate_array<float4>(pin_num);
2347 constraint_usage.current_rotations = tls.allocator.allocate_array<math::Quaternion>(
2348 pin_num);
2349
2350 /* Initialize the previous pin rotation. */
2351 if (prev_selection_attr && prev_rotations_attr) {
2352 MutableSpan<math::Quaternion> begin_rotations =
2353 tls.allocator.allocate_array<math::Quaternion>(pin_num);
2354 threading::parallel_for(pin_selection.index_range(), 1024, [&](const IndexRange range) {
2355 for (const int pin_i : range) {
2356 const int point_i = points[pin_i];
2357 const bool was_pinned = prev_selection_attr[point_i];
2358 if (was_pinned) {
2359 begin_rotations[pin_i] = prev_rotations_attr[point_i];
2360 continue;
2361 }
2362 begin_rotations[pin_i] = geo_data.rotation_attr.span[point_i];
2363 }
2364 });
2365 constraint_usage.begin_rotations = begin_rotations;
2366 }
2367 else {
2368 constraint_usage.begin_rotations = end_rotations;
2369 }
2370 }
2371 }
2372 }
2373
2374 void create_chunk_constraints__pin_rotations(TLS &tls, const int chunk_i)
2375 {
2376 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
2377 ChunkData &chunk_data = chunks_data_[chunk_i];
2378 const GeometryData &geo_data = *geometries_.data[chunk.data_key_i];
2379 for (const int constraint_usage_i : geo_data.pin_rotation_constraints.index_range()) {
2380 const PinRotationConstraintUsage &constraint_usage =
2381 geo_data.pin_rotation_constraints[constraint_usage_i];
2382 const PinRotationConstraint &constraint =
2383 constraints_.pin_rotation_constraints[constraint_usage.constraint_i];
2384
2385 const IndexRange pin_range = unique_sorted_indices::find_content_range<int>(
2386 constraint_usage.points, chunk.points_range);
2387 if (pin_range.is_empty()) {
2388 continue;
2389 }
2390 chunk_data.pin_rotation_constraints.append({constraint_usage_i, pin_range});
2391 chunk_data.static_constraints.append(&tls.scope.construct<xpbd::PinRotationConstraintSet>(
2392 chunk.data_key_i,
2393 constraint_usage.points.slice(pin_range),
2394 constraint_usage.current_rotations.slice(pin_range),
2395 constraint_usage.compliances.slice(pin_range),
2396 error_scale_from_threshold(constraint.error_threshold),
2397 constraint_usage.lambdas.slice(pin_range)));
2398 }
2399 }
2400
2401 struct ResidualErrorTLS {
2402 float total_error_squared = 0.0f;
2403 int total_error_count = 0;
2404 };
2405
2406 Result do_simulation()
2407 {
2408 this->prepare_solver_geometry_refs();
2409 float average_error_squared = 0.0f;
2410
2411 if (this->support_chunk_simulation()) {
2412 threading::EnumerableThreadSpecific<ResidualErrorTLS> error_tls;
2413
2414 this->parallel_for_each_chunk(1, [&](const int chunk_i) {
2415 float chunk_error_squared;
2416 int chunk_error_count;
2417 int solver_refs_i = 0;
2418 for (const int substep_i : IndexRange(substeps_)) {
2419 const SubstepInterval substep(
2420 substeps_, substep_i, interpolation_begin_, interpolation_end_);
2421 this->simulate__update_pins__chunk(chunk_i, substep);
2422 this->simulate__inertial_update__chunk(chunk_i, solver_refs_i);
2423 this->simulate__gather_dynamic_constraints__chunk(substep, chunk_i, solver_refs_i);
2424 this->simulate__reset_forces__chunk(chunk_i);
2425
2426 const Span<xpbd::GeometryRef> solver_refs = geometries_.solver_refs[solver_refs_i];
2427 xpbd::ConstraintSetParams solve_params{solver_refs, sub_delta_time_};
2428 for ([[maybe_unused]] const int iter_i : IndexRange(constraint_iterations_)) {
2429 xpbd::GaussSeidelUpdater updater{solver_refs};
2430 this->simulate__position_solve__single_iteration__chunk(
2431 chunk_i, solve_params, updater);
2432 chunk_error_squared = updater.total_error_squared();
2433 chunk_error_count = updater.total_error_count();
2434 }
2435
2436 this->simulate__update_velocities__chunk(chunk_i, solver_refs_i);
2437 this->simulate__velocity_solve__chunk(chunk_i, solver_refs_i);
2438 solver_refs_i = 1 - solver_refs_i;
2439 }
2440 this->simulate__ensure_final_data_in_outputs__chunk(chunk_i);
2441
2442 if (chunk_error_count) {
2443 error_tls.local().total_error_squared += chunk_error_squared;
2444 error_tls.local().total_error_count += chunk_error_count;
2445 }
2446 });
2447
2448 float total_error_squared = 0.0f;
2449 int total_error_count = 0;
2450 for (const ResidualErrorTLS &error : error_tls) {
2451 total_error_squared += error.total_error_squared;
2452 total_error_count += error.total_error_count;
2453 }
2454 if (total_error_count) {
2455 average_error_squared = total_error_squared / total_error_count;
2456 }
2457 }
2458 else {
2459 int solver_refs_i = 0;
2460 for (const int substep_i : IndexRange(substeps_)) {
2461 const SubstepInterval substep(
2462 substeps_, substep_i, interpolation_begin_, interpolation_end_);
2463 this->parallel_for_each_chunk(16, [&](const int chunk_i) {
2464 this->simulate__update_pins__chunk(chunk_i, substep);
2465 this->simulate__inertial_update__chunk(chunk_i, solver_refs_i);
2466 });
2467 this->simulate__gather_dynamic_constraints(substep, solver_refs_i);
2468 this->simulate__reset_forces();
2469 for ([[maybe_unused]] const int iter_i : IndexRange(constraint_iterations_)) {
2470 this->simulate__position_solve__single_iteration(solver_refs_i, average_error_squared);
2471 }
2472 this->parallel_for_each_chunk(16, [&](const int chunk_i) {
2473 this->simulate__update_velocities__chunk(chunk_i, solver_refs_i);
2474 });
2475 this->simulate__velocity_solve(solver_refs_i);
2476 this->parallel_for_each_chunk(16, [&](const int chunk_i) {
2477 this->simulate__ensure_final_data_in_outputs__chunk(chunk_i);
2478 });
2479 solver_refs_i = 1 - solver_refs_i;
2480 }
2481 }
2482
2483 return Result{math::sqrt(average_error_squared)};
2484 }
2485
2486 bool support_chunk_simulation() const
2487 {
2488 for (const int data_key_i : geometries_.data_keys.index_range()) {
2489 const GeometryData &geo_data = *geometries_.data[data_key_i];
2490 if (!geo_data.static_constraints.is_empty()) {
2491 return false;
2492 }
2493 }
2494 return true;
2495 }
2496
2497 void prepare_solver_geometry_refs()
2498 {
2499 for (const int direction : IndexRange(2)) {
2500 Array<xpbd::GeometryRef> &refs = geometries_.solver_refs[direction];
2501 refs.reinitialize(geometries_.data_keys.size());
2502 for (const int data_key_i : geometries_.data_keys.index_range()) {
2503 GeometryData &geo_data = *geometries_.data[data_key_i];
2504 xpbd::GeometryRef &ref = refs[data_key_i];
2505
2506 if (direction == 0) {
2507 ref.positions = geo_data.temp_positions;
2508 ref.prev_positions = geo_data.position_attr.span;
2509 if (geo_data.uses_rotation) {
2510 ref.rotations = geo_data.temp_rotations;
2511 ref.prev_rotations = geo_data.rotation_attr.span;
2512 }
2513 }
2514 else {
2515 ref.positions = geo_data.position_attr.span;
2516 ref.prev_positions = geo_data.temp_positions;
2517 if (geo_data.uses_rotation) {
2518 ref.rotations = geo_data.rotation_attr.span;
2519 ref.prev_rotations = geo_data.temp_rotations;
2520 }
2521 }
2522 ref.velocities = geo_data.velocity_attr.span;
2523 ref.inv_masses = geo_data.inv_masses;
2524 if (geo_data.uses_rotation) {
2525 ref.angular_velocities = geo_data.angular_velocity_attr.span;
2526 ref.moments_of_inertia = geo_data.moments_of_inertia;
2527 ref.inv_moments_of_inertia = geo_data.inv_moments_of_inertia;
2528 }
2529 }
2530 }
2531 }
2532
2533 void simulate__update_pins__chunk(const int chunk_i, const SubstepInterval &substep)
2534 {
2535 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
2536 const int data_key_i = chunk.data_key_i;
2537 GeometryData &geo_data = *geometries_.data[data_key_i];
2538 ChunkData &chunk_data = chunks_data_[chunk_i];
2539
2540 /* Update animated pin positions. */
2541 for (const PinPositionConstraintChunkUsage &constraint_chunk_usage :
2542 chunk_data.pin_position_constraints)
2543 {
2544 const PinPositionConstraintUsage &constraint_usage =
2545 geo_data.pin_position_constraints[constraint_chunk_usage.constraint_usage_i];
2546 for (const int pin_i : constraint_chunk_usage.pin_range) {
2547 const float3 &begin_pos = constraint_usage.begin_positions[pin_i];
2548 const float3 &end_pos = constraint_usage.end_positions[pin_i];
2549 const float3 pin_pos = math::interpolate(begin_pos, end_pos, substep.interpolate_end);
2550 constraint_usage.current_positions[pin_i] = pin_pos;
2551 }
2552 }
2553 if (geo_data.uses_rotation) {
2554 for (const PinRotationConstraintChunkUsage &constraint_chunk_usage :
2555 chunk_data.pin_rotation_constraints)
2556 {
2557 const PinRotationConstraintUsage &constraint_usage =
2558 geo_data.pin_rotation_constraints[constraint_chunk_usage.constraint_usage_i];
2559 for (const int pin_i : constraint_chunk_usage.pin_range) {
2560 const math::Quaternion &begin_rot = constraint_usage.begin_rotations[pin_i];
2561 const math::Quaternion &end_rot = constraint_usage.end_rotations[pin_i];
2562 const math::Quaternion pin_rot = math::interpolate(
2563 begin_rot, end_rot, substep.interpolate_end);
2564 constraint_usage.current_rotations[pin_i] = pin_rot;
2565 }
2566 }
2567 }
2568 }
2569
2570 void simulate__inertial_update__chunk(const int chunk_i, const int solver_refs_i)
2571 {
2572 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
2573 const IndexRange points_range = chunk.points_range;
2574 const int data_key_i = chunk.data_key_i;
2575 GeometryData &geo_data = *geometries_.data[data_key_i];
2576 xpbd::GeometryRef &ref = geometries_.solver_refs[solver_refs_i][data_key_i];
2577
2578 this->integrate_linear_velocities(sub_delta_time_,
2579 ref.prev_positions.slice(points_range),
2580 ref.positions.slice(points_range),
2581 geo_data.velocity_attr.span.slice(points_range),
2582 geo_data.inv_masses.as_span().slice(points_range),
2583 geo_data.external_force_attr.slice(points_range));
2584 if (geo_data.uses_rotation) {
2585 this->integrate_angular_velocities(
2586 sub_delta_time_,
2587 ref.prev_rotations.slice(points_range),
2588 ref.rotations.slice(points_range),
2589 geo_data.angular_velocity_attr.span.slice(points_range),
2590 geo_data.inv_moments_of_inertia.as_span().slice(points_range),
2591 geo_data.external_torque_attr.slice(points_range));
2592 }
2593 }
2594
2595 void simulate__gather_dynamic_constraints(const SubstepInterval &substep,
2596 const int solver_refs_i)
2597 {
2598 this->parallel_for_each_chunk(1, [&](const int chunk_i) {
2599 this->simulate__gather_dynamic_constraints__chunk(substep, chunk_i, solver_refs_i);
2600 });
2601 }
2602
2603 void simulate__gather_dynamic_constraints__chunk(const SubstepInterval &substep,
2604 const int chunk_i,
2605 const int solver_refs_i)
2606 {
2607 const float max_distance = this->get_max_search_distance(sub_delta_time_);
2608 ChunkData &chunk_data = chunks_data_[chunk_i];
2609 const ExternalFaceContacts &prev_face_contacts = chunk_data.external_face_contacts;
2610 const ExternalEdgeContacts &prev_edge_contacts = chunk_data.external_edge_contacts;
2611 ExternalFaceContacts new_face_contacts;
2612 ExternalEdgeContacts new_edge_contacts;
2613 this->gather_contacts__mesh_colliders(chunk_i,
2614 max_distance,
2615 solver_refs_i,
2616 substep,
2617 prev_face_contacts,
2618 prev_edge_contacts,
2619 new_face_contacts,
2620 new_edge_contacts);
2621
2622 for (const int i : IndexRange(new_face_contacts.points.size())) {
2623 new_face_contacts.collider_velocities.append(
2624 math::safe_divide(new_face_contacts.collider_motion[i], sub_delta_time_));
2625 }
2626 for (const int i : IndexRange(new_edge_contacts.point_pairs.size())) {
2627 new_edge_contacts.collider_velocities.append(
2628 math::safe_divide(new_edge_contacts.collider_motion[i], sub_delta_time_));
2629 }
2630 chunk_data.external_face_contacts = std::move(new_face_contacts);
2631 chunk_data.external_edge_contacts = std::move(new_edge_contacts);
2632 }
2633
2634 void simulate__reset_forces()
2635 {
2636 this->parallel_for_each_chunk(
2637 16, [&](const int chunk_i) { this->simulate__reset_forces__chunk(chunk_i); });
2638 for (const int data_key_i : geometries_.data_keys.index_range()) {
2639 GeometryData &geo_data = *geometries_.data[data_key_i];
2640 for (ConstraintWithColoring &constraint : geo_data.static_constraints) {
2641 constraint.constraint->reset_forces();
2642 }
2643 }
2644 }
2645
2646 void simulate__reset_forces__chunk(const int chunk_i)
2647 {
2648 ChunkData &chunk_data = chunks_data_[chunk_i];
2649 chunk_data.external_face_contacts.lambdas_normal.fill(0.0f);
2650 chunk_data.external_face_contacts.lambdas_friction.fill(0.0f);
2651 for (xpbd::ConstraintSet *constraint : chunk_data.static_constraints) {
2652 constraint->reset_forces();
2653 }
2654 for (xpbd::VelocityConstraintSet *constraint : chunk_data.static_velocity_constraints) {
2655 constraint->reset_forces();
2656 }
2657 }
2658
2659 void simulate__position_solve__single_iteration(const int solver_refs_i,
2660 float &r_average_error_squared)
2661 {
2662 const Span<xpbd::GeometryRef> solver_refs = geometries_.solver_refs[solver_refs_i];
2663 xpbd::ConstraintSetParams solve_params{solver_refs, sub_delta_time_};
2664 threading::EnumerableThreadSpecific<ResidualErrorTLS> error_tls;
2665
2666 this->parallel_for_each_chunk(1, [&](const int chunk_i) {
2667 xpbd::GaussSeidelUpdater updater{solver_refs};
2668 this->simulate__position_solve__single_iteration__chunk(chunk_i, solve_params, updater);
2669 error_tls.local().total_error_squared += updater.total_error_squared();
2670 error_tls.local().total_error_count += updater.total_error_count();
2671 });
2672
2673 for (const int data_key_i : geometries_.data_keys.index_range()) {
2674 const GeometryData &geo_data = *geometries_.data[data_key_i];
2675 for (const ConstraintWithColoring &constraint : geo_data.static_constraints) {
2676 for (const int color_i : constraint.coloring.colors.index_range()) {
2677 const IndexMask &mask = constraint.coloring.colors[color_i];
2678 threading::parallel_for(mask.index_range(), 512, [&](const IndexRange range) {
2679 const IndexMask sliced_mask = mask.slice(range);
2680 xpbd::GaussSeidelUpdater updater{solver_refs};
2681 constraint.constraint->solve_sequential(solve_params, updater, sliced_mask);
2682 error_tls.local().total_error_squared += updater.total_error_squared();
2683 error_tls.local().total_error_count += updater.total_error_count();
2684 });
2685 }
2686 }
2687 }
2688
2689 float total_error_squared = 0.0f;
2690 int total_error_count = 0;
2691 for (const ResidualErrorTLS &error : error_tls) {
2692 total_error_squared += error.total_error_squared;
2693 total_error_count += error.total_error_count;
2694 }
2695 if (total_error_count) {
2696 r_average_error_squared = total_error_squared / total_error_count;
2697 }
2698 }
2699
2700 void simulate__position_solve__single_iteration__chunk(const int chunk_i,
2701 xpbd::ConstraintSetParams solve_params,
2702 xpbd::GaussSeidelUpdater &updater)
2703 {
2704 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
2705 ChunkData &chunk_data = chunks_data_[chunk_i];
2706
2707 for (xpbd::ConstraintSet *constraint : chunk_data.static_constraints) {
2708 constraint->solve_sequential_all(solve_params, updater);
2709 }
2710
2711 if (!chunk_data.external_face_contacts.points.is_empty()) {
2712 ExternalFaceContacts &contacts = chunk_data.external_face_contacts;
2713 xpbd::CollisionFaceConstraintSet constraint(chunk.data_key_i,
2714 contacts.points,
2715 contacts.point_radii,
2716 contacts.positions_on_face,
2717 contacts.collider_motion,
2718 contacts.face_normals,
2719 contacts.face_margins,
2720 contacts.compliance_terms,
2721 contacts.static_frictions,
2722 contacts.dynamic_frictions,
2723 contacts.error_scales,
2724 contacts.active_states,
2725 contacts.lambdas_normal);
2726 constraint.solve_sequential_all(solve_params, updater);
2727 }
2728 if (!chunk_data.external_edge_contacts.point_pairs.is_empty()) {
2729 ExternalEdgeContacts &contacts = chunk_data.external_edge_contacts;
2730 xpbd::CollisionEdgeConstraintSet constraint(chunk.data_key_i,
2731 contacts.point_pairs,
2732 contacts.point_radii,
2733 contacts.positions_on_edge,
2734 contacts.collider_motion,
2735 contacts.edge_directions,
2736 contacts.edge_normals,
2737 contacts.edge_margins,
2738 contacts.compliance_terms,
2739 contacts.static_frictions,
2740 contacts.dynamic_frictions,
2741 contacts.error_scales,
2742 contacts.active_states,
2743 contacts.point_mix_factors,
2744 contacts.lambdas_normal);
2745 constraint.solve_sequential_all(solve_params, updater);
2746 }
2747 }
2748
2749 void simulate__update_velocities__chunk(const int chunk_i, const int solver_refs_i)
2750 {
2751 if (sub_delta_time_ <= 0.0f) {
2752 /* This may happen for example on the first frame when no time has passed yet. */
2753 return;
2754 }
2755
2756 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
2757 const IndexRange points_range = chunk.points_range;
2758 const int data_key_i = chunk.data_key_i;
2759 GeometryData &geo_data = *geometries_.data[data_key_i];
2760 xpbd::GeometryRef &ref = geometries_.solver_refs[solver_refs_i][data_key_i];
2761 this->update_linear_velocities(sub_delta_time_,
2762 ref.prev_positions.slice(points_range),
2763 ref.positions.slice(points_range),
2764 geo_data.velocity_attr.span.slice(points_range));
2765 if (geo_data.uses_rotation) {
2766 this->update_angular_velocities(sub_delta_time_,
2767 ref.prev_rotations.slice(points_range),
2768 ref.rotations.slice(points_range),
2769 geo_data.angular_velocity_attr.span.slice(points_range));
2770 }
2771 }
2772
2773 void simulate__velocity_solve(const int solver_refs_i)
2774 {
2775 this->parallel_for_each_chunk(8, [&](const int chunk_i) {
2776 this->simulate__velocity_solve__chunk(chunk_i, solver_refs_i);
2777 });
2778 }
2779
2780 void simulate__velocity_solve__chunk(const int chunk_i, const int solver_refs_i)
2781 {
2782 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
2783 ChunkData &chunk_data = chunks_data_[chunk_i];
2784
2785 const Span<xpbd::GeometryRef> solver_refs = geometries_.solver_refs[solver_refs_i];
2786 xpbd::ConstraintSetParams params{solver_refs, sub_delta_time_};
2787 xpbd::VelocityUpdater velocity_updater{solver_refs};
2788
2789 for (xpbd::VelocityConstraintSet *constraint : chunk_data.static_velocity_constraints) {
2790 constraint->solve_sequential(params, velocity_updater);
2791 }
2792
2793 if (!chunk_data.external_face_contacts.points.is_empty()) {
2794 ExternalFaceContacts &contacts = chunk_data.external_face_contacts;
2795 xpbd::FrictionFaceConstraintSet constraint(chunk.data_key_i,
2796 contacts.points,
2797 contacts.face_normals,
2798 contacts.collider_velocities,
2799 contacts.dynamic_frictions,
2800 contacts.lambdas_normal,
2801 contacts.lambdas_friction);
2802 constraint.solve_sequential(params, velocity_updater);
2803 }
2804 if (!chunk_data.external_edge_contacts.point_pairs.is_empty()) {
2805 ExternalEdgeContacts &contacts = chunk_data.external_edge_contacts;
2806 xpbd::FrictionEdgeConstraintSet constraint(chunk.data_key_i,
2807 contacts.point_pairs,
2808 contacts.edge_normals,
2809 contacts.collider_velocities,
2810 contacts.dynamic_frictions,
2811 contacts.lambdas_normal,
2812 contacts.point_mix_factors,
2813 contacts.lambdas_friction);
2814 constraint.solve_sequential(params, velocity_updater);
2815 }
2816 }
2817
2818 void simulate__ensure_final_data_in_outputs__chunk(const int chunk_i)
2819 {
2820 if (substeps_ % 2 == 0) {
2821 /* Nothing to do. */
2822 return;
2823 }
2824 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
2825 GeometryData &geo_data = *geometries_.data[chunk.data_key_i];
2826 const IndexRange points_range = chunk.points_range;
2827 geo_data.position_attr.span.slice(points_range)
2828 .copy_from(geo_data.temp_positions.as_span().slice(points_range));
2829 if (geo_data.uses_rotation) {
2830 geo_data.rotation_attr.span.slice(points_range)
2831 .copy_from(geo_data.temp_rotations.as_span().slice(points_range));
2832 }
2833 }
2834
2835 void finish_common_attribute_writers()
2836 {
2837 for (const int data_key_i : geometries_.data_keys.index_range()) {
2838 GeometryData &geo_data = *geometries_.data[data_key_i];
2839
2840 geo_data.position_attr.finish();
2841 geo_data.velocity_attr.finish();
2842 geo_data.rotation_attr.finish();
2843 geo_data.angular_velocity_attr.finish();
2844 }
2845 }
2846
2847 void integrate_linear_velocities(const float delta_time,
2848 const Span<float3> old_positions,
2849 MutableSpan<float3> new_positions,
2850 MutableSpan<float3> velocities,
2851 const Span<float> inv_masses,
2852 const Span<float3> forces)
2853 {
2854 for (const int i : old_positions.index_range()) {
2855 const float3 external_force = forces[i];
2856 const float inv_mass = inv_masses[i];
2857 const float3 &old_pos = old_positions[i];
2858 const float3 acceleration = external_force * inv_mass;
2859 const float3 new_velocity = velocities[i] + acceleration * delta_time;
2860 velocities[i] = new_velocity;
2861 new_positions[i] = old_pos + new_velocity * delta_time;
2862 }
2863 }
2864
2865 void integrate_angular_velocities(const float delta_time,
2866 const Span<math::Quaternion> old_rotations,
2867 MutableSpan<math::Quaternion> new_rotations,
2868 MutableSpan<float3> angular_velocities,
2869 const Span<float3> inv_inertias,
2870 const Span<float3> torques)
2871 {
2872 for (const int i : old_rotations.index_range()) {
2873 const math::Quaternion &old_rotation = old_rotations[i];
2874 const float3 &external_torque = torques[i];
2875 const float3 &inv_inertia = inv_inertias[i];
2876 if (math::is_zero(inv_inertia)) {
2877 new_rotations[i] = old_rotation;
2878 continue;
2879 }
2880 float3 &angular_velocity = angular_velocities[i];
2881 const float3 precession = math::cross(angular_velocity,
2882 math::safe_divide(angular_velocity, inv_inertia));
2883 angular_velocity += delta_time * (external_torque - precession) * inv_inertia;
2884 const math::Quaternion direction = old_rotation * math::Quaternion(0, angular_velocity);
2885 new_rotations[i] = math::normalize(
2886 math::Quaternion(float4(old_rotation) + delta_time * 0.5f * float4(direction)));
2887 }
2888 }
2889
2890 void update_linear_velocities(const float delta_time,
2891 const Span<float3> prev_positions,
2892 const Span<float3> new_positions,
2893 MutableSpan<float3> r_velocities)
2894 {
2895 const float inv_delta_time = math::safe_rcp(delta_time);
2896 for (const int i : r_velocities.index_range()) {
2897 const float3 &old_pos = prev_positions[i];
2898 const float3 &new_pos = new_positions[i];
2899 const float3 diff = new_pos - old_pos;
2900 const float3 velocity = diff * inv_delta_time;
2901 r_velocities[i] = velocity;
2902 }
2903 }
2904
2905 void update_angular_velocities(const float delta_time,
2906 const Span<math::Quaternion> prev_rotations,
2907 const Span<math::Quaternion> new_rotations,
2908 MutableSpan<float3> r_angular_velocities)
2909 {
2910 const float inv_delta_time = math::safe_rcp(delta_time);
2911 for (const int i : r_angular_velocities.index_range()) {
2912 float3 diff =
2913 (math::invert_normalized(prev_rotations[i]) * new_rotations[i]).imaginary_part();
2914 for (const int j : IndexRange(3)) {
2915 if (math::abs(diff[j]) < 1e-5f) {
2916 diff[j] = 0.0f;
2917 }
2918 }
2919 const float3 new_angular_velocity = 2.0f * diff * inv_delta_time;
2920 r_angular_velocities[i] = new_angular_velocity;
2921 }
2922 }
2923
2924 float compute_contact_friction(const float point_friction, const float collider_friction) const
2925 {
2926 return math::sqrt(point_friction * collider_friction);
2927 }
2928
2929 float get_max_search_distance(const float delta_time)
2930 {
2931 /* This is 60 m/s or 216 km/h. */
2932 constexpr float max_velocity = 60.0f;
2933 const float max_search_distance = 2.0f * max_velocity * delta_time;
2934 return max_search_distance;
2935 }
2936
2937 template<typename T>
2938 bke::SpanAttributeWriter<T> ensure_attribute(bke::MutableAttributeAccessor attributes,
2939 const StringRef name,
2940 const bke::AttrDomain domain)
2941 {
2942 const std::optional<bke::AttributeMetaData> meta_data = attributes.lookup_meta_data(name);
2943 if (meta_data) {
2944 if (meta_data->domain != domain ||
2945 meta_data->data_type != bke::cpp_type_to_attribute_type(CPPType::get<T>()))
2946 {
2947 attributes.remove(name);
2948 }
2949 }
2950 return attributes.lookup_or_add_for_write_span<T>(name, domain);
2951 }
2952
2953 template<typename T>
2954 bke::SpanAttributeWriter<T> get_output_attribute_writer(const int geo_data_i,
2955 const StringRef name,
2956 const AttrDomain domain)
2957 {
2958 if (name.is_empty()) {
2959 return {};
2960 }
2961 GeometryData &geo_data = *geometries_.data[geo_data_i];
2962 return geo_data.attributes.lookup_or_add_for_write_span<T>(name, domain);
2963 }
2964
2965 const Bundle *get_previous_bundle(const Bundle &bundle) const
2966 {
2967 const BundlePtr *previous_bundle_ptr = bundle.lookup_ptr<BundlePtr>(
2968 *BundleKey::from_str("previous"));
2969 if (!previous_bundle_ptr || !*previous_bundle_ptr) {
2970 return nullptr;
2971 }
2972 return &**previous_bundle_ptr;
2973 }
2974
2975 bool effector_applies_to_geometry([[maybe_unused]] const StringRef effector_path,
2976 const Bundle &effector,
2977 const int data_key_i) const
2978 {
2979 const DataKey &data_key = geometries_.data_keys[data_key_i];
2980 const GeometrySetData &geo_set_data = geometries_.geometry_sets[data_key.geo_bundle_i];
2981
2982 const std::string filter =
2983 effector.lookup<std::string>(*BundleKey::from_str("filter")).value_or("");
2984 const bool match = tag_filter_matches(filter, geo_set_data.tags);
2985 return match;
2986 }
2987
2988 void parallel_for_each_chunk(const int grain_size, const FunctionRef<void(int chunk_i)> fn)
2989 {
2991 geometries_.chunks.index_range(), grain_size, [&](const IndexRange chunk_range) {
2992 for (const int chunk_i : chunk_range) {
2993 fn(chunk_i);
2994 }
2995 });
2996 }
2997
2998 void write_back_geometries_to_world()
2999 {
3000 for (const int geo_bundle_i : geometries_.geometry_sets.index_range()) {
3001 GeometrySetData &geo_set_data = geometries_.geometry_sets[geo_bundle_i];
3002 world_.add_path_override(geo_set_data.path, std::move(geo_set_data.geometry));
3003 }
3004 }
3005
3006 PointCloud *write_back__plane_contacts(const IndexRange mesh_colliders_range,
3007 const OffsetIndices<int> points_by_chunk)
3008 {
3010 points_by_chunk.total_size());
3011 MutableAttributeAccessor attributes = pointcloud->attributes_for_write();
3012 bke::SpanAttributeWriter<int> geometries_writer =
3013 attributes.lookup_or_add_for_write_only_span<int>("geometry", AttrDomain::Point);
3014 bke::SpanAttributeWriter<int> colliders_writer =
3015 attributes.lookup_or_add_for_write_only_span<int>("collider", AttrDomain::Point);
3016 bke::SpanAttributeWriter<int> geometry_points0_writer =
3017 attributes.lookup_or_add_for_write_only_span<int>("geometry_point0", AttrDomain::Point);
3018 MutableSpan<float3> positions = pointcloud->positions_for_write();
3019 bke::SpanAttributeWriter<float3> collider_velocities_writer =
3020 attributes.lookup_or_add_for_write_only_span<float3>("collider_velocity",
3021 AttrDomain::Point);
3022 bke::SpanAttributeWriter<float3> normals_writer =
3023 attributes.lookup_or_add_for_write_only_span<float3>("normal", AttrDomain::Point);
3024 bke::SpanAttributeWriter<float> static_frictions_writer =
3025 attributes.lookup_or_add_for_write_only_span<float>("static_friction", AttrDomain::Point);
3026 bke::SpanAttributeWriter<float> dynamic_frictions_writer =
3027 attributes.lookup_or_add_for_write_only_span<float>("dynamic_friction", AttrDomain::Point);
3028 bke::SpanAttributeWriter<bool> active_states_writer =
3029 attributes.lookup_or_add_for_write_only_span<bool>("active", AttrDomain::Point);
3030 bke::SpanAttributeWriter<float> lambdas_normal_writer =
3031 attributes.lookup_or_add_for_write_only_span<float>("lambda_normal", AttrDomain::Point);
3032 bke::SpanAttributeWriter<float> lambdas_friction_writer =
3033 attributes.lookup_or_add_for_write_only_span<float>("lambda_friction", AttrDomain::Point);
3034
3035 this->parallel_for_each_chunk(16, [&](const int chunk_i) {
3036 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
3037 const ChunkData &chunk_data = chunks_data_[chunk_i];
3038 const ExternalFaceContacts &contacts = chunk_data.external_face_contacts;
3039
3040 const IndexRange points = points_by_chunk[chunk_i];
3041 if (points.is_empty()) {
3042 /* Avoids checking the filter a second time. */
3043 return;
3044 }
3045
3046 /* Store collider indices and affected geometry point indices that map a contact to the
3047 * simulated geometry. */
3048 MutableSpan<int> geometries = geometries_writer.span.slice(points);
3049 MutableSpan<int> colliders = colliders_writer.span.slice(points);
3050 MutableSpan<int> geometry_points0 = geometry_points0_writer.span.slice(points);
3051
3052 geometries.fill(chunk.data_key_i);
3053 for (const auto &item : contacts.mesh_contact_indices.items()) {
3054 colliders[item.value] = mesh_colliders_range[item.key.mesh_collider_i];
3055 geometry_points0[item.value] = contacts.points[item.value];
3056 }
3057
3058 array_utils::copy(contacts.positions_on_face.as_span(), positions.slice(points));
3059 array_utils::copy(contacts.collider_velocities.as_span(),
3060 collider_velocities_writer.span.slice(points));
3061 array_utils::copy(contacts.face_normals.as_span(), normals_writer.span.slice(points));
3062 array_utils::copy(contacts.static_frictions.as_span(),
3063 static_frictions_writer.span.slice(points));
3064 array_utils::copy(contacts.dynamic_frictions.as_span(),
3065 dynamic_frictions_writer.span.slice(points));
3066 array_utils::copy(contacts.active_states.as_span(), active_states_writer.span.slice(points));
3067 array_utils::copy(contacts.lambdas_normal.as_span(),
3068 lambdas_normal_writer.span.slice(points));
3069 array_utils::copy(contacts.lambdas_friction.as_span(),
3070 lambdas_friction_writer.span.slice(points));
3071 });
3072 pointcloud->tag_positions_changed();
3073 geometries_writer.finish();
3074 colliders_writer.finish();
3075 geometry_points0_writer.finish();
3076 collider_velocities_writer.finish();
3077 normals_writer.finish();
3078 static_frictions_writer.finish();
3079 dynamic_frictions_writer.finish();
3080 active_states_writer.finish();
3081 lambdas_normal_writer.finish();
3082 lambdas_friction_writer.finish();
3083
3084 return pointcloud;
3085 }
3086
3087 PointCloud *write_back__edge_contacts(const IndexRange mesh_colliders_range,
3088 const OffsetIndices<int> points_by_chunk)
3089 {
3091 points_by_chunk.total_size());
3092 MutableAttributeAccessor attributes = pointcloud->attributes_for_write();
3093 bke::SpanAttributeWriter<int> geometries_writer =
3094 attributes.lookup_or_add_for_write_only_span<int>("geometry", AttrDomain::Point);
3095 bke::SpanAttributeWriter<int> colliders_writer =
3096 attributes.lookup_or_add_for_write_only_span<int>("collider", AttrDomain::Point);
3097 bke::SpanAttributeWriter<int> geometry_points0_writer =
3098 attributes.lookup_or_add_for_write_only_span<int>("geometry_point0", AttrDomain::Point);
3099 bke::SpanAttributeWriter<int> geometry_points1_writer =
3100 attributes.lookup_or_add_for_write_only_span<int>("geometry_point1", AttrDomain::Point);
3101 MutableSpan<float3> positions = pointcloud->positions_for_write();
3102 bke::SpanAttributeWriter<float3> collider_velocities_writer =
3103 attributes.lookup_or_add_for_write_only_span<float3>("collider_velocity",
3104 AttrDomain::Point);
3105 bke::SpanAttributeWriter<float3> normals_writer =
3106 attributes.lookup_or_add_for_write_only_span<float3>("normal", AttrDomain::Point);
3107 bke::SpanAttributeWriter<float> static_frictions_writer =
3108 attributes.lookup_or_add_for_write_only_span<float>("static_friction", AttrDomain::Point);
3109 bke::SpanAttributeWriter<float> dynamic_frictions_writer =
3110 attributes.lookup_or_add_for_write_only_span<float>("dynamic_friction", AttrDomain::Point);
3111 bke::SpanAttributeWriter<bool> active_states_writer =
3112 attributes.lookup_or_add_for_write_only_span<bool>("active", AttrDomain::Point);
3113 bke::SpanAttributeWriter<float> lambdas_normal_writer =
3114 attributes.lookup_or_add_for_write_only_span<float>("lambda_normal", AttrDomain::Point);
3115 bke::SpanAttributeWriter<float> lambdas_friction_writer =
3116 attributes.lookup_or_add_for_write_only_span<float>("lambda_friction", AttrDomain::Point);
3117
3118 this->parallel_for_each_chunk(16, [&](const int chunk_i) {
3119 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
3120 const ChunkData &chunk_data = chunks_data_[chunk_i];
3121 const ExternalEdgeContacts &contacts = chunk_data.external_edge_contacts;
3122
3123 const IndexRange points = points_by_chunk[chunk_i];
3124 if (points.is_empty()) {
3125 /* Avoids checking the filter a second time. */
3126 return;
3127 }
3128
3129 /* Store collider indices and affected geometry point indices that map a contact to the
3130 * simulated geometry. */
3131 MutableSpan<int> geometries = geometries_writer.span.slice(points);
3132 MutableSpan<int> colliders = colliders_writer.span.slice(points);
3133 MutableSpan<int> geometry_points0 = geometry_points0_writer.span.slice(points);
3134 MutableSpan<int> geometry_points1 = geometry_points1_writer.span.slice(points);
3135 geometries.fill(chunk.data_key_i);
3136 for (const auto &item : contacts.mesh_contact_indices.items()) {
3137 colliders[item.value] = mesh_colliders_range[item.key.mesh_collider_i];
3138 geometry_points0[item.value] = contacts.point_pairs[item.value][0];
3139 geometry_points1[item.value] = contacts.point_pairs[item.value][1];
3140 }
3141
3142 array_utils::copy(contacts.positions_on_edge.as_span(), positions.slice(points));
3143 array_utils::copy(contacts.collider_velocities.as_span(),
3144 collider_velocities_writer.span.slice(points));
3145 array_utils::copy(contacts.edge_normals.as_span(), normals_writer.span.slice(points));
3146 array_utils::copy(contacts.static_frictions.as_span(),
3147 static_frictions_writer.span.slice(points));
3148 array_utils::copy(contacts.dynamic_frictions.as_span(),
3149 dynamic_frictions_writer.span.slice(points));
3150 array_utils::copy(contacts.active_states.as_span(), active_states_writer.span.slice(points));
3151 array_utils::copy(contacts.lambdas_normal.as_span(),
3152 lambdas_normal_writer.span.slice(points));
3153 array_utils::copy(contacts.lambdas_friction.as_span(),
3154 lambdas_friction_writer.span.slice(points));
3155 });
3156 pointcloud->tag_positions_changed();
3157 geometries_writer.finish();
3158 colliders_writer.finish();
3159 geometry_points0_writer.finish();
3160 geometry_points1_writer.finish();
3161 collider_velocities_writer.finish();
3162 normals_writer.finish();
3163 static_frictions_writer.finish();
3164 dynamic_frictions_writer.finish();
3165 active_states_writer.finish();
3166 lambdas_normal_writer.finish();
3167 lambdas_friction_writer.finish();
3168
3169 return pointcloud;
3170 }
3171
3172 void write_back__contacts()
3173 {
3174 for (CollisionContacts &contacts : this->constraints_.collision_contacts) {
3175 const Bundle &bundle = **world_.lookup_path_ptr<BundlePtr>(contacts.path);
3176 const std::string plane_points_path = Bundle::combine_path(
3177 {contacts.path, "plane_contacts"});
3178 const std::string edge_points_path = Bundle::combine_path({contacts.path, "edge_contacts"});
3179 const std::string collider_map_path = Bundle::combine_path({contacts.path, "collider_map"});
3180
3181 /* Collider paths are combined in a single array, these are offsets for collider indices. */
3182 const IndexRange geometries_range = geometries_.geometry_sets.index_range();
3183 const IndexRange mesh_colliders_range = geometries_range.after(
3184 constraints_.mesh_colliders.size());
3185 Vector<std::string> collider_paths;
3186 collider_paths.reserve(geometries_range.size() + mesh_colliders_range.size());
3187 for (const GeometrySetData &geometry_set_data : geometries_.geometry_sets) {
3188 collider_paths.append_unchecked(geometry_set_data.path);
3189 }
3190 for (const MeshCollider &collider : constraints_.mesh_colliders) {
3191 collider_paths.append_unchecked(collider.path);
3192 }
3193
3194 Array<int> plane_contacts_offsets(geometries_.chunks.size() + 1);
3195 Array<int> edge_contacts_offsets(geometries_.chunks.size() + 1);
3196 this->parallel_for_each_chunk(16, [&](const int chunk_i) {
3197 const GeometryDataChunk &chunk = geometries_.chunks[chunk_i];
3198 const ChunkData &chunk_data = chunks_data_[chunk_i];
3199
3200 if (!effector_applies_to_geometry(contacts.path, bundle, chunk.data_key_i)) {
3201 plane_contacts_offsets[chunk_i] = 0;
3202 edge_contacts_offsets[chunk_i] = 0;
3203 return;
3204 }
3205
3206 plane_contacts_offsets[chunk_i] = chunk_data.external_face_contacts.points.size();
3207 edge_contacts_offsets[chunk_i] = chunk_data.external_edge_contacts.point_pairs.size();
3208 });
3209 const OffsetIndices plane_contacts_by_chunk = offset_indices::accumulate_counts_to_offsets(
3210 plane_contacts_offsets);
3211 const OffsetIndices edge_contacts_by_chunk = offset_indices::accumulate_counts_to_offsets(
3212 edge_contacts_offsets);
3213
3214 GeometrySet plane_contacts_geometry;
3215 GeometrySet edge_contacts_geometry;
3216 if (plane_contacts_by_chunk.total_size() > 0) {
3217 plane_contacts_geometry.replace_pointcloud(
3218 write_back__plane_contacts(mesh_colliders_range, plane_contacts_by_chunk));
3219 }
3220 if (edge_contacts_by_chunk.total_size() > 0) {
3221 edge_contacts_geometry.replace_pointcloud(
3222 write_back__edge_contacts(mesh_colliders_range, edge_contacts_by_chunk));
3223 }
3224
3225 world_.add_path_override(plane_points_path, std::move(plane_contacts_geometry));
3226 world_.add_path_override(edge_points_path, std::move(edge_contacts_geometry));
3227 /* TODO Currently have to create an explicit BundleItemSocketValue to store a list with
3228 * add_path_override. It relies on socket_type_info_by_static_type, which only supports
3229 * fields and single values currently, but not lists. */
3230 world_.add_path_override(
3231 collider_map_path,
3234 bke::SocketValueVariant::from(GList::from_container(std::move(collider_paths)))});
3235 }
3236 }
3237
3238 template<typename T> VArrayRangeSpans<T> make_range_spans(TLS &tls, const VArray<T> &varray)
3239 {
3240 return VArrayRangeSpans<T>(tls.scope, varray, geometries_.max_chunk_size);
3241 }
3242
3243 template<typename T>
3244 VArray<T> lookup_attribute_default(const int data_key_i,
3245 const StringRef attribute_name,
3246 const AttrDomain domain,
3247 const T &default_value)
3248 {
3249 GeometryData &geo_data = *geometries_.data[data_key_i];
3250 VArray<T> varray = *geo_data.attributes.lookup<T>(attribute_name, domain);
3251 if (!varray) {
3252 this->report(
3254 fmt::format(
3255 "Attribute \"{}\" not found in \"{}\", using fallback value",
3256 attribute_name,
3257 geometries_.geometry_sets[geometries_.data_keys[data_key_i].geo_bundle_i].path));
3258 return VArray<T>::from_single(default_value, geo_data.attributes.domain_size(domain));
3259 }
3260 return varray;
3261 }
3262
3263 template<typename T>
3264 VArray<T> lookup_attribute_required(const int data_key_i,
3265 const StringRef attribute_name,
3266 const AttrDomain domain)
3267 {
3268 GeometryData &geo_data = *geometries_.data[data_key_i];
3269 VArray<T> varray = *geo_data.attributes.lookup<T>(attribute_name, domain);
3270 if (!varray) {
3271 this->report(
3273 fmt::format(
3274 "Attribute \"{}\" not found on \"{}\", some functionality is disabled",
3275 attribute_name,
3276 geometries_.geometry_sets[geometries_.data_keys[data_key_i].geo_bundle_i].path));
3277 }
3278 return varray;
3279 }
3280
3281 template<typename T>
3282 VArray<T> lookup_attribute_optional(const int data_key_i,
3283 const StringRef attribute_name,
3284 const AttrDomain domain)
3285 {
3286 GeometryData &geo_data = *geometries_.data[data_key_i];
3287 VArray<T> varray = *geo_data.attributes.lookup<T>(attribute_name, domain);
3288 if (!varray) {
3289 this->report(
3291 fmt::format(
3292 "Optional attribute \"{}\" not found on \"{}\"",
3293 attribute_name,
3294 geometries_.geometry_sets[geometries_.data_keys[data_key_i].geo_bundle_i].path));
3295 }
3296 return varray;
3297 }
3298
3299 std::string prop_attr_name(const StringRef effector_path, const StringRef prop_name) const
3300 {
3301 return fmt::format("sim:prop:{}:{}", effector_path, prop_name);
3302 }
3303
3304 std::string prev_prop_attr_name(const StringRef effector_path, const StringRef prop_name) const
3305 {
3306 return fmt::format("sim:prop_prev:{}:{}", effector_path, prop_name);
3307 }
3308
3309 void report(NodeWarningType type, std::string warning)
3310 {
3311 std::lock_guard<Mutex> lock(warnings_mutex_);
3312 warnings_.add({type, std::move(warning)});
3313 }
3314};
3315
3317{
3318 BundlePtr world_ptr = params.get_input<BundlePtr>("World"_ustr);
3319 if (!world_ptr) {
3321 return;
3322 }
3323 const int substeps = params.get_input<int>("Substeps"_ustr);
3324 if (substeps <= 0) {
3325 params.set_output("World"_ustr, std::move(world_ptr));
3326 return;
3327 }
3328 const int constraint_iterations = params.get_input<int>("Constraint Iterations"_ustr);
3329 const float delta_time = std::max(0.0f, params.get_input<float>("Delta Time"_ustr));
3330 Bundle &world = world_ptr.ensure_mutable_inplace();
3331 const std::string geometry_tag_filter = params.extract_input<std::string>("Filter"_ustr);
3332 const float4x4 simulation_to_world = params.extract_input<float4x4>("Simulation to World"_ustr);
3333 const float interpolation_begin = params.extract_input<float>("Begin"_ustr);
3334 const float interpolation_end = params.extract_input<float>("End"_ustr);
3335 const std::string solver_path = params.extract_input<std::string>("Solver Path"_ustr);
3336
3337 XpbdSolverStep step(world,
3338 delta_time,
3339 substeps,
3340 constraint_iterations,
3341 interpolation_begin,
3342 interpolation_end,
3343 geometry_tag_filter,
3344 simulation_to_world);
3345 step.do_step();
3346
3347 if (!solver_path.empty()) {
3348 BundlePtr solver_data_ptr = Bundle::create();
3349 Bundle &solver_data = solver_data_ptr.ensure_mutable_inplace();
3350 solver_data.add(Bundle::type_item_name, std::string(XPBDSolverDataBundle::name));
3351 solver_data.add_path("residual_error", step.result().total_residual_error);
3352 world.add_path_override(solver_path, std::move(solver_data_ptr));
3353 }
3354 for (const std::pair<NodeWarningType, std::string> &warning : step.warnings()) {
3355 params.error_message_add(warning.first, warning.second);
3356 }
3357
3358 params.set_output("World"_ustr, std::move(world_ptr));
3359}
3360
3361static void node_label(const bNodeTree * /*ntree*/,
3362 const bNode * /*node*/,
3363 char *label,
3364 const int label_maxncpy)
3365{
3367 label, CTX_IFACE_(BLT_I18NCONTEXT_ID_NODETREE, "XPBD Solver (Experimental)"), label_maxncpy);
3368}
3369
3370static void node_register()
3371{
3372 static blender::bke::bNodeType ntype;
3373
3374 geo_node_type_base(&ntype, "GeometryNodeXPBDSolver"_ustr);
3375 ntype.ui_name = "XPBD Solver";
3376 ntype.ui_description = "Simulate physics using the XPBD framework";
3379 ntype.declare = node_declare;
3381 ntype.labelfunc = node_label;
3383}
3384NOD_REGISTER_NODE(node_register)
3385
3386} // namespace blender::nodes::node_geo_xpbd_solver_cc
Low-level operations for curves.
Low-level operations for grease pencil.
#define NODE_CLASS_GEOMETRY
Definition BKE_node.hh:492
General operations for point clouds.
#define BLI_SCOPED_DEFER(function_to_defer)
#define BLT_I18NCONTEXT_ID_NODETREE
#define TIP_(msgid)
#define CTX_IFACE_(context, msgid)
#define NOD_REGISTER_NODE(REGISTER_FUNC)
volatile int lock
#define BLI_assert(a)
#define ELEM(...)
SIMD_FORCE_INLINE btVector3 transform(const btVector3 &point) const
constexpr Span slice(int64_t start, int64_t size) const
Definition BLI_span.hh:141
constexpr const T * data() const
Definition BLI_span.hh:219
constexpr int64_t first_index(const T &search_value) const
Definition BLI_span.hh:381
constexpr int64_t size() const
Definition BLI_span.hh:256
constexpr IndexRange index_range() const
Definition BLI_span.hh:405
int64_t size() const
Definition BLI_array.hh:267
const T * data() const
Definition BLI_array.hh:323
void fill(const T &value) const
Definition BLI_array.hh:283
void reinitialize(const int64_t new_size)
Definition BLI_array.hh:430
static const CPPType & get()
static IndexMask from_bools(Span< bool > bools, LinearAllocator<> &memory)
constexpr int64_t size() const
constexpr bool is_empty() const
static constexpr IndexRange from_begin_end(const int64_t begin, const int64_t end)
constexpr IndexRange()=default
constexpr IndexRange after(int64_t n) const
constexpr IndexRange slice(int64_t start, int64_t size) const
constexpr IndexRange take_front(int64_t n) const
constexpr IndexRange drop_front(int64_t n) const
const Value * lookup_ptr(const Key &key) const
Definition BLI_map.hh:508
bool add(const Key &key, const Value &value)
Definition BLI_map.hh:295
Span< Value > lookup_as(const ForwardKey &key) const
Span< Value > lookup(const Key &key) const
void add_as(ForwardKey &&key, ForwardValue &&value)
constexpr MutableSpan slice(const int64_t start, const int64_t size) const
Definition BLI_span.hh:579
constexpr void fill(const T &value) const
Definition BLI_span.hh:523
constexpr IndexRange index_range() const
Definition BLI_span.hh:676
LinearAllocator & allocator()
bool is_empty() const
Definition BLI_stack.hh:310
void push(const T &value)
Definition BLI_stack.hh:215
void materialize_compressed_to_uninitialized(const IndexMask &mask, MutableSpan< T > r_span) const
static VArray from_single(T value, const int64_t size)
bool add(const Key &key)
int64_t size() const
void append(const T &value)
void append_unchecked(const T &value)
void reserve(const int64_t min_capacity)
std::optional< AttributeMetaData > lookup_meta_data(StringRef name) const
IndexRange curves_range() const
OffsetIndices< int > points_by_curve() const
MutableAttributeAccessor attributes_for_write()
void to_geometry_set(GeometrySet &r_geometry_set) const
Definition instances.cc:115
Span< int > reference_handles() const
Definition instances.cc:222
Span< float4x4 > transforms() const
Definition instances.cc:235
Span< InstanceReference > references() const
Definition instances.cc:290
Span< int > unique_ids() const
Definition instances.cc:520
GSpanAttributeWriter lookup_or_add_for_write_span(StringRef name, AttrDomain domain, AttrType data_type, const AttributeInit &initializer=AttributeInitDefaultValue())
GSpanAttributeWriter lookup_or_add_for_write_only_span(StringRef name, AttrDomain domain, AttrType data_type)
static SocketValueVariant from(T &&value)
std::optional< RayHit > ray_intersect(const Ray &ray) const
Definition bvh.cc:439
std::optional< ClosestPointResult > closest_point(const float3 &point, float radius=std::numeric_limits< float >::max()) const
Definition bvh.cc:709
bke::CurvesGeometry & strokes_for_write()
constexpr bool is_empty() const
constexpr bool is_empty() const
void to_indices(MutableSpan< T > r_indices) const
static std::optional< BundleKey > from_str(StringRef key)
static void register_type(BundleType bundle_type)
bool add(BundleKey key, const BundleItemValue &value)
static std::string combine_path(Span< StringRef > path)
const T * lookup_path_ptr(StringRef path) const
std::optional< StringRef > type() const
void add_path_override(StringRef path, const BundleItemValue &value)
const BundleItemValue * lookup(BundleKey key) const
bool add_path(StringRef path, const BundleItemValue &value)
static GListPtr from_container(ContainerT &&container)
void error_message_add(const NodeWarningType type, StringRef message) const
T extract_input(const UString identifier)
T get_input(const UString identifier) const
void set_output(const UString identifier, T &&value)
XpbdSolverStep(Bundle &world, const float total_delta_time, const int substeps, const int constraint_iterations, const float interpolation_begin, const float interpolation_end, const StringRef geometry_tag_filter, const float4x4 &simulation_to_world)
Span< std::pair< NodeWarningType, std::string > > warnings() const
virtual void reset_forces()=0
void solve_sequential_all(const ConstraintSetParams &params, GaussSeidelUpdater &updater)
virtual void solve_sequential(const ConstraintSetParams &params, VelocityUpdater &updater)=0
IMETHOD Vector diff(const Vector &a, const Vector &b, double dt)
Definition frames.inl:1166
#define instance_id
#define index(i)
#define layer
VecBase< float, D > step(VecOp< float, D >, VecOp< float, D >) RET
MatBase< 4, 4 > float4x4
VecBase< float, 3 > float3
float2x2 invert(float2x2 mat)
#define T
double epsilon
default precision while comparing with Equal(..,..) functions. Initialized at 0.0000001.
Definition utility.cpp:22
void copy(const GVArray &src, GMutableSpan dst, exec_mode::Mode mode=exec_mode::parallel)
T mix3(const float3 &weights, const T &v0, const T &v1, const T &v2)
T mix2(float factor, const T &a, const T &b)
float3 compute_bary_coord_in_triangle(Span< float3 > vert_positions, Span< int > corner_verts, const int3 &corner_tri, const float3 &position)
GroupedSpan< int > build_edge_to_face_map(OffsetIndices< int > faces, Span< int > corner_edges, int edges_num, Array< int > &r_offsets, Array< int > &r_indices)
void node_register_type(bNodeType &ntype)
Definition node.cc:2920
bNodeSocketType * node_socket_type_find_static(int type, int subtype=0)
Definition node.cc:2975
AttrType cpp_type_to_attribute_type(const CPPType &type)
int size(const AssetLibraryReference *library_reference)
QuaternionBase< float > Quaternion
VecBase< T, 3 > normal_tri(const VecBase< T, 3 > &v1, const VecBase< T, 3 > &v2, const VecBase< T, 3 > &v3)
MatBase< T, NumCol, NumRow > transpose(const MatBase< T, NumRow, NumCol > &mat)
T safe_rcp(const T &a)
T sqrt(const T &a)
T safe_divide(const T &a, const T &b)
T distance(const T &a, const T &b)
QuaternionBase< T > normalize_and_get_length(const QuaternionBase< T > &q, T &out_length)
T dot(const QuaternionBase< T > &a, const QuaternionBase< T > &b)
bool is_zero(const T &a)
CartesianBasis invert(const CartesianBasis &basis)
T midpoint(const T &a, const T &b)
AxisSigned cross(const AxisSigned a, const AxisSigned b)
T interpolate(const T &a, const T &b, const FactorT &t)
QuaternionBase< T > invert_normalized(const QuaternionBase< T > &q)
MatBase< T, NumCol, NumRow > normalize(const MatBase< T, NumCol, NumRow > &a)
VecBase< T, 3 > to_scale(const MatBase< T, NumCol, NumRow > &mat)
T square(const T &a)
T distance_squared(const VecBase< T, Size > &a, const VecBase< T, Size > &b)
bool is_unit(const VecBase< T, Size > &a, const T epsilon=T(10) *std::numeric_limits< T >::epsilon())
T abs(const T &a)
VecBase< T, 3 > transform_direction(const MatBase< T, 3, 3 > &mat, const VecBase< T, 3 > &direction)
VecBase< T, 3 > transform_point(const CartesianBasis &basis, const VecBase< T, 3 > &v)
static void node_declare(NodeDeclarationBuilder &b)
static void node_label(const bNodeTree *, const bNode *, char *label, const int label_maxncpy)
static NestedBundleTypePtr make_world_type()
static void node_geo_exec(GeoNodeExecParams params)
std::shared_ptr< const NestedBundleType > NestedBundleTypePtr
std::shared_ptr< const FlatBundleType > FlatBundleTypePtr
bool tag_filter_matches(const StringRef tag_filter, const Set< std::string > &tags)
Vector< std::string > gather_bundle_paths_by_data_type(const Bundle &bundle, const eNodeSocketDatatype data_type)
void foreach_nested_bundle_item(const Bundle &bundle, const FunctionRef< void(Span< BundleKey >, const BundleItemValue &value)> fn)
ImplicitSharingPtr< Bundle > BundlePtr
OffsetIndices< int > accumulate_counts_to_offsets(MutableSpan< int > counts_to_offsets, int start_offset=0)
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
IndexRange find_content_range(const Span< T > indices, const IndexRange range)
unsigned __int64 uint64_t
Definition BKE_text.h:91
MINLINE int mod_i(int i, int n)
__int64 int64_t
Definition BKE_text.h:90
void isect_seg_seg_v3(const float a0[3], const float a1[3], const float b0[3], const float b1[3], float r_a[3], float r_b[3])
MINLINE void copy_v3_v3(float r[3], const float a[3])
Mesh * BKE_mesh_copy_for_eval(const Mesh &source)
int BLI_bvhtree_ray_cast_ex(const BVHTree *tree, const float co[3], const float dir[3], float radius, BVHTreeRayHit *hit, BVHTree_RayCastCallback callback, void *userdata, int flag)
char * BLI_strncpy_utf8(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
MatBase< float, 4, 4 > float4x4
MINLINE float pow2f(float x)
VecBase< float, 4 > float4
VecBase< int32_t, 2 > int2
VecBase< int32_t, 3 > int3
BMesh const char void * data
MatBase< float, 3, 3 > float3x3
void BKE_id_free(Main *bmain, void *idv)
std::mutex Mutex
Definition BLI_mutex.hh:51
PointCloud * BKE_pointcloud_new_nomain(PointCloudType type, int totpoint)
VecBase< float, 3 > float3
@ PROP_TIME_ABSOLUTE
Definition RNA_types.hh:311
DO_INLINE void filter(lfVector *V, fmatrix3x3 *S)
constexpr uint64_t get_default_hash(const T &v, const Args &...args)
Definition BLI_hash.hh:252
void geo_node_type_base(bke::bNodeType *ntype, UString idname, const std::optional< int16_t > legacy_type)
void mask(PageMask &srt, TileMaps &tilemaps, const uint3 global_id, const uint local_tile_index)
float4 transform(float4 hs_position)
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
#define min(a, b)
Definition sort.cc:38
void replace_pointcloud(PointCloud *pointcloud, GeometryOwnershipType ownership=GeometryOwnershipType::Owned)
const Instances * get_instances() const
const Mesh * get_mesh() const
static constexpr int _200
Definition BKE_node.hh:248
Defines a node type.
Definition BKE_node.hh:265
std::string ui_description
Definition BKE_node.hh:271
void(*) labelfunc(const bNodeTree *ntree, const bNode *node, char *label, int label_maxncpy)
Definition BKE_node.hh:301
NodeGeometryExecFunction geometry_node_execute
Definition BKE_node.hh:385
NodeDeclareFunction declare
Definition BKE_node.hh:393
Vector< PinPositionConstraintChunkUsage > pin_position_constraints
Vector< PinRotationConstraintChunkUsage > pin_rotation_constraints
Vector< xpbd::VelocityConstraintSet * > static_velocity_constraints
Vector< CrossEdgeLengthConstraint > cross_edge_length_constraints
Vector< RodStretchShearConstraint > rod_stretch_shear_constraints
friend bool operator==(const DataKey &a, const DataKey &b)=default
void init_or_preserve_state(const ExternalEdgeContacts &prev_contacts, const std::optional< int > &prev_i)
void init_or_preserve_state(const ExternalFaceContacts &prev_contacts, const std::optional< int > &prev_i)
std::array< Array< xpbd::GeometryRef >, 2 > solver_refs
Vector< EdgeLengthConstraintUsage > edge_length_constraints
Vector< PinPositionConstraintUsage > pin_position_constraints
Vector< RodBendTwistConstraintUsage > rod_bend_twist_constraints
bke::SpanAttributeWriter< math::Quaternion > rotation_attr
Vector< RodStretchShearConstraintUsage > rod_stretch_shear_constraints
GeometryData(const bke::MutableAttributeAccessor attributes)
Vector< PinRotationConstraintUsage > pin_rotation_constraints
Vector< CrossEdgeLengthConstraintUsage > cross_edge_length_constraints
std::variant< StaticMeshInfo, DeformingMeshInfo > mesh
friend bool operator==(const MeshContactId &a, const MeshContactId &b)=default
SubstepInterval(const int substeps, const int current_i, const float interpolation_begin, const float interpolation_end)
MutableSpan< float3 > angular_velocities
MutableSpan< math::Quaternion > rotations
Span< math::Quaternion > prev_rotations
float z
Definition sky_math.h:136
float y
Definition sky_math.h:136
float x
Definition sky_math.h:136