Debian Codegraph @

editor/scene/3d/skeleton_3d_editor_plugin.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* skeleton_3d_editor_plugin.cpp */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #include "skeleton_3d_editor_plugin.h"
32
33 #include "core/io/resource_saver.h"
34 #include "editor/animation/animation_player_editor_plugin.h"
35 #include "editor/editor_node.h"
36 #include "editor/editor_string_names.h"
37 #include "editor/editor_undo_redo_manager.h"
38 #include "editor/inspector/editor_properties.h"
39 #include "editor/inspector/editor_properties_vector.h"
40 #include "editor/scene/3d/node_3d_editor_plugin.h"
41 #include "editor/settings/editor_settings.h"
42 #include "editor/themes/editor_scale.h"
43 #include "scene/3d/mesh_instance_3d.h"
44 #include "scene/3d/physics/collision_shape_3d.h"
45 #include "scene/3d/physics/physical_bone_3d.h"
46 #include "scene/3d/physics/physical_bone_simulator_3d.h"
47 #include "scene/gui/separator.h"
48 #include "scene/gui/texture_rect.h"
49 #include "scene/resources/3d/capsule_shape_3d.h"
50 #include "scene/resources/skeleton_profile.h"
51 #include "scene/resources/surface_tool.h"
52
53 void BonePropertiesEditor::create_editors() {
54 section = memnew(EditorInspectorSection);
55 section->setup("trf_properties", label, this, Color(0.0f, 0.0f, 0.0f), true);
56 section->unfold();
57 add_child(section);
58
59 enabled_checkbox = memnew(EditorPropertyCheck());
60 enabled_checkbox->set_label("Pose Enabled");
61 enabled_checkbox->set_selectable(false);
62 enabled_checkbox->connect("property_changed", callable_mp(this, &BonePropertiesEditor::_value_changed));
63 section->get_vbox()->add_child(enabled_checkbox);
64
65 // Position property.
66 EditorPropertyRangeHint large_range_hint;
67 large_range_hint.min = -10000;
68 large_range_hint.max = 10000;
69 large_range_hint.step = 0.001;
70
71 position_property = memnew(EditorPropertyVector3());
72 position_property->setup(large_range_hint);
73 position_property->set_label("Position");
74 position_property->set_selectable(false);
75 position_property->connect("property_changed", callable_mp(this, &BonePropertiesEditor::_value_changed));
76 position_property->connect("property_keyed", callable_mp(this, &BonePropertiesEditor::_property_keyed));
77 section->get_vbox()->add_child(position_property);
78
79 // Rotation property.
80 rotation_property = memnew(EditorPropertyQuaternion());
81 // Quaternions are almost never used for human-readable values that need stepifying,
82 // so we should be more precise with their step, as much as the float precision allows.
83 #ifdef REAL_T_IS_DOUBLE
84 constexpr double QUATERNION_STEP = 1e-14;
85 #else
86 constexpr double QUATERNION_STEP = 1e-6;
87 #endif
88 EditorPropertyRangeHint quaternion_range_hint;
89 quaternion_range_hint.min = -1.0;
90 quaternion_range_hint.max = 1.0;
91 quaternion_range_hint.step = QUATERNION_STEP;
92 rotation_property->setup(quaternion_range_hint);
93 rotation_property->set_label("Rotation");
94 rotation_property->set_selectable(false);
95 rotation_property->connect("property_changed", callable_mp(this, &BonePropertiesEditor::_value_changed));
96 rotation_property->connect("property_keyed", callable_mp(this, &BonePropertiesEditor::_property_keyed));
97 section->get_vbox()->add_child(rotation_property);
98
99 // Scale property.
100 scale_property = memnew(EditorPropertyVector3());
101 scale_property->setup(large_range_hint, true);
102 scale_property->set_label("Scale");
103 scale_property->set_selectable(false);
104 scale_property->connect("property_changed", callable_mp(this, &BonePropertiesEditor::_value_changed));
105 scale_property->connect("property_keyed", callable_mp(this, &BonePropertiesEditor::_property_keyed));
106 section->get_vbox()->add_child(scale_property);
107
108 // Transform/Matrix section.
109 rest_section = memnew(EditorInspectorSection);
110 rest_section->setup("trf_properties_transform", "Rest", this, Color(0.0f, 0.0f, 0.0f), true);
111 section->get_vbox()->add_child(rest_section);
112
113 // Transform/Matrix property.
114 rest_matrix = memnew(EditorPropertyTransform3D());
115 rest_matrix->setup(large_range_hint);
116 rest_matrix->set_label("Transform");
117 rest_matrix->set_selectable(false);
118 rest_section->get_vbox()->add_child(rest_matrix);
119
120 // Bone Metadata property
121 meta_section = memnew(EditorInspectorSection);
122 meta_section->setup("bone_meta", TTR("Bone Metadata"), this, Color(.0f, .0f, .0f), true);
123 section->get_vbox()->add_child(meta_section);
124
125 EditorInspectorActionButton *add_metadata_button = memnew(EditorInspectorActionButton(TTRC("Add Bone Metadata"), SNAME("Add")));
126 add_metadata_button->connect(SceneStringName(pressed), callable_mp(this, &BonePropertiesEditor::_show_add_meta_dialog));
127 section->get_vbox()->add_child(add_metadata_button);
128
129 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
130 undo_redo->connect("version_changed", callable_mp(this, &BonePropertiesEditor::_update_properties));
131 undo_redo->connect("history_changed", callable_mp(this, &BonePropertiesEditor::_update_properties));
132 }
133
134 void BonePropertiesEditor::_notification(int p_what) {
135 switch (p_what) {
136 case NOTIFICATION_THEME_CHANGED: {
137 const Color section_color = get_theme_color(SNAME("prop_subsection"), EditorStringName(Editor));
138 section->set_bg_color(section_color);
139 rest_section->set_bg_color(section_color);
140 } break;
141 }
142 }
143
144 void BonePropertiesEditor::_value_changed(const String &p_property, const Variant &p_value, const String &p_name, bool p_changing) {
145 if (updating || !skeleton) {
146 return;
147 }
148
149 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
150 undo_redo->create_action(TTR("Set Bone Transform"), UndoRedo::MERGE_ENDS);
151 undo_redo->add_undo_property(skeleton, p_property, skeleton->get(p_property));
152 undo_redo->add_do_property(skeleton, p_property, p_value);
153
154 Skeleton3DEditor *se = Skeleton3DEditor::get_singleton();
155 if (se) {
156 undo_redo->add_do_method(se, "update_joint_tree");
157 undo_redo->add_undo_method(se, "update_joint_tree");
158 }
159
160 undo_redo->commit_action();
161 }
162
163 void BonePropertiesEditor::_meta_changed(const String &p_property, const Variant &p_value, const String &p_name, bool p_changing) {
164 if (!skeleton || p_property.get_slicec('/', 2) != "bone_meta") {
165 return;
166 }
167
168 int bone = p_property.get_slicec('/', 1).to_int();
169 if (bone >= skeleton->get_bone_count()) {
170 return;
171 }
172
173 String key = p_property.get_slicec('/', 3);
174 if (!skeleton->has_bone_meta(bone, key)) {
175 return;
176 }
177
178 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
179 undo_redo->create_action(vformat(TTR("Modify metadata '%s' for bone '%s'"), key, skeleton->get_bone_name(bone)));
180 undo_redo->add_do_property(skeleton, p_property, p_value);
181 undo_redo->add_do_method(meta_editors[p_property], "update_property");
182 undo_redo->add_undo_property(skeleton, p_property, skeleton->get_bone_meta(bone, key));
183 undo_redo->add_undo_method(meta_editors[p_property], "update_property");
184 undo_redo->commit_action();
185 }
186
187 void BonePropertiesEditor::_meta_deleted(const String &p_property) {
188 if (!skeleton || p_property.get_slicec('/', 2) != "bone_meta") {
189 return;
190 }
191
192 int bone = p_property.get_slicec('/', 1).to_int();
193 if (bone >= skeleton->get_bone_count()) {
194 return;
195 }
196
197 String key = p_property.get_slicec('/', 3);
198 if (!skeleton->has_bone_meta(bone, key)) {
199 return;
200 }
201
202 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
203 undo_redo->create_action(vformat(TTR("Remove metadata '%s' from bone '%s'"), key, skeleton->get_bone_name(bone)));
204 undo_redo->add_do_property(skeleton, p_property, Variant());
205 undo_redo->add_undo_property(skeleton, p_property, skeleton->get_bone_meta(bone, key));
206 undo_redo->commit_action();
207
208 emit_signal(SNAME("property_deleted"), p_property);
209 }
210
211 void BonePropertiesEditor::_show_add_meta_dialog() {
212 if (!add_meta_dialog) {
213 add_meta_dialog = memnew(AddMetadataDialog());
214 add_meta_dialog->connect(SceneStringName(confirmed), callable_mp(this, &BonePropertiesEditor::_add_meta_confirm));
215 add_child(add_meta_dialog);
216 }
217
218 int bone = Skeleton3DEditor::get_singleton()->get_selected_bone();
219 StringName dialog_title = skeleton->get_bone_name(bone);
220
221 List<StringName> existing_meta_keys;
222 skeleton->get_bone_meta_list(bone, &existing_meta_keys);
223 add_meta_dialog->open(dialog_title, existing_meta_keys);
224 }
225
226 void BonePropertiesEditor::_add_meta_confirm() {
227 int bone = Skeleton3DEditor::get_singleton()->get_selected_bone();
228 String name = add_meta_dialog->get_meta_name();
229 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
230 undo_redo->create_action(vformat(TTR("Add metadata '%s' to bone '%s'"), name, skeleton->get_bone_name(bone)));
231 undo_redo->add_do_method(skeleton, "set_bone_meta", bone, name, add_meta_dialog->get_meta_defval());
232 undo_redo->add_undo_method(skeleton, "set_bone_meta", bone, name, Variant());
233 undo_redo->commit_action();
234 }
235
236 BonePropertiesEditor::BonePropertiesEditor(Skeleton3D *p_skeleton) {
237 create_editors();
238 set_skeleton(p_skeleton);
239 }
240
241 void BonePropertiesEditor::set_keyable(const bool p_keyable) {
242 position_property->set_keying(p_keyable);
243 rotation_property->set_keying(p_keyable);
244 scale_property->set_keying(p_keyable);
245 }
246
247 void BonePropertiesEditor::set_skeleton(Skeleton3D *p_skeleton) {
248 skeleton = p_skeleton;
249
250 if (skeleton) {
251 return;
252 }
253
254 enabled_checkbox->set_object_and_property(nullptr, String());
255 position_property->set_object_and_property(nullptr, String());
256 rotation_property->set_object_and_property(nullptr, String());
257 scale_property->set_object_and_property(nullptr, String());
258 rest_matrix->set_object_and_property(nullptr, String());
259
260 for (KeyValue<StringName, EditorProperty *> &E : meta_editors) {
261 E.value->set_object_and_property(nullptr, String());
262 }
263 }
264
265 void BonePropertiesEditor::set_target(const String &p_prop) {
266 enabled_checkbox->set_object_and_property(skeleton, p_prop + "enabled");
267 enabled_checkbox->update_property();
268
269 position_property->set_object_and_property(skeleton, p_prop + "position");
270 position_property->update_property();
271
272 rotation_property->set_object_and_property(skeleton, p_prop + "rotation");
273 rotation_property->update_property();
274
275 scale_property->set_object_and_property(skeleton, p_prop + "scale");
276 scale_property->update_property();
277
278 rest_matrix->set_object_and_property(skeleton, p_prop + "rest");
279 rest_matrix->update_property();
280 }
281
282 void BonePropertiesEditor::_property_keyed(const String &p_path, bool p_advance) {
283 AnimationTrackEditor *te = AnimationPlayerEditor::get_singleton()->get_track_editor();
284 if (!te || !te->has_keying()) {
285 return;
286 }
287 te->_clear_selection();
288 PackedStringArray split = p_path.split("/");
289 if (split.size() == 3 && split[0] == "bones") {
290 int bone_idx = split[1].to_int();
291 if (split[2] == "position") {
292 te->insert_transform_key(skeleton, skeleton->get_bone_name(bone_idx), Animation::TYPE_POSITION_3D, (Vector3)skeleton->get(p_path) / skeleton->get_motion_scale());
293 }
294 if (split[2] == "rotation") {
295 te->insert_transform_key(skeleton, skeleton->get_bone_name(bone_idx), Animation::TYPE_ROTATION_3D, skeleton->get(p_path));
296 }
297 if (split[2] == "scale") {
298 te->insert_transform_key(skeleton, skeleton->get_bone_name(bone_idx), Animation::TYPE_SCALE_3D, skeleton->get(p_path));
299 }
300 }
301 }
302
303 void BonePropertiesEditor::_update_properties() {
304 if (!skeleton || !Skeleton3DEditor::get_singleton()) {
305 return;
306 }
307 int selected = Skeleton3DEditor::get_singleton()->get_selected_bone();
308 List<PropertyInfo> props;
309 HashSet<StringName> meta_seen;
310 skeleton->get_property_list(&props);
311 for (const PropertyInfo &E : props) {
312 PackedStringArray split = E.name.split("/");
313 if (split.size() >= 3 && split[0] == "bones") {
314 if (split[1].to_int() == selected) {
315 if (split[2] == "enabled") {
316 enabled_checkbox->set_read_only(E.usage & PROPERTY_USAGE_READ_ONLY);
317 enabled_checkbox->update_property();
318 enabled_checkbox->update_editor_property_status();
319 enabled_checkbox->queue_redraw();
320 }
321 if (split[2] == "position") {
322 position_property->set_read_only(E.usage & PROPERTY_USAGE_READ_ONLY);
323 position_property->update_property();
324 position_property->update_editor_property_status();
325 position_property->queue_redraw();
326 }
327 if (split[2] == "rotation") {
328 rotation_property->set_read_only(E.usage & PROPERTY_USAGE_READ_ONLY);
329 rotation_property->update_property();
330 rotation_property->update_editor_property_status();
331 rotation_property->queue_redraw();
332 }
333 if (split[2] == "scale") {
334 scale_property->set_read_only(E.usage & PROPERTY_USAGE_READ_ONLY);
335 scale_property->update_property();
336 scale_property->update_editor_property_status();
337 scale_property->queue_redraw();
338 }
339 if (split[2] == "rest") {
340 rest_matrix->set_read_only(E.usage & PROPERTY_USAGE_READ_ONLY);
341 rest_matrix->update_property();
342 rest_matrix->update_editor_property_status();
343 rest_matrix->queue_redraw();
344 }
345 if (split[2] == "bone_meta") {
346 meta_seen.insert(E.name);
347 if (!meta_editors.find(E.name)) {
348 EditorProperty *editor = EditorInspectorDefaultPlugin::get_editor_for_property(skeleton, E.type, E.name, PROPERTY_HINT_NONE, "", E.usage);
349 editor->set_label(split[3]);
350 editor->set_object_and_property(skeleton, E.name);
351 editor->set_deletable(true);
352 editor->set_selectable(false);
353 editor->connect("property_changed", callable_mp(this, &BonePropertiesEditor::_meta_changed));
354 editor->connect("property_deleted", callable_mp(this, &BonePropertiesEditor::_meta_deleted));
355
356 meta_section->get_vbox()->add_child(editor);
357 editor->update_property();
358 editor->update_editor_property_status();
359 editor->queue_redraw();
360
361 meta_editors[E.name] = editor;
362 }
363 }
364 }
365 }
366 }
367 // UI for any bone metadata prop not seen during the iteration has to be deleted
368 for (KeyValue<StringName, EditorProperty *> iter : meta_editors) {
369 if (!meta_seen.has(iter.key)) {
370 callable_mp((Node *)meta_section->get_vbox(), &Node::remove_child).call_deferred(iter.value);
371 meta_editors.remove(meta_editors.find(iter.key));
372 }
373 }
374 }
375
376 Skeleton3DEditor *Skeleton3DEditor::singleton = nullptr;
377
378 void Skeleton3DEditor::set_keyable(const bool p_keyable) {
379 keyable = p_keyable;
380 if (p_keyable) {
381 animation_hb->show();
382 } else {
383 animation_hb->hide();
384 }
385 }
386
387 void Skeleton3DEditor::set_bone_options_enabled(const bool p_bone_options_enabled) {
388 skeleton_options->get_popup()->set_item_disabled(SKELETON_OPTION_RESET_SELECTED_POSES, !p_bone_options_enabled);
389 skeleton_options->get_popup()->set_item_disabled(SKELETON_OPTION_SELECTED_POSES_TO_RESTS, !p_bone_options_enabled);
390 }
391
392 void Skeleton3DEditor::_bind_methods() {
393 ClassDB::bind_method(D_METHOD("update_all"), &Skeleton3DEditor::update_all);
394 ClassDB::bind_method(D_METHOD("update_joint_tree"), &Skeleton3DEditor::update_joint_tree);
395 }
396
397 void Skeleton3DEditor::_on_click_skeleton_option(int p_skeleton_option) {
398 ERR_FAIL_COND(!skeleton);
399
400 switch (p_skeleton_option) {
401 case SKELETON_OPTION_RESET_ALL_POSES: {
402 reset_pose(true);
403 break;
404 }
405 case SKELETON_OPTION_RESET_SELECTED_POSES: {
406 reset_pose(false);
407 break;
408 }
409 case SKELETON_OPTION_ALL_POSES_TO_RESTS: {
410 pose_to_rest(true);
411 break;
412 }
413 case SKELETON_OPTION_SELECTED_POSES_TO_RESTS: {
414 pose_to_rest(false);
415 break;
416 }
417 case SKELETON_OPTION_CREATE_PHYSICAL_SKELETON: {
418 create_physical_skeleton();
419 break;
420 }
421 case SKELETON_OPTION_EXPORT_SKELETON_PROFILE: {
422 export_skeleton_profile();
423 break;
424 }
425 }
426 }
427
428 void Skeleton3DEditor::reset_pose(const bool p_all_bones) {
429 ERR_FAIL_COND(!skeleton);
430
431 const int bone_count = skeleton->get_bone_count();
432 if (!bone_count) {
433 return;
434 }
435
436 EditorUndoRedoManager *ur = EditorUndoRedoManager::get_singleton();
437 ur->create_action(TTR("Set Bone Transform"), UndoRedo::MERGE_ENDS);
438 if (p_all_bones) {
439 for (int i = 0; i < bone_count; i++) {
440 ur->add_undo_method(skeleton, "set_bone_pose_position", i, skeleton->get_bone_pose_position(i));
441 ur->add_undo_method(skeleton, "set_bone_pose_rotation", i, skeleton->get_bone_pose_rotation(i));
442 ur->add_undo_method(skeleton, "set_bone_pose_scale", i, skeleton->get_bone_pose_scale(i));
443 }
444 ur->add_do_method(skeleton, "reset_bone_poses");
445 } else {
446 // Todo: Do method with multiple bone selection.
447 if (selected_bone == -1) {
448 ur->commit_action();
449 return;
450 }
451 ur->add_undo_method(skeleton, "set_bone_pose_position", selected_bone, skeleton->get_bone_pose_position(selected_bone));
452 ur->add_undo_method(skeleton, "set_bone_pose_rotation", selected_bone, skeleton->get_bone_pose_rotation(selected_bone));
453 ur->add_undo_method(skeleton, "set_bone_pose_scale", selected_bone, skeleton->get_bone_pose_scale(selected_bone));
454 ur->add_do_method(skeleton, "reset_bone_pose", selected_bone);
455 }
456
457 ur->add_undo_method(this, "update_joint_tree");
458 ur->add_do_method(this, "update_joint_tree");
459
460 ur->commit_action();
461 }
462
463 void Skeleton3DEditor::insert_keys(const bool p_all_bones, const bool p_enable_modifier) {
464 ERR_FAIL_COND(!skeleton);
465
466 AnimationTrackEditor *te = AnimationPlayerEditor::get_singleton()->get_track_editor();
467 bool is_read_only = te->is_read_only();
468 if (is_read_only) {
469 te->popup_read_only_dialog();
470 return;
471 }
472 if (p_enable_modifier) {
473 if (!skeleton->is_connected(SceneStringName(skeleton_updated), callable_mp(this, &Skeleton3DEditor::_insert_keys).bind(p_all_bones))) {
474 skeleton->connect(SceneStringName(skeleton_updated), callable_mp(this, &Skeleton3DEditor::_insert_keys).bind(p_all_bones), CONNECT_ONE_SHOT);
475 } else {
476 WARN_PRINT_ED("A skeleton_updated signal is already connected with _insert_keys().");
477 }
478 skeleton->force_update_deferred();
479 skeleton->notification(Skeleton3D::NOTIFICATION_UPDATE_SKELETON);
480 // Force disconnecting signal if remain the connecting just in case.
481 if (skeleton->is_connected(SceneStringName(skeleton_updated), callable_mp(this, &Skeleton3DEditor::_insert_keys).bind(p_all_bones))) {
482 skeleton->disconnect(SceneStringName(skeleton_updated), callable_mp(this, &Skeleton3DEditor::_insert_keys).bind(p_all_bones));
483 }
484 } else {
485 _insert_keys(p_all_bones);
486 }
487 }
488
489 void Skeleton3DEditor::_insert_keys(const bool p_all_bones) {
490 ERR_FAIL_COND(!skeleton);
491
492 bool pos_enabled = key_loc_button->is_pressed();
493 bool rot_enabled = key_rot_button->is_pressed();
494 bool scl_enabled = key_scale_button->is_pressed();
495
496 int bone_len = skeleton->get_bone_count();
497 Node *root = EditorNode::get_singleton()->get_tree()->get_root();
498 String path = String(root->get_path_to(skeleton));
499
500 AnimationTrackEditor *te = AnimationPlayerEditor::get_singleton()->get_track_editor();
501 te->make_insert_queue();
502 for (int i = 0; i < bone_len; i++) {
503 const String name = skeleton->get_bone_name(i);
504
505 if (name.is_empty()) {
506 continue;
507 }
508
509 if (pos_enabled && (p_all_bones || te->has_track(skeleton, name, Animation::TYPE_POSITION_3D))) {
510 te->insert_transform_key(skeleton, name, Animation::TYPE_POSITION_3D, skeleton->get_bone_pose_position(i) / skeleton->get_motion_scale());
511 }
512 if (rot_enabled && (p_all_bones || te->has_track(skeleton, name, Animation::TYPE_ROTATION_3D))) {
513 te->insert_transform_key(skeleton, name, Animation::TYPE_ROTATION_3D, skeleton->get_bone_pose_rotation(i));
514 }
515 if (scl_enabled && (p_all_bones || te->has_track(skeleton, name, Animation::TYPE_SCALE_3D))) {
516 te->insert_transform_key(skeleton, name, Animation::TYPE_SCALE_3D, skeleton->get_bone_pose_scale(i));
517 }
518 }
519 te->commit_insert_queue();
520 }
521
522 void Skeleton3DEditor::pose_to_rest(const bool p_all_bones) {
523 ERR_FAIL_COND(!skeleton);
524
525 const int bone_count = skeleton->get_bone_count();
526 if (!bone_count) {
527 return;
528 }
529
530 EditorUndoRedoManager *ur = EditorUndoRedoManager::get_singleton();
531 ur->create_action(TTR("Set Bone Rest"), UndoRedo::MERGE_ENDS);
532 if (p_all_bones) {
533 for (int i = 0; i < bone_count; i++) {
534 ur->add_do_method(skeleton, "set_bone_rest", i, skeleton->get_bone_pose(i));
535 ur->add_undo_method(skeleton, "set_bone_rest", i, skeleton->get_bone_rest(i));
536 }
537 } else {
538 // Todo: Do method with multiple bone selection.
539 if (selected_bone == -1) {
540 ur->commit_action();
541 return;
542 }
543 ur->add_do_method(skeleton, "set_bone_rest", selected_bone, skeleton->get_bone_pose(selected_bone));
544 ur->add_undo_method(skeleton, "set_bone_rest", selected_bone, skeleton->get_bone_rest(selected_bone));
545 }
546
547 ur->add_undo_method(this, "update_joint_tree");
548 ur->add_do_method(this, "update_joint_tree");
549
550 ur->commit_action();
551 }
552
553 void Skeleton3DEditor::create_physical_skeleton() {
554 EditorUndoRedoManager *ur = EditorUndoRedoManager::get_singleton();
555 ERR_FAIL_NULL(get_tree());
556 Node *owner = get_tree()->get_edited_scene_root();
557
558 const int bone_count = skeleton->get_bone_count();
559
560 if (!bone_count) {
561 EditorNode::get_singleton()->show_warning(vformat(TTR("Cannot create a physical skeleton for a Skeleton3D node with no bones.")));
562 return;
563 }
564
565 Vector<BoneInfo> bones_infos;
566 bones_infos.resize(bone_count);
567
568 ur->create_action(TTR("Create physical bones"), UndoRedo::MERGE_ALL);
569
570 PhysicalBoneSimulator3D *simulator = memnew(PhysicalBoneSimulator3D);
571 ur->add_do_method(skeleton, "add_child", simulator);
572 ur->add_do_method(simulator, "set_owner", owner);
573 ur->add_do_method(simulator, "set_name", "PhysicalBoneSimulator3D");
574 for (int bone_id = 0; bone_count > bone_id; ++bone_id) {
575 const int parent = skeleton->get_bone_parent(bone_id);
576
577 if (parent < 0) {
578 bones_infos.write[bone_id].relative_rest = skeleton->get_bone_rest(bone_id);
579 } else {
580 const int parent_parent = skeleton->get_bone_parent(parent);
581
582 bones_infos.write[bone_id].relative_rest = bones_infos[parent].relative_rest * skeleton->get_bone_rest(bone_id);
583
584 // Create physical bone on parent.
585 if (!bones_infos[parent].physical_bone) {
586 PhysicalBone3D *physical_bone = create_physical_bone(parent, bone_id, bones_infos);
587 if (physical_bone && physical_bone->get_child(0)) {
588 CollisionShape3D *collision_shape = Object::cast_to<CollisionShape3D>(physical_bone->get_child(0));
589 if (collision_shape) {
590 bones_infos.write[parent].physical_bone = physical_bone;
591
592 ur->add_do_method(simulator, "add_child", physical_bone);
593 ur->add_do_method(physical_bone, "set_owner", owner);
594 ur->add_do_method(collision_shape, "set_owner", owner);
595 ur->add_do_property(physical_bone, "bone_name", skeleton->get_bone_name(parent));
596
597 // Create joint between parent of parent.
598 if (parent_parent != -1) {
599 ur->add_do_method(physical_bone, "set_joint_type", PhysicalBone3D::JOINT_TYPE_PIN);
600 }
601
602 ur->add_do_method(Node3DEditor::get_singleton(), SceneStringName(_request_gizmo), physical_bone);
603 ur->add_do_method(Node3DEditor::get_singleton(), SceneStringName(_request_gizmo), collision_shape);
604
605 ur->add_do_reference(physical_bone);
606 ur->add_undo_method(simulator, "remove_child", physical_bone);
607 }
608 }
609 }
610 }
611 }
612 ur->add_undo_method(skeleton, "remove_child", simulator);
613 ur->commit_action();
614 }
615
616 PhysicalBone3D *Skeleton3DEditor::create_physical_bone(int bone_id, int bone_child_id, const Vector<BoneInfo> &bones_infos) {
617 const Transform3D child_rest = skeleton->get_bone_rest(bone_child_id);
618
619 const real_t half_height(child_rest.origin.length() * 0.5);
620 const real_t radius(half_height * 0.2);
621
622 CapsuleShape3D *bone_shape_capsule = memnew(CapsuleShape3D);
623 bone_shape_capsule->set_height(half_height * 2);
624 bone_shape_capsule->set_radius(radius);
625
626 CollisionShape3D *bone_shape = memnew(CollisionShape3D);
627 bone_shape->set_shape(bone_shape_capsule);
628 bone_shape->set_name("CollisionShape3D");
629
630 Transform3D capsule_transform;
631 capsule_transform.basis.rows[0] = Vector3(1, 0, 0);
632 capsule_transform.basis.rows[1] = Vector3(0, 0, 1);
633 capsule_transform.basis.rows[2] = Vector3(0, -1, 0);
634 bone_shape->set_transform(capsule_transform);
635
636 /// Get an up vector not collinear with child rest origin
637 Vector3 up = Vector3(0, 1, 0);
638 if (up.cross(child_rest.origin).is_zero_approx()) {
639 up = Vector3(0, 0, 1);
640 }
641
642 Transform3D body_transform;
643 body_transform.basis = Basis::looking_at(child_rest.origin, up);
644 body_transform.origin = body_transform.basis.xform(Vector3(0, 0, -half_height));
645
646 Transform3D joint_transform;
647 joint_transform.origin = Vector3(0, 0, half_height);
648
649 PhysicalBone3D *physical_bone = memnew(PhysicalBone3D);
650 physical_bone->add_child(bone_shape);
651 physical_bone->set_name("Physical Bone " + skeleton->get_bone_name(bone_id));
652 physical_bone->set_body_offset(body_transform);
653 physical_bone->set_joint_offset(joint_transform);
654 return physical_bone;
655 }
656
657 void Skeleton3DEditor::export_skeleton_profile() {
658 if (!skeleton->get_bone_count()) {
659 EditorNode::get_singleton()->show_warning(vformat(TTR("Cannot export a SkeletonProfile for a Skeleton3D node with no bones.")));
660 return;
661 }
662
663 file_dialog->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
664 file_dialog->set_title(TTR("Export Skeleton Profile As..."));
665
666 List<String> exts;
667 ResourceLoader::get_recognized_extensions_for_type("SkeletonProfile", &exts);
668 file_dialog->clear_filters();
669 for (const String &K : exts) {
670 file_dialog->add_filter("*." + K);
671 }
672
673 file_dialog->popup_file_dialog();
674 }
675
676 void Skeleton3DEditor::_file_selected(const String &p_file) {
677 // Export SkeletonProfile.
678 Ref<SkeletonProfile> sp(memnew(SkeletonProfile));
679
680 // Build SkeletonProfile.
681 sp->set_group_size(1);
682
683 Vector<Vector2> handle_positions;
684 Vector2 position_max;
685 Vector2 position_min;
686
687 const int bone_count = skeleton->get_bone_count();
688 sp->set_bone_size(bone_count);
689 for (int i = 0; i < bone_count; i++) {
690 sp->set_bone_name(i, skeleton->get_bone_name(i));
691 int parent = skeleton->get_bone_parent(i);
692 if (parent >= 0) {
693 sp->set_bone_parent(i, skeleton->get_bone_name(parent));
694 }
695 sp->set_reference_pose(i, skeleton->get_bone_rest(i));
696
697 Transform3D grest = skeleton->get_bone_global_rest(i);
698 handle_positions.append(Vector2(grest.origin.x, grest.origin.y));
699 if (i == 0) {
700 position_max = Vector2(grest.origin.x, grest.origin.y);
701 position_min = Vector2(grest.origin.x, grest.origin.y);
702 } else {
703 position_max = position_max.max(Vector2(grest.origin.x, grest.origin.y));
704 position_min = position_min.min(Vector2(grest.origin.x, grest.origin.y));
705 }
706 }
707
708 // Layout handles provisionaly.
709 Vector2 bound = Vector2(position_max.x - position_min.x, position_max.y - position_min.y);
710 Vector2 center = Vector2((position_max.x + position_min.x) * 0.5, (position_max.y + position_min.y) * 0.5);
711 float nrm = MAX(bound.x, bound.y);
712 if (nrm > 0) {
713 for (int i = 0; i < bone_count; i++) {
714 handle_positions.write[i] = (handle_positions[i] - center) / nrm * 0.9;
715 sp->set_handle_offset(i, Vector2(0.5 + handle_positions[i].x, 0.5 - handle_positions[i].y));
716 }
717 }
718
719 Error err = ResourceSaver::save(sp, p_file);
720
721 if (err != OK) {
722 EditorNode::get_singleton()->show_warning(vformat(TTR("Error saving file: %s"), p_file));
723 return;
724 }
725 }
726
727 Variant Skeleton3DEditor::get_drag_data_fw(const Point2 &p_point, Control *p_from) {
728 TreeItem *selected = joint_tree->get_selected();
729
730 if (!selected) {
731 return Variant();
732 }
733
734 Ref<Texture> icon = selected->get_icon(0);
735
736 VBoxContainer *vb = memnew(VBoxContainer);
737 HBoxContainer *hb = memnew(HBoxContainer);
738 TextureRect *tf = memnew(TextureRect);
739 tf->set_texture(icon);
740 tf->set_stretch_mode(TextureRect::STRETCH_KEEP_CENTERED);
741 hb->add_child(tf);
742 Label *label = memnew(Label(selected->get_text(0)));
743 label->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
744 hb->add_child(label);
745 vb->add_child(hb);
746 hb->set_modulate(Color(1, 1, 1, 1));
747
748 set_drag_preview(vb);
749 Dictionary drag_data;
750 drag_data["type"] = "skeleton_bone";
751 drag_data["source"] = selected->get_instance_id();
752
753 return drag_data;
754 }
755
756 bool Skeleton3DEditor::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
757 Dictionary drag_data = p_data;
758 if (!drag_data.has("type") || drag_data["type"] != "skeleton_bone" || !drag_data.has("source")) {
759 return false;
760 }
761
762 TreeItem *target = (p_point == Vector2(Math::INF, Math::INF)) ? joint_tree->get_selected() : joint_tree->get_item_at_position(p_point);
763 if (!target) {
764 return false;
765 }
766
767 const String path = target->get_metadata(0);
768 if (!path.begins_with("bones/")) {
769 return false;
770 }
771
772 TreeItem *selected = ObjectDB::get_instance<TreeItem>(drag_data["source"]);
773 if (!selected || selected->get_tree() != joint_tree || target == selected) {
774 return false;
775 }
776
777 const String selected_path = selected->get_metadata(0);
778 if (!selected_path.begins_with("bones/")) {
779 return false;
780 }
781
782 return true;
783 }
784
785 void Skeleton3DEditor::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
786 if (!can_drop_data_fw(p_point, p_data, p_from)) {
787 return;
788 }
789
790 Dictionary drag_data = p_data;
791
792 TreeItem *target = (p_point == Vector2(Math::INF, Math::INF)) ? joint_tree->get_selected() : joint_tree->get_item_at_position(p_point);
793 TreeItem *selected = ObjectDB::get_instance<TreeItem>(drag_data["source"]);
794 if (!target || !selected || selected->get_tree() != joint_tree || !skeleton) {
795 return;
796 }
797
798 const String target_path = target->get_metadata(0);
799 const String selected_path = selected->get_metadata(0);
800 if (!target_path.begins_with("bones/") || !selected_path.begins_with("bones/")) {
801 return;
802 }
803
804 const BoneId target_boneidx = target_path.get_slicec('/', 1).to_int();
805 const BoneId selected_boneidx = selected_path.get_slicec('/', 1).to_int();
806
807 move_skeleton_bone(skeleton->get_path(), selected_boneidx, target_boneidx);
808 }
809
810 void Skeleton3DEditor::move_skeleton_bone(NodePath p_skeleton_path, int32_t p_selected_boneidx, int32_t p_target_boneidx) {
811 Node *node = get_node_or_null(p_skeleton_path);
812 Skeleton3D *skeleton_node = Object::cast_to<Skeleton3D>(node);
813 ERR_FAIL_NULL(skeleton_node);
814 EditorUndoRedoManager *ur = EditorUndoRedoManager::get_singleton();
815 ur->create_action(TTR("Set Bone Parentage"));
816 // If the target is a child of ourselves, we move only *us* and not our children.
817 if (skeleton_node->is_bone_parent_of(p_target_boneidx, p_selected_boneidx)) {
818 const BoneId parent_idx = skeleton_node->get_bone_parent(p_selected_boneidx);
819 const int bone_count = skeleton_node->get_bone_count();
820 for (BoneId i = 0; i < bone_count; ++i) {
821 if (skeleton_node->get_bone_parent(i) == p_selected_boneidx) {
822 ur->add_undo_method(skeleton_node, "set_bone_parent", i, skeleton_node->get_bone_parent(i));
823 ur->add_do_method(skeleton_node, "set_bone_parent", i, parent_idx);
824 skeleton_node->set_bone_parent(i, parent_idx);
825 }
826 }
827 }
828 ur->add_undo_method(skeleton_node, "set_bone_parent", p_selected_boneidx, skeleton_node->get_bone_parent(p_selected_boneidx));
829 ur->add_do_method(skeleton_node, "set_bone_parent", p_selected_boneidx, p_target_boneidx);
830
831 ur->add_undo_method(this, "update_joint_tree");
832 ur->add_do_method(this, "update_joint_tree");
833
834 skeleton_node->set_bone_parent(p_selected_boneidx, p_target_boneidx);
835
836 ur->commit_action();
837 }
838
839 void Skeleton3DEditor::_joint_tree_selection_changed() {
840 TreeItem *selected = joint_tree->get_selected();
841 if (selected) {
842 const String path = selected->get_metadata(0);
843 if (!path.begins_with("bones/")) {
844 return;
845 }
846 const int b_idx = path.get_slicec('/', 1).to_int();
847 selected_bone = b_idx;
848 if (pose_editor) {
849 const String bone_path = "bones/" + itos(b_idx) + "/";
850 pose_editor->set_target(bone_path);
851 pose_editor->set_keyable(keyable);
852 }
853 }
854
855 if (pose_editor && pose_editor->is_inside_tree()) {
856 pose_editor->set_visible(selected);
857 }
858 set_bone_options_enabled(selected);
859
860 _update_properties();
861 _update_gizmo_visible();
862 }
863
864 // May be not used with single select mode.
865 void Skeleton3DEditor::_joint_tree_rmb_select(const Vector2 &p_pos, MouseButton p_button) {
866 }
867
868 void Skeleton3DEditor::_joint_tree_button_clicked(Object *p_item, int p_column, int p_id, MouseButton p_button) {
869 if (!skeleton) {
870 return;
871 }
872
873 TreeItem *tree_item = Object::cast_to<TreeItem>(p_item);
874 if (tree_item) {
875 String tree_item_metadata = tree_item->get_metadata(0);
876
877 String bone_enabled_property = tree_item_metadata + "/enabled";
878 String bone_parent_property = tree_item_metadata + "/parent";
879 String bone_name_property = tree_item_metadata + "/name";
880 String bone_position_property = tree_item_metadata + "/position";
881 String bone_rotation_property = tree_item_metadata + "/rotation";
882 String bone_scale_property = tree_item_metadata + "/scale";
883 String bone_rest_property = tree_item_metadata + "/rest";
884
885 Variant current_enabled = skeleton->get(bone_enabled_property);
886 Variant current_parent = skeleton->get(bone_parent_property);
887 Variant current_name = skeleton->get(bone_name_property);
888 Variant current_position = skeleton->get(bone_position_property);
889 Variant current_rotation = skeleton->get(bone_rotation_property);
890 Variant current_scale = skeleton->get(bone_scale_property);
891 Variant current_rest = skeleton->get(bone_rest_property);
892
893 EditorUndoRedoManager *ur = EditorUndoRedoManager::get_singleton();
894 ur->create_action(TTR("Revert Bone"));
895
896 bool can_revert_enabled = EditorPropertyRevert::can_property_revert(skeleton, bone_enabled_property, &current_enabled);
897 if (can_revert_enabled) {
898 bool is_valid = false;
899 Variant new_enabled = EditorPropertyRevert::get_property_revert_value(skeleton, bone_enabled_property, &is_valid);
900 if (is_valid) {
901 ur->add_undo_method(skeleton, "set", bone_enabled_property, current_enabled);
902 ur->add_do_method(skeleton, "set", bone_enabled_property, new_enabled);
903 }
904 }
905
906 bool can_revert_parent = EditorPropertyRevert::can_property_revert(skeleton, bone_parent_property, &current_parent);
907 if (can_revert_parent) {
908 bool is_valid = false;
909 Variant new_parent = EditorPropertyRevert::get_property_revert_value(skeleton, bone_parent_property, &is_valid);
910 if (is_valid) {
911 ur->add_undo_method(skeleton, "set", bone_parent_property, current_parent);
912 ur->add_do_method(skeleton, "set", bone_parent_property, new_parent);
913 }
914 }
915 bool can_revert_name = EditorPropertyRevert::can_property_revert(skeleton, bone_name_property, &current_name);
916 if (can_revert_name) {
917 bool is_valid = false;
918 Variant new_name = EditorPropertyRevert::get_property_revert_value(skeleton, bone_name_property, &is_valid);
919 if (is_valid) {
920 ur->add_undo_method(skeleton, "set", bone_name_property, current_name);
921 ur->add_do_method(skeleton, "set", bone_name_property, new_name);
922 }
923 }
924 bool can_revert_position = EditorPropertyRevert::can_property_revert(skeleton, bone_position_property, &current_position);
925 if (can_revert_position) {
926 bool is_valid = false;
927 Variant new_position = EditorPropertyRevert::get_property_revert_value(skeleton, bone_position_property, &is_valid);
928 if (is_valid) {
929 ur->add_undo_method(skeleton, "set", bone_position_property, current_position);
930 ur->add_do_method(skeleton, "set", bone_position_property, new_position);
931 }
932 }
933 bool can_revert_rotation = EditorPropertyRevert::can_property_revert(skeleton, bone_rotation_property, &current_rotation);
934 if (can_revert_rotation) {
935 bool is_valid = false;
936 Variant new_rotation = EditorPropertyRevert::get_property_revert_value(skeleton, bone_rotation_property, &is_valid);
937 if (is_valid) {
938 ur->add_undo_method(skeleton, "set", bone_rotation_property, current_rotation);
939 ur->add_do_method(skeleton, "set", bone_rotation_property, new_rotation);
940 }
941 }
942 bool can_revert_scale = EditorPropertyRevert::can_property_revert(skeleton, bone_scale_property, &current_scale);
943 if (can_revert_scale) {
944 bool is_valid = false;
945 Variant new_scale = EditorPropertyRevert::get_property_revert_value(skeleton, bone_scale_property, &is_valid);
946 if (is_valid) {
947 ur->add_undo_method(skeleton, "set", bone_scale_property, current_scale);
948 ur->add_do_method(skeleton, "set", bone_scale_property, new_scale);
949 }
950 }
951 bool can_revert_rest = EditorPropertyRevert::can_property_revert(skeleton, bone_rest_property, &current_rest);
952 if (can_revert_rest) {
953 bool is_valid = false;
954 Variant new_rest = EditorPropertyRevert::get_property_revert_value(skeleton, bone_rest_property, &is_valid);
955 if (is_valid) {
956 ur->add_undo_method(skeleton, "set", bone_rest_property, current_rest);
957 ur->add_do_method(skeleton, "set", bone_rest_property, new_rest);
958 }
959 }
960
961 ur->add_undo_method(this, "update_all");
962 ur->add_do_method(this, "update_all");
963
964 ur->commit_action();
965 }
966 return;
967 }
968
969 void Skeleton3DEditor::_update_properties() {
970 if (pose_editor) {
971 pose_editor->_update_properties();
972 }
973 Node3DEditor::get_singleton()->update_transform_gizmo();
974 }
975
976 void Skeleton3DEditor::update_joint_tree() {
977 joint_tree->clear();
978
979 if (!skeleton) {
980 return;
981 }
982
983 TreeItem *root = joint_tree->create_item();
984
985 HashMap<int, TreeItem *> items;
986
987 items.insert(-1, root);
988
989 Ref<Texture> bone_icon = get_editor_theme_icon(SNAME("Bone"));
990
991 Vector<int> bones_to_process = skeleton->get_parentless_bones();
992 while (bones_to_process.size() > 0) {
993 int current_bone_idx = bones_to_process[0];
994 bones_to_process.erase(current_bone_idx);
995
996 const int parent_idx = skeleton->get_bone_parent(current_bone_idx);
997 TreeItem *parent_item = items.find(parent_idx)->value;
998
999 TreeItem *joint_item = joint_tree->create_item(parent_item);
1000 items.insert(current_bone_idx, joint_item);
1001
1002 joint_item->set_text(0, skeleton->get_bone_name(current_bone_idx));
1003 joint_item->set_icon(0, bone_icon);
1004 joint_item->set_selectable(0, true);
1005 joint_item->set_metadata(0, "bones/" + itos(current_bone_idx));
1006
1007 String bone_enabled_property = "bones/" + itos(current_bone_idx) + "/enabled";
1008 String bone_parent_property = "bones/" + itos(current_bone_idx) + "/parent";
1009 String bone_name_property = "bones/" + itos(current_bone_idx) + "/name";
1010 String bone_position_property = "bones/" + itos(current_bone_idx) + "/position";
1011 String bone_rotation_property = "bones/" + itos(current_bone_idx) + "/rotation";
1012 String bone_scale_property = "bones/" + itos(current_bone_idx) + "/scale";
1013 String bone_rest_property = "bones/" + itos(current_bone_idx) + "/rest";
1014
1015 Variant current_enabled = skeleton->get(bone_enabled_property);
1016 Variant current_parent = skeleton->get(bone_parent_property);
1017 Variant current_name = skeleton->get(bone_name_property);
1018 Variant current_position = skeleton->get(bone_position_property);
1019 Variant current_rotation = skeleton->get(bone_rotation_property);
1020 Variant current_scale = skeleton->get(bone_scale_property);
1021 Variant current_rest = skeleton->get(bone_rest_property);
1022
1023 bool can_revert_enabled = EditorPropertyRevert::can_property_revert(skeleton, bone_enabled_property, &current_enabled);
1024 bool can_revert_parent = EditorPropertyRevert::can_property_revert(skeleton, bone_parent_property, &current_parent);
1025 bool can_revert_name = EditorPropertyRevert::can_property_revert(skeleton, bone_name_property, &current_name);
1026 bool can_revert_position = EditorPropertyRevert::can_property_revert(skeleton, bone_position_property, &current_position);
1027 bool can_revert_rotation = EditorPropertyRevert::can_property_revert(skeleton, bone_rotation_property, &current_rotation);
1028 bool can_revert_scale = EditorPropertyRevert::can_property_revert(skeleton, bone_scale_property, &current_scale);
1029 bool can_revert_rest = EditorPropertyRevert::can_property_revert(skeleton, bone_rest_property, &current_rest);
1030
1031 if (can_revert_enabled || can_revert_parent || can_revert_name || can_revert_position || can_revert_rotation || can_revert_scale || can_revert_rest) {
1032 joint_item->add_button(0, get_editor_theme_icon(SNAME("ReloadSmall")), JOINT_BUTTON_REVERT, false, TTR("Revert"));
1033 }
1034
1035 // Add the bone's children to the list of bones to be processed.
1036 Vector<int> current_bone_child_bones = skeleton->get_bone_children(current_bone_idx);
1037 int child_bone_size = current_bone_child_bones.size();
1038 for (int i = 0; i < child_bone_size; i++) {
1039 bones_to_process.push_back(current_bone_child_bones[i]);
1040 }
1041
1042 if (current_bone_idx == selected_bone) {
1043 joint_item->select(0);
1044 }
1045 }
1046 }
1047
1048 void Skeleton3DEditor::update_all() {
1049 _update_properties();
1050 update_joint_tree();
1051 }
1052
1053 void Skeleton3DEditor::create_editors() {
1054 set_h_size_flags(SIZE_EXPAND_FILL);
1055 set_focus_mode(FOCUS_ALL);
1056
1057 Node3DEditor *ne = Node3DEditor::get_singleton();
1058 AnimationTrackEditor *te = AnimationPlayerEditor::get_singleton()->get_track_editor();
1059
1060 // Create File dialog.
1061 file_dialog = memnew(EditorFileDialog);
1062 file_dialog->connect("file_selected", callable_mp(this, &Skeleton3DEditor::_file_selected));
1063 add_child(file_dialog);
1064
1065 // Create Top Menu Bar.
1066 topmenu_bar = memnew(HBoxContainer);
1067 ne->add_control_to_menu_panel(topmenu_bar);
1068
1069 // Create Skeleton Option in Top Menu Bar.
1070 skeleton_options = memnew(MenuButton);
1071 skeleton_options->set_flat(false);
1072 skeleton_options->set_theme_type_variation("FlatMenuButtonNoIconTint");
1073 topmenu_bar->add_child(skeleton_options);
1074
1075 skeleton_options->set_text(TTR("Skeleton3D"));
1076
1077 // Skeleton options.
1078 PopupMenu *p = skeleton_options->get_popup();
1079 p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/reset_all_poses", TTRC("Reset All Bone Poses")), SKELETON_OPTION_RESET_ALL_POSES);
1080 p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/reset_selected_poses", TTRC("Reset Selected Poses")), SKELETON_OPTION_RESET_SELECTED_POSES);
1081 p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/all_poses_to_rests", TTRC("Apply All Poses to Rests")), SKELETON_OPTION_ALL_POSES_TO_RESTS);
1082 p->add_shortcut(ED_SHORTCUT("skeleton_3d_editor/selected_poses_to_rests", TTRC("Apply Selected Poses to Rests")), SKELETON_OPTION_SELECTED_POSES_TO_RESTS);
1083 p->add_item(TTR("Create Physical Skeleton"), SKELETON_OPTION_CREATE_PHYSICAL_SKELETON);
1084 p->add_item(TTR("Export Skeleton Profile"), SKELETON_OPTION_EXPORT_SKELETON_PROFILE);
1085
1086 p->connect(SceneStringName(id_pressed), callable_mp(this, &Skeleton3DEditor::_on_click_skeleton_option));
1087 set_bone_options_enabled(false);
1088
1089 Vector<Variant> button_binds;
1090 button_binds.resize(1);
1091
1092 edit_mode_button = memnew(Button);
1093 topmenu_bar->add_child(edit_mode_button);
1094 edit_mode_button->set_theme_type_variation(SceneStringName(FlatButton));
1095 edit_mode_button->set_toggle_mode(true);
1096 edit_mode_button->set_focus_mode(FOCUS_ACCESSIBILITY);
1097 edit_mode_button->set_tooltip_text(TTR("Edit Mode\nShow buttons on joints."));
1098 edit_mode_button->connect(SceneStringName(toggled), callable_mp(this, &Skeleton3DEditor::edit_mode_toggled));
1099
1100 edit_mode = false;
1101
1102 if (skeleton) {
1103 skeleton->add_child(handles_mesh_instance);
1104 handles_mesh_instance->set_skeleton_path(NodePath(""));
1105 }
1106
1107 // Keying buttons.
1108 animation_hb = memnew(HBoxContainer);
1109 topmenu_bar->add_child(animation_hb);
1110 animation_hb->add_child(memnew(VSeparator));
1111 animation_hb->hide();
1112
1113 key_loc_button = memnew(Button);
1114 key_loc_button->set_theme_type_variation(SceneStringName(FlatButton));
1115 key_loc_button->set_toggle_mode(true);
1116 key_loc_button->set_pressed(editor_plugin->loc_pressed);
1117 key_loc_button->set_focus_mode(FOCUS_ACCESSIBILITY);
1118 key_loc_button->set_tooltip_text(TTR("Translation mask for inserting keys."));
1119 animation_hb->add_child(key_loc_button);
1120 if (!key_loc_button->is_connected(SceneStringName(toggled), callable_mp(this, &Skeleton3DEditor::_loc_toggled))) {
1121 key_loc_button->connect(SceneStringName(toggled), callable_mp(this, &Skeleton3DEditor::_loc_toggled));
1122 }
1123
1124 key_rot_button = memnew(Button);
1125 key_rot_button->set_theme_type_variation(SceneStringName(FlatButton));
1126 key_rot_button->set_toggle_mode(true);
1127 key_rot_button->set_pressed(editor_plugin->rot_pressed);
1128 key_rot_button->set_focus_mode(FOCUS_ACCESSIBILITY);
1129 key_rot_button->set_tooltip_text(TTR("Rotation mask for inserting keys."));
1130 animation_hb->add_child(key_rot_button);
1131 if (!key_rot_button->is_connected(SceneStringName(toggled), callable_mp(this, &Skeleton3DEditor::_rot_toggled))) {
1132 key_rot_button->connect(SceneStringName(toggled), callable_mp(this, &Skeleton3DEditor::_rot_toggled));
1133 }
1134
1135 key_scale_button = memnew(Button);
1136 key_scale_button->set_theme_type_variation(SceneStringName(FlatButton));
1137 key_scale_button->set_toggle_mode(true);
1138 key_scale_button->set_pressed(editor_plugin->scl_pressed);
1139 key_scale_button->set_focus_mode(FOCUS_ACCESSIBILITY);
1140 key_scale_button->set_tooltip_text(TTR("Scale mask for inserting keys."));
1141 animation_hb->add_child(key_scale_button);
1142 if (!key_scale_button->is_connected(SceneStringName(toggled), callable_mp(this, &Skeleton3DEditor::_scl_toggled))) {
1143 key_scale_button->connect(SceneStringName(toggled), callable_mp(this, &Skeleton3DEditor::_scl_toggled));
1144 }
1145
1146 key_insert_button = memnew(Button);
1147 key_insert_button->set_theme_type_variation(SceneStringName(FlatButton));
1148 key_insert_button->set_focus_mode(FOCUS_ACCESSIBILITY);
1149 key_insert_button->connect(SceneStringName(pressed), callable_mp(this, &Skeleton3DEditor::insert_keys).bind(false, false));
1150 key_insert_button->set_tooltip_text(TTRC("Insert key (based on mask) for bones with an existing track."));
1151 key_insert_button->set_shortcut(ED_SHORTCUT("skeleton_3d_editor/insert_key_to_existing_tracks", TTRC("Insert Key (Existing Tracks)"), Key::INSERT));
1152 animation_hb->add_child(key_insert_button);
1153
1154 key_insert_new_button = memnew(Button);
1155 key_insert_new_button->set_theme_type_variation(SceneStringName(FlatButton));
1156 key_insert_new_button->set_focus_mode(FOCUS_ACCESSIBILITY);
1157 key_insert_new_button->connect(SceneStringName(pressed), callable_mp(this, &Skeleton3DEditor::insert_keys).bind(true, false));
1158 key_insert_new_button->set_tooltip_text(TTRC("Insert key (based on mask) for all bones."));
1159 key_insert_new_button->set_shortcut(ED_SHORTCUT("skeleton_3d_editor/insert_key_of_all_bones", TTRC("Insert Key (All Bones)"), KeyModifierMask::CMD_OR_CTRL + Key::INSERT));
1160 animation_hb->add_child(key_insert_new_button);
1161
1162 key_mod_insert_button = memnew(Button);
1163 key_mod_insert_button->set_theme_type_variation(SceneStringName(FlatButton));
1164 key_mod_insert_button->set_focus_mode(FOCUS_ACCESSIBILITY);
1165 key_mod_insert_button->connect(SceneStringName(pressed), callable_mp(this, &Skeleton3DEditor::insert_keys).bind(false, true));
1166 key_mod_insert_button->set_tooltip_text(TTRC("Insert key (based on mask) for modified bones with an existing track."));
1167 key_mod_insert_button->set_shortcut(ED_SHORTCUT("skeleton_3d_editor/insert_key_to_existing_tracks", TTRC("Insert Key (Existing Tracks)"), Key::INSERT));
1168 animation_hb->add_child(key_mod_insert_button);
1169
1170 key_mod_insert_new_button = memnew(Button);
1171 key_mod_insert_new_button->set_theme_type_variation(SceneStringName(FlatButton));
1172 key_mod_insert_new_button->set_focus_mode(FOCUS_ACCESSIBILITY);
1173 key_mod_insert_new_button->connect(SceneStringName(pressed), callable_mp(this, &Skeleton3DEditor::insert_keys).bind(true, true));
1174 key_mod_insert_new_button->set_tooltip_text(TTRC("Insert new key (based on mask) for all modified bones."));
1175 key_mod_insert_new_button->set_shortcut(ED_SHORTCUT("skeleton_3d_editor/insert_key_of_all_bones", TTRC("Insert Key (All Bones)"), KeyModifierMask::CMD_OR_CTRL + Key::INSERT));
1176 animation_hb->add_child(key_mod_insert_new_button);
1177
1178 // Bone tree.
1179 bones_section = memnew(EditorInspectorSection);
1180 bones_section->setup("bones", "Bones", skeleton, Color(0.0f, 0.0, 0.0f), true);
1181 add_child(bones_section);
1182 bones_section->unfold();
1183
1184 ScrollContainer *s_con = memnew(ScrollContainer);
1185 s_con->set_h_size_flags(SIZE_EXPAND_FILL);
1186 s_con->set_custom_minimum_size(Size2(1, 350) * EDSCALE);
1187 bones_section->get_vbox()->add_child(s_con);
1188
1189 joint_tree = memnew(Tree);
1190 joint_tree->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
1191 joint_tree->set_columns(1);
1192 joint_tree->set_focus_mode(Control::FOCUS_NONE);
1193 joint_tree->set_select_mode(Tree::SELECT_SINGLE);
1194 joint_tree->set_hide_root(true);
1195 joint_tree->set_v_size_flags(SIZE_EXPAND_FILL);
1196 joint_tree->set_h_size_flags(SIZE_EXPAND_FILL);
1197 joint_tree->set_allow_rmb_select(true);
1198 joint_tree->set_theme_type_variation("TreeSecondary");
1199 SET_DRAG_FORWARDING_GCD(joint_tree, Skeleton3DEditor);
1200 s_con->add_child(joint_tree);
1201
1202 pose_editor = memnew(BonePropertiesEditor(skeleton));
1203 pose_editor->set_label(TTR("Bone Transform"));
1204 pose_editor->set_visible(false);
1205 add_child(pose_editor);
1206
1207 set_keyable(te->has_keying());
1208 }
1209
1210 void Skeleton3DEditor::_loc_toggled(bool p_toggled_on) {
1211 if (!editor_plugin) {
1212 return;
1213 }
1214 editor_plugin->loc_pressed = p_toggled_on;
1215 }
1216 void Skeleton3DEditor::_rot_toggled(bool p_toggled_on) {
1217 if (!editor_plugin) {
1218 return;
1219 }
1220 editor_plugin->rot_pressed = p_toggled_on;
1221 }
1222 void Skeleton3DEditor::_scl_toggled(bool p_toggled_on) {
1223 if (!editor_plugin) {
1224 return;
1225 }
1226 editor_plugin->scl_pressed = p_toggled_on;
1227 }
1228
1229 void Skeleton3DEditor::_notification(int p_what) {
1230 switch (p_what) {
1231 case NOTIFICATION_ENTER_TREE: {
1232 update_joint_tree();
1233
1234 joint_tree->connect(SceneStringName(item_selected), callable_mp(this, &Skeleton3DEditor::_joint_tree_selection_changed));
1235 joint_tree->connect("item_mouse_selected", callable_mp(this, &Skeleton3DEditor::_joint_tree_rmb_select));
1236 joint_tree->connect("button_clicked", callable_mp(this, &Skeleton3DEditor::_joint_tree_button_clicked));
1237
1238 skeleton->connect(SceneStringName(pose_updated), callable_mp(this, &Skeleton3DEditor::_draw_gizmo));
1239 skeleton->connect(SceneStringName(pose_updated), callable_mp(this, &Skeleton3DEditor::_update_properties));
1240 skeleton->connect(SceneStringName(bone_enabled_changed), callable_mp(this, &Skeleton3DEditor::_bone_enabled_changed));
1241 skeleton->connect(SceneStringName(show_rest_only_changed), callable_mp(this, &Skeleton3DEditor::_update_gizmo_visible));
1242
1243 get_tree()->connect("node_removed", callable_mp(this, &Skeleton3DEditor::_node_removed));
1244 } break;
1245 case NOTIFICATION_READY: {
1246 // Will trigger NOTIFICATION_THEME_CHANGED, but won't cause any loops if called here.
1247 add_theme_constant_override("separation", 0);
1248 } break;
1249 case NOTIFICATION_THEME_CHANGED: {
1250 skeleton_options->set_button_icon(get_editor_theme_icon(SNAME("Skeleton3D")));
1251 edit_mode_button->set_button_icon(get_editor_theme_icon(SNAME("ToolBoneSelect")));
1252 key_loc_button->set_button_icon(get_editor_theme_icon(SNAME("KeyPosition")));
1253 key_rot_button->set_button_icon(get_editor_theme_icon(SNAME("KeyRotation")));
1254 key_scale_button->set_button_icon(get_editor_theme_icon(SNAME("KeyScale")));
1255 key_insert_button->set_button_icon(get_editor_theme_icon(SNAME("InsertKey")));
1256 key_insert_new_button->set_button_icon(get_editor_theme_icon(SNAME("NewKey")));
1257 key_mod_insert_button->set_button_icon(get_editor_theme_icon(SNAME("InsertModKey")));
1258 key_mod_insert_new_button->set_button_icon(get_editor_theme_icon(SNAME("NewModKey")));
1259 bones_section->set_bg_color(get_theme_color(SNAME("prop_subsection"), EditorStringName(Editor)));
1260
1261 update_joint_tree();
1262 } break;
1263 case NOTIFICATION_PREDELETE: {
1264 if (skeleton) {
1265 select_bone(-1); // Requires that the joint_tree has not been deleted.
1266 _disconnect_from_skeleton();
1267 skeleton->set_transform_gizmo_visible(true);
1268
1269 if (handles_mesh_instance->get_parent()) {
1270 handles_mesh_instance->get_parent()->remove_child(handles_mesh_instance);
1271 }
1272 }
1273 edit_mode_toggled(false);
1274 } break;
1275 }
1276 }
1277
1278 void Skeleton3DEditor::_node_removed(Node *p_node) {
1279 if (skeleton && p_node == skeleton) {
1280 _disconnect_from_skeleton();
1281 if (pose_editor) {
1282 pose_editor->set_skeleton(nullptr);
1283 pose_editor->set_visible(false);
1284 }
1285 edit_mode = false;
1286 skeleton = nullptr;
1287 skeleton_options->hide();
1288 }
1289
1290 _update_properties();
1291 }
1292
1293 void Skeleton3DEditor::_disconnect_from_skeleton() {
1294 if (!skeleton) {
1295 return;
1296 }
1297
1298 if (skeleton->is_connected(SceneStringName(show_rest_only_changed), callable_mp(this, &Skeleton3DEditor::_update_gizmo_visible))) {
1299 skeleton->disconnect(SceneStringName(show_rest_only_changed), callable_mp(this, &Skeleton3DEditor::_update_gizmo_visible));
1300 }
1301 if (skeleton->is_connected(SceneStringName(bone_enabled_changed), callable_mp(this, &Skeleton3DEditor::_bone_enabled_changed))) {
1302 skeleton->disconnect(SceneStringName(bone_enabled_changed), callable_mp(this, &Skeleton3DEditor::_bone_enabled_changed));
1303 }
1304 if (skeleton->is_connected(SceneStringName(pose_updated), callable_mp(this, &Skeleton3DEditor::_draw_gizmo))) {
1305 skeleton->disconnect(SceneStringName(pose_updated), callable_mp(this, &Skeleton3DEditor::_draw_gizmo));
1306 }
1307 if (skeleton->is_connected(SceneStringName(pose_updated), callable_mp(this, &Skeleton3DEditor::_update_properties))) {
1308 skeleton->disconnect(SceneStringName(pose_updated), callable_mp(this, &Skeleton3DEditor::_update_properties));
1309 }
1310 }
1311
1312 void Skeleton3DEditor::edit_mode_toggled(const bool pressed) {
1313 edit_mode = pressed;
1314 _update_gizmo_visible();
1315 }
1316
1317 Skeleton3DEditor::Skeleton3DEditor(EditorInspectorPluginSkeleton *e_plugin, Skeleton3D *p_skeleton) :
1318 editor_plugin(e_plugin),
1319 skeleton(p_skeleton) {
1320 singleton = this;
1321
1322 // Handle.
1323 handle_material.instantiate();
1324 handle_shader.instantiate();
1325 handle_shader->set_code(R"(
1326 // Skeleton 3D gizmo handle shader.
1327
1328 shader_type spatial;
1329 render_mode unshaded, shadows_disabled, depth_draw_always, fog_disabled;
1330
1331 uniform sampler2D texture_albedo : source_color;
1332 uniform float point_size : hint_range(0, 128) = 32;
1333
1334 void vertex() {
1335 if (!OUTPUT_IS_SRGB) {
1336 COLOR.rgb = mix(pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb * (1.0 / 12.92), lessThan(COLOR.rgb, vec3(0.04045)));
1337 }
1338
1339 VERTEX = VERTEX;
1340 POSITION = PROJECTION_MATRIX * VIEW_MATRIX * MODEL_MATRIX * vec4(VERTEX.xyz, 1.0);
1341 POSITION.z = mix(POSITION.z, POSITION.w, 0.999);
1342 POINT_SIZE = point_size;
1343 }
1344
1345 void fragment() {
1346 vec4 albedo_tex = texture(texture_albedo, POINT_COORD);
1347 vec3 col = albedo_tex.rgb + COLOR.rgb;
1348 col = vec3(min(col.r, 1.0), min(col.g, 1.0), min(col.b, 1.0));
1349 ALBEDO = col;
1350
1351 if (albedo_tex.a < 0.5) {
1352 discard;
1353 }
1354
1355 ALPHA = albedo_tex.a;
1356 }
1357 )");
1358 handle_material->set_shader(handle_shader);
1359 Ref<Texture2D> handle = EditorNode::get_singleton()->get_editor_theme()->get_icon(SNAME("EditorBoneHandle"), EditorStringName(EditorIcons));
1360 handle_material->set_shader_parameter("point_size", handle->get_width());
1361 handle_material->set_shader_parameter("texture_albedo", handle);
1362
1363 handles_mesh_instance = memnew(MeshInstance3D);
1364 handles_mesh_instance->set_cast_shadows_setting(GeometryInstance3D::SHADOW_CASTING_SETTING_OFF);
1365 handles_mesh.instantiate();
1366 handles_mesh_instance->set_mesh(handles_mesh);
1367
1368 create_editors();
1369 }
1370
1371 void Skeleton3DEditor::update_bone_original() {
1372 if (!skeleton) {
1373 return;
1374 }
1375 if (skeleton->get_bone_count() == 0 || selected_bone == -1) {
1376 return;
1377 }
1378 bone_original_position = skeleton->get_bone_pose_position(selected_bone);
1379 bone_original_rotation = skeleton->get_bone_pose_rotation(selected_bone);
1380 bone_original_scale = skeleton->get_bone_pose_scale(selected_bone);
1381 }
1382
1383 void Skeleton3DEditor::_hide_handles() {
1384 handles_mesh_instance->hide();
1385 }
1386
1387 void Skeleton3DEditor::_draw_gizmo() {
1388 if (!skeleton) {
1389 return;
1390 }
1391
1392 // If you call get_bone_global_pose() while drawing the surface, such as toggle rest mode,
1393 // the skeleton update will be done first and
1394 // the drawing surface will be interrupted once and an error will occur.
1395 skeleton->force_update_all_dirty_bones();
1396
1397 // Handles.
1398 if (edit_mode) {
1399 _draw_handles();
1400 } else {
1401 _hide_handles();
1402 }
1403 }
1404
1405 void Skeleton3DEditor::_draw_handles() {
1406 const int bone_count = skeleton->get_bone_count();
1407
1408 handles_mesh->clear_surfaces();
1409
1410 if (bone_count) {
1411 handles_mesh_instance->show();
1412
1413 handles_mesh->surface_begin(Mesh::PRIMITIVE_POINTS);
1414
1415 for (int i = 0; i < bone_count; i++) {
1416 Color c;
1417 if (i == selected_bone) {
1418 c = Color(1, 1, 0);
1419 } else {
1420 c = Color(0.1, 0.25, 0.8);
1421 }
1422 Vector3 point = skeleton->get_bone_global_pose(i).origin;
1423 handles_mesh->surface_set_color(c);
1424 handles_mesh->surface_add_vertex(point);
1425 }
1426 handles_mesh->surface_end();
1427 handles_mesh->surface_set_material(0, handle_material);
1428 } else {
1429 handles_mesh_instance->hide();
1430 }
1431 }
1432
1433 TreeItem *Skeleton3DEditor::_find(TreeItem *p_node, const NodePath &p_path) {
1434 if (!p_node) {
1435 return nullptr;
1436 }
1437
1438 NodePath np = p_node->get_metadata(0);
1439 if (np == p_path) {
1440 return p_node;
1441 }
1442
1443 TreeItem *children = p_node->get_first_child();
1444 while (children) {
1445 TreeItem *n = _find(children, p_path);
1446 if (n) {
1447 return n;
1448 }
1449 children = children->get_next();
1450 }
1451
1452 return nullptr;
1453 }
1454
1455 void Skeleton3DEditor::_subgizmo_selection_change() {
1456 if (!skeleton) {
1457 return;
1458 }
1459
1460 // Once validated by subgizmos_intersect_ray, but required if through inspector's bones tree.
1461 if (!edit_mode) {
1462 skeleton->clear_subgizmo_selection();
1463 return;
1464 }
1465
1466 int selected = -1;
1467 Skeleton3DEditor *se = Skeleton3DEditor::get_singleton();
1468 if (se) {
1469 selected = se->get_selected_bone();
1470 }
1471
1472 if (selected >= 0) {
1473 Vector<Ref<Node3DGizmo>> gizmos = skeleton->get_gizmos();
1474 for (int i = 0; i < gizmos.size(); i++) {
1475 Ref<EditorNode3DGizmo> gizmo = gizmos[i];
1476 if (gizmo.is_null()) {
1477 continue;
1478 }
1479 Ref<Skeleton3DGizmoPlugin> plugin = gizmo->get_plugin();
1480 if (plugin.is_null()) {
1481 continue;
1482 }
1483 skeleton->set_subgizmo_selection(gizmo, selected, skeleton->get_bone_global_pose(selected));
1484 break;
1485 }
1486 } else {
1487 skeleton->clear_subgizmo_selection();
1488 }
1489 }
1490
1491 void Skeleton3DEditor::select_bone(int p_idx) {
1492 if (p_idx >= 0) {
1493 TreeItem *ti = _find(joint_tree->get_root(), "bones/" + itos(p_idx));
1494 if (ti) {
1495 // Make visible when it's collapsed.
1496 TreeItem *node = ti->get_parent();
1497 while (node && node != joint_tree->get_root()) {
1498 node->set_collapsed(false);
1499 node = node->get_parent();
1500 }
1501 ti->select(0);
1502 joint_tree->scroll_to_item(ti);
1503 }
1504 } else {
1505 selected_bone = -1;
1506 joint_tree->deselect_all();
1507 _joint_tree_selection_changed();
1508 }
1509 }
1510
1511 Skeleton3DEditor::~Skeleton3DEditor() {
1512 singleton = nullptr;
1513
1514 handles_mesh_instance->queue_free();
1515
1516 Node3DEditor *ne = Node3DEditor::get_singleton();
1517
1518 ne->remove_control_from_menu_panel(topmenu_bar);
1519 memdelete(topmenu_bar);
1520 }
1521
1522 bool EditorInspectorPluginSkeleton::can_handle(Object *p_object) {
1523 return Object::cast_to<Skeleton3D>(p_object) != nullptr;
1524 }
1525
1526 void EditorInspectorPluginSkeleton::parse_begin(Object *p_object) {
1527 Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_object);
1528 ERR_FAIL_NULL(skeleton);
1529
1530 skel_editor = memnew(Skeleton3DEditor(this, skeleton));
1531 add_custom_control(skel_editor);
1532 }
1533
1534 Skeleton3DEditorPlugin::Skeleton3DEditorPlugin() {
1535 skeleton_plugin = memnew(EditorInspectorPluginSkeleton);
1536
1537 EditorInspector::add_inspector_plugin(skeleton_plugin);
1538
1539 Ref<Skeleton3DGizmoPlugin> gizmo_plugin = Ref<Skeleton3DGizmoPlugin>(memnew(Skeleton3DGizmoPlugin));
1540 Node3DEditor::get_singleton()->add_gizmo_plugin(gizmo_plugin);
1541 }
1542
1543 EditorPlugin::AfterGUIInput Skeleton3DEditorPlugin::forward_3d_gui_input(Camera3D *p_camera, const Ref<InputEvent> &p_event) {
1544 Skeleton3DEditor *se = Skeleton3DEditor::get_singleton();
1545 if (se && se->is_edit_mode()) {
1546 const Ref<InputEventMouseButton> mb = p_event;
1547 if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT && mb->is_pressed()) {
1548 se->update_bone_original();
1549 }
1550 return EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
1551 }
1552 return EditorPlugin::AFTER_GUI_INPUT_PASS;
1553 }
1554
1555 bool Skeleton3DEditorPlugin::handles(Object *p_object) const {
1556 return p_object->is_class("Skeleton3D");
1557 }
1558
1559 void Skeleton3DEditor::_bone_enabled_changed(const int p_bone_id) {
1560 _update_gizmo_visible();
1561 }
1562
1563 void Skeleton3DEditor::_update_gizmo_visible() {
1564 if (!skeleton) {
1565 return;
1566 }
1567
1568 _subgizmo_selection_change();
1569 if (edit_mode) {
1570 if (selected_bone == -1) {
1571 skeleton->set_transform_gizmo_visible(false);
1572 } else {
1573 if (skeleton->is_bone_enabled(selected_bone) && !skeleton->is_show_rest_only()) {
1574 skeleton->set_transform_gizmo_visible(true);
1575 } else {
1576 skeleton->set_transform_gizmo_visible(false);
1577 }
1578 }
1579 } else {
1580 skeleton->set_transform_gizmo_visible(true);
1581 }
1582 _draw_gizmo();
1583 }
1584
1585 int Skeleton3DEditor::get_selected_bone() const {
1586 return selected_bone;
1587 }
1588
1589 Skeleton3DGizmoPlugin::SelectionMaterials Skeleton3DGizmoPlugin::selection_materials;
1590
1591 Skeleton3DGizmoPlugin::Skeleton3DGizmoPlugin() {
1592 selection_materials.unselected_mat.instantiate();
1593 selection_materials.unselected_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
1594 selection_materials.unselected_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
1595 selection_materials.unselected_mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
1596 selection_materials.unselected_mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
1597 selection_materials.unselected_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
1598
1599 selection_materials.selected_mat.instantiate();
1600 Ref<Shader> selected_sh = Ref<Shader>(memnew(Shader));
1601 selected_sh->set_code(R"(
1602 // Skeleton 3D gizmo bones shader.
1603
1604 shader_type spatial;
1605 render_mode unshaded, shadows_disabled;
1606
1607 void vertex() {
1608 if (!OUTPUT_IS_SRGB) {
1609 COLOR.rgb = mix(pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb * (1.0 / 12.92), lessThan(COLOR.rgb,vec3(0.04045)));
1610 }
1611 VERTEX = VERTEX;
1612 POSITION = PROJECTION_MATRIX * VIEW_MATRIX * MODEL_MATRIX * vec4(VERTEX.xyz, 1.0);
1613 POSITION.z = mix(POSITION.z, POSITION.w, 0.998);
1614 }
1615
1616 void fragment() {
1617 ALBEDO = COLOR.rgb;
1618 ALPHA = COLOR.a;
1619 }
1620 )");
1621 selection_materials.selected_mat->set_shader(selected_sh);
1622 }
1623
1624 Skeleton3DGizmoPlugin::~Skeleton3DGizmoPlugin() {
1625 selection_materials.unselected_mat.unref();
1626 selection_materials.selected_mat.unref();
1627 }
1628
1629 bool Skeleton3DGizmoPlugin::has_gizmo(Node3D *p_spatial) {
1630 return Object::cast_to<Skeleton3D>(p_spatial) != nullptr;
1631 }
1632
1633 String Skeleton3DGizmoPlugin::get_gizmo_name() const {
1634 return "Skeleton3D";
1635 }
1636
1637 int Skeleton3DGizmoPlugin::get_priority() const {
1638 return -1;
1639 }
1640
1641 int Skeleton3DGizmoPlugin::subgizmos_intersect_ray(const EditorNode3DGizmo *p_gizmo, Camera3D *p_camera, const Vector2 &p_point) const {
1642 Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_gizmo->get_node_3d());
1643 ERR_FAIL_NULL_V(skeleton, -1);
1644
1645 Skeleton3DEditor *se = Skeleton3DEditor::get_singleton();
1646
1647 if (!se || !se->is_edit_mode()) {
1648 return -1;
1649 }
1650
1651 int closest_idx = skeleton_intersect_ray(skeleton, p_camera, p_point);
1652
1653 if (closest_idx >= 0) {
1654 se->select_bone(closest_idx);
1655 se->update_bone_original();
1656 return closest_idx;
1657 }
1658
1659 se->select_bone(-1);
1660 return -1;
1661 }
1662
1663 int Skeleton3DGizmoPlugin::skeleton_intersect_ray(const Skeleton3D *p_skeleton, Camera3D *p_camera, const Vector2 &p_point) {
1664 real_t grab_threshold = 8 * EDSCALE;
1665 Vector3 ray_from = p_camera->get_global_transform().origin;
1666 Transform3D gt = p_skeleton->get_global_transform();
1667 int closest_idx = -1;
1668 real_t closest_dist = 1e10;
1669 const int bone_count = p_skeleton->get_bone_count();
1670 for (int i = 0; i < bone_count; i++) {
1671 Vector3 joint_pos_3d = gt.xform(p_skeleton->get_bone_global_pose(i).origin);
1672 Vector2 joint_pos_2d = p_camera->unproject_position(joint_pos_3d);
1673 real_t dist_3d = ray_from.distance_to(joint_pos_3d);
1674 real_t dist_2d = p_point.distance_to(joint_pos_2d);
1675 if (dist_2d < grab_threshold && dist_3d < closest_dist) {
1676 closest_dist = dist_3d;
1677 closest_idx = i;
1678 }
1679 }
1680 return closest_idx;
1681 }
1682
1683 Transform3D Skeleton3DGizmoPlugin::get_subgizmo_transform(const EditorNode3DGizmo *p_gizmo, int p_id) const {
1684 Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_gizmo->get_node_3d());
1685 ERR_FAIL_NULL_V(skeleton, Transform3D());
1686
1687 return skeleton->get_bone_global_pose(p_id);
1688 }
1689
1690 void Skeleton3DGizmoPlugin::set_subgizmo_transform(const EditorNode3DGizmo *p_gizmo, int p_id, Transform3D p_transform) {
1691 Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_gizmo->get_node_3d());
1692 ERR_FAIL_NULL(skeleton);
1693
1694 // Prepare for global to local.
1695 Transform3D original_to_local;
1696 int parent_idx = skeleton->get_bone_parent(p_id);
1697 if (parent_idx >= 0) {
1698 original_to_local = skeleton->get_bone_global_pose(parent_idx);
1699 }
1700 Basis to_local = original_to_local.get_basis().inverse();
1701
1702 // Prepare transform.
1703 Transform3D t;
1704
1705 // Basis.
1706 t.basis = to_local * p_transform.get_basis();
1707
1708 // Origin.
1709 Vector3 orig = skeleton->get_bone_pose(p_id).origin;
1710 Vector3 sub = p_transform.origin - skeleton->get_bone_global_pose(p_id).origin;
1711 t.origin = orig + to_local.xform(sub);
1712
1713 // Apply transform.
1714 skeleton->set_bone_pose_position(p_id, t.origin);
1715 skeleton->set_bone_pose_rotation(p_id, t.basis.get_rotation_quaternion());
1716 skeleton->set_bone_pose_scale(p_id, t.basis.get_scale());
1717 }
1718
1719 void Skeleton3DGizmoPlugin::commit_subgizmos(const EditorNode3DGizmo *p_gizmo, const Vector<int> &p_ids, const Vector<Transform3D> &p_restore, bool p_cancel) {
1720 Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_gizmo->get_node_3d());
1721 ERR_FAIL_NULL(skeleton);
1722
1723 Skeleton3DEditor *se = Skeleton3DEditor::get_singleton();
1724 Node3DEditor *ne = Node3DEditor::get_singleton();
1725
1726 EditorUndoRedoManager *ur = EditorUndoRedoManager::get_singleton();
1727 ur->create_action(TTR("Set Bone Transform"));
1728
1729 if (p_cancel) {
1730 for (int id : p_ids) {
1731 ur->add_do_method(skeleton, "set_bone_pose_position", id, se->get_bone_original_position());
1732 ur->add_do_method(skeleton, "set_bone_pose_rotation", id, se->get_bone_original_rotation());
1733 ur->add_do_method(skeleton, "set_bone_pose_scale", id, se->get_bone_original_scale());
1734 ur->add_undo_method(skeleton, "set_bone_pose_position", id, skeleton->get_bone_pose_position(id));
1735 ur->add_undo_method(skeleton, "set_bone_pose_rotation", id, skeleton->get_bone_pose_rotation(id));
1736 ur->add_undo_method(skeleton, "set_bone_pose_scale", id, skeleton->get_bone_pose_scale(id));
1737 }
1738 } else {
1739 Node3DEditor::ToolMode tool_mode = ne->get_tool_mode();
1740 if (tool_mode == Node3DEditor::TOOL_MODE_MOVE || tool_mode == Node3DEditor::TOOL_MODE_TRANSFORM) {
1741 for (int id : p_ids) {
1742 ur->add_do_method(skeleton, "set_bone_pose_position", id, skeleton->get_bone_pose_position(id));
1743 ur->add_undo_method(skeleton, "set_bone_pose_position", id, se->get_bone_original_position());
1744 }
1745 }
1746 if (tool_mode == Node3DEditor::TOOL_MODE_ROTATE || tool_mode == Node3DEditor::TOOL_MODE_TRANSFORM) {
1747 for (int id : p_ids) {
1748 ur->add_do_method(skeleton, "set_bone_pose_rotation", id, skeleton->get_bone_pose_rotation(id));
1749 ur->add_undo_method(skeleton, "set_bone_pose_rotation", id, se->get_bone_original_rotation());
1750 }
1751 }
1752 if (tool_mode == Node3DEditor::TOOL_MODE_SCALE || tool_mode == Node3DEditor::TOOL_MODE_TRANSFORM) {
1753 for (int id : p_ids) {
1754 ur->add_do_method(skeleton, "set_bone_pose_scale", id, skeleton->get_bone_pose_scale(id));
1755 ur->add_undo_method(skeleton, "set_bone_pose_scale", id, se->get_bone_original_scale());
1756 }
1757 }
1758 }
1759
1760 ur->add_do_method(se, "update_joint_tree");
1761 ur->add_undo_method(se, "update_joint_tree");
1762
1763 ur->commit_action();
1764 }
1765
1766 void Skeleton3DGizmoPlugin::redraw(EditorNode3DGizmo *p_gizmo) {
1767 Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_gizmo->get_node_3d());
1768 p_gizmo->clear();
1769
1770 if (!skeleton->get_bone_count()) {
1771 return;
1772 }
1773
1774 int selected = -1;
1775 Skeleton3DEditor *se = Skeleton3DEditor::get_singleton();
1776 if (se) {
1777 selected = se->get_selected_bone();
1778 }
1779
1780 Ref<ArrayMesh> m = get_bones_mesh(skeleton, selected, p_gizmo->is_selected());
1781 p_gizmo->add_mesh(m, Ref<Material>(), Transform3D(), skeleton->register_skin(skeleton->create_skin_from_rest_transforms()));
1782 }
1783
1784 Ref<ArrayMesh> Skeleton3DGizmoPlugin::get_bones_mesh(Skeleton3D *p_skeleton, int p_selected, bool p_is_selected) {
1785 Color bone_color = EDITOR_GET("editors/3d_gizmos/gizmo_colors/skeleton");
1786 Color selected_bone_color = EDITOR_GET("editors/3d_gizmos/gizmo_colors/selected_bone");
1787 real_t bone_axis_length = EDITOR_GET("editors/3d_gizmos/gizmo_settings/bone_axis_length");
1788 int bone_shape = EDITOR_GET("editors/3d_gizmos/gizmo_settings/bone_shape");
1789
1790 LocalVector<Color> axis_colors;
1791 axis_colors.push_back(Node3DEditor::get_singleton()->get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor)));
1792 axis_colors.push_back(Node3DEditor::get_singleton()->get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor)));
1793 axis_colors.push_back(Node3DEditor::get_singleton()->get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor)));
1794
1795 Ref<SurfaceTool> surface_tool(memnew(SurfaceTool));
1796 surface_tool->begin(Mesh::PRIMITIVE_LINES);
1797
1798 if (p_is_selected) {
1799 surface_tool->set_material(selection_materials.selected_mat);
1800 } else {
1801 selection_materials.unselected_mat->set_albedo(bone_color);
1802 surface_tool->set_material(selection_materials.unselected_mat);
1803 }
1804
1805 LocalVector<int> bones;
1806 LocalVector<float> weights;
1807 bones.resize(4);
1808 weights.resize(4);
1809 for (int i = 0; i < 4; i++) {
1810 bones[i] = 0;
1811 weights[i] = 0;
1812 }
1813 weights[0] = 1;
1814
1815 int current_bone_index = 0;
1816 Vector<int> bones_to_process = p_skeleton->get_parentless_bones();
1817
1818 while (bones_to_process.size() > current_bone_index) {
1819 int current_bone_idx = bones_to_process[current_bone_index];
1820 current_bone_index++;
1821
1822 Color current_bone_color = (current_bone_idx == p_selected) ? selected_bone_color : bone_color;
1823
1824 Vector<int> child_bones_vector;
1825 child_bones_vector = p_skeleton->get_bone_children(current_bone_idx);
1826 int child_bones_size = child_bones_vector.size();
1827
1828 for (int i = 0; i < child_bones_size; i++) {
1829 // Something wrong.
1830 if (child_bones_vector[i] < 0) {
1831 continue;
1832 }
1833
1834 int child_bone_idx = child_bones_vector[i];
1835
1836 Vector3 v0 = p_skeleton->get_bone_global_rest(current_bone_idx).origin;
1837 Vector3 v1 = p_skeleton->get_bone_global_rest(child_bone_idx).origin;
1838 Vector3 d = (v1 - v0).normalized();
1839 real_t dist = v0.distance_to(v1);
1840
1841 // Find closest axis.
1842 int closest = -1;
1843 real_t closest_d = 0.0;
1844 for (int j = 0; j < 3; j++) {
1845 real_t dp = Math::abs(p_skeleton->get_bone_global_rest(current_bone_idx).basis[j].normalized().dot(d));
1846 if (j == 0 || dp > closest_d) {
1847 closest = j;
1848 }
1849 }
1850
1851 // Draw bone.
1852 switch (bone_shape) {
1853 case 0: { // Wire shape.
1854 surface_tool->set_color(current_bone_color);
1855 bones[0] = current_bone_idx;
1856 surface_tool->set_bones(Vector<int>(bones));
1857 surface_tool->set_weights(Vector<float>(weights));
1858 surface_tool->add_vertex(v0);
1859 bones[0] = child_bone_idx;
1860 surface_tool->set_bones(Vector<int>(bones));
1861 surface_tool->set_weights(Vector<float>(weights));
1862 surface_tool->add_vertex(v1);
1863 } break;
1864
1865 case 1: { // Octahedron shape.
1866 Vector3 first;
1867 Vector3 points[6];
1868 int point_idx = 0;
1869 for (int j = 0; j < 3; j++) {
1870 Vector3 axis;
1871 if (first == Vector3()) {
1872 axis = d.cross(d.cross(p_skeleton->get_bone_global_rest(current_bone_idx).basis[j])).normalized();
1873 first = axis;
1874 } else {
1875 axis = d.cross(first).normalized();
1876 }
1877
1878 surface_tool->set_color(current_bone_color);
1879 for (int k = 0; k < 2; k++) {
1880 if (k == 1) {
1881 axis = -axis;
1882 }
1883 Vector3 point = v0 + d * dist * 0.2;
1884 point += axis * dist * 0.1;
1885
1886 bones[0] = current_bone_idx;
1887 surface_tool->set_bones(Vector<int>(bones));
1888 surface_tool->set_weights(Vector<float>(weights));
1889 surface_tool->add_vertex(v0);
1890 surface_tool->set_bones(Vector<int>(bones));
1891 surface_tool->set_weights(Vector<float>(weights));
1892 surface_tool->add_vertex(point);
1893
1894 surface_tool->set_bones(Vector<int>(bones));
1895 surface_tool->set_weights(Vector<float>(weights));
1896 surface_tool->add_vertex(point);
1897 bones[0] = child_bone_idx;
1898 surface_tool->set_bones(Vector<int>(bones));
1899 surface_tool->set_weights(Vector<float>(weights));
1900 surface_tool->add_vertex(v1);
1901 points[point_idx++] = point;
1902 }
1903 }
1904 surface_tool->set_color(current_bone_color);
1905 SWAP(points[1], points[2]);
1906 bones[0] = current_bone_idx;
1907 for (int j = 0; j < 6; j++) {
1908 surface_tool->set_bones(Vector<int>(bones));
1909 surface_tool->set_weights(Vector<float>(weights));
1910 surface_tool->add_vertex(points[j]);
1911 surface_tool->set_bones(Vector<int>(bones));
1912 surface_tool->set_weights(Vector<float>(weights));
1913 surface_tool->add_vertex(points[(j + 1) % 6]);
1914 }
1915 } break;
1916 }
1917
1918 // Axis as root of the bone.
1919 for (int j = 0; j < 3; j++) {
1920 bones[0] = current_bone_idx;
1921 surface_tool->set_color(axis_colors[j]);
1922 surface_tool->set_bones(Vector<int>(bones));
1923 surface_tool->set_weights(Vector<float>(weights));
1924 surface_tool->add_vertex(v0);
1925 surface_tool->set_bones(Vector<int>(bones));
1926 surface_tool->set_weights(Vector<float>(weights));
1927 surface_tool->add_vertex(v0 + (p_skeleton->get_bone_global_rest(current_bone_idx).basis.inverse())[j].normalized() * dist * bone_axis_length);
1928
1929 if (j == closest) {
1930 continue;
1931 }
1932 }
1933
1934 // Axis at the end of the bone children.
1935 if (i == child_bones_size - 1) {
1936 for (int j = 0; j < 3; j++) {
1937 bones[0] = child_bone_idx;
1938 surface_tool->set_color(axis_colors[j]);
1939 surface_tool->set_bones(Vector<int>(bones));
1940 surface_tool->set_weights(Vector<float>(weights));
1941 surface_tool->add_vertex(v1);
1942 surface_tool->set_bones(Vector<int>(bones));
1943 surface_tool->set_weights(Vector<float>(weights));
1944 surface_tool->add_vertex(v1 + (p_skeleton->get_bone_global_rest(child_bone_idx).basis.inverse())[j].normalized() * dist * bone_axis_length);
1945
1946 if (j == closest) {
1947 continue;
1948 }
1949 }
1950 }
1951
1952 // Add the bone's children to the list of bones to be processed.
1953 bones_to_process.push_back(child_bones_vector[i]);
1954 }
1955 }
1956
1957 return surface_tool->commit();
1958 }