Debian Codegraph @

editor/scene/3d/node_3d_editor_plugin.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* node_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 "node_3d_editor_plugin.h"
32
33 #include "core/config/project_settings.h"
34 #include "core/input/input.h"
35 #include "core/input/input_map.h"
36 #include "core/math/math_funcs.h"
37 #include "core/math/projection.h"
38 #include "core/os/keyboard.h"
39 #include "core/string/translation_server.h"
40 #include "editor/animation/animation_player_editor_plugin.h"
41 #include "editor/debugger/editor_debugger_node.h"
42 #include "editor/docks/scene_tree_dock.h"
43 #include "editor/editor_main_screen.h"
44 #include "editor/editor_node.h"
45 #include "editor/editor_string_names.h"
46 #include "editor/editor_undo_redo_manager.h"
47 #include "editor/gui/editor_spin_slider.h"
48 #include "editor/plugins/editor_plugin_list.h"
49 #include "editor/run/editor_run_bar.h"
50 #include "editor/scene/3d/gizmos/audio_listener_3d_gizmo_plugin.h"
51 #include "editor/scene/3d/gizmos/audio_stream_player_3d_gizmo_plugin.h"
52 #include "editor/scene/3d/gizmos/camera_3d_gizmo_plugin.h"
53 #include "editor/scene/3d/gizmos/chain_ik_3d_gizmo_plugin.h"
54 #include "editor/scene/3d/gizmos/cpu_particles_3d_gizmo_plugin.h"
55 #include "editor/scene/3d/gizmos/decal_gizmo_plugin.h"
56 #include "editor/scene/3d/gizmos/fog_volume_gizmo_plugin.h"
57 #include "editor/scene/3d/gizmos/geometry_instance_3d_gizmo_plugin.h"
58 #include "editor/scene/3d/gizmos/gpu_particles_3d_gizmo_plugin.h"
59 #include "editor/scene/3d/gizmos/gpu_particles_collision_3d_gizmo_plugin.h"
60 #include "editor/scene/3d/gizmos/label_3d_gizmo_plugin.h"
61 #include "editor/scene/3d/gizmos/light_3d_gizmo_plugin.h"
62 #include "editor/scene/3d/gizmos/lightmap_gi_gizmo_plugin.h"
63 #include "editor/scene/3d/gizmos/lightmap_probe_gizmo_plugin.h"
64 #include "editor/scene/3d/gizmos/marker_3d_gizmo_plugin.h"
65 #include "editor/scene/3d/gizmos/mesh_instance_3d_gizmo_plugin.h"
66 #include "editor/scene/3d/gizmos/occluder_instance_3d_gizmo_plugin.h"
67 #include "editor/scene/3d/gizmos/particles_3d_emission_shape_gizmo_plugin.h"
68 #include "editor/scene/3d/gizmos/physics/collision_object_3d_gizmo_plugin.h"
69 #include "editor/scene/3d/gizmos/physics/collision_polygon_3d_gizmo_plugin.h"
70 #include "editor/scene/3d/gizmos/physics/collision_shape_3d_gizmo_plugin.h"
71 #include "editor/scene/3d/gizmos/physics/joint_3d_gizmo_plugin.h"
72 #include "editor/scene/3d/gizmos/physics/physics_bone_3d_gizmo_plugin.h"
73 #include "editor/scene/3d/gizmos/physics/ray_cast_3d_gizmo_plugin.h"
74 #include "editor/scene/3d/gizmos/physics/shape_cast_3d_gizmo_plugin.h"
75 #include "editor/scene/3d/gizmos/physics/soft_body_3d_gizmo_plugin.h"
76 #include "editor/scene/3d/gizmos/physics/spring_arm_3d_gizmo_plugin.h"
77 #include "editor/scene/3d/gizmos/physics/vehicle_body_3d_gizmo_plugin.h"
78 #include "editor/scene/3d/gizmos/reflection_probe_gizmo_plugin.h"
79 #include "editor/scene/3d/gizmos/spring_bone_3d_gizmo_plugin.h"
80 #include "editor/scene/3d/gizmos/sprite_base_3d_gizmo_plugin.h"
81 #include "editor/scene/3d/gizmos/two_bone_ik_3d_gizmo_plugin.h"
82 #include "editor/scene/3d/gizmos/visible_on_screen_notifier_3d_gizmo_plugin.h"
83 #include "editor/scene/3d/gizmos/voxel_gi_gizmo_plugin.h"
84 #include "editor/scene/3d/node_3d_editor_gizmos.h"
85 #include "editor/settings/editor_settings.h"
86 #include "editor/translations/editor_translation_preview_button.h"
87 #include "editor/translations/editor_translation_preview_menu.h"
88 #include "scene/3d/audio_stream_player_3d.h"
89 #include "scene/3d/camera_3d.h"
90 #include "scene/3d/decal.h"
91 #include "scene/3d/light_3d.h"
92 #include "scene/3d/mesh_instance_3d.h"
93 #include "scene/3d/physics/collision_shape_3d.h"
94 #include "scene/3d/physics/physics_body_3d.h"
95 #include "scene/3d/sprite_3d.h"
96 #include "scene/3d/visual_instance_3d.h"
97 #include "scene/3d/world_environment.h"
98 #include "scene/gui/center_container.h"
99 #include "scene/gui/color_picker.h"
100 #include "scene/gui/flow_container.h"
101 #include "scene/gui/separator.h"
102 #include "scene/gui/split_container.h"
103 #include "scene/gui/subviewport_container.h"
104 #include "scene/resources/3d/sky_material.h"
105 #include "scene/resources/packed_scene.h"
106 #include "scene/resources/surface_tool.h"
107
108 constexpr real_t DISTANCE_DEFAULT = 4;
109
110 constexpr real_t GIZMO_ARROW_SIZE = 0.35;
111 constexpr real_t GIZMO_RING_HALF_WIDTH = 0.1;
112 constexpr real_t GIZMO_PLANE_SIZE = 0.2;
113 constexpr real_t GIZMO_PLANE_DST = 0.3;
114 constexpr real_t GIZMO_CIRCLE_SIZE = 1.1;
115 constexpr real_t GIZMO_VIEW_ROTATION_SIZE = 1.25;
116 constexpr real_t GIZMO_SCALE_OFFSET = GIZMO_CIRCLE_SIZE + 0.3;
117 constexpr real_t GIZMO_ARROW_OFFSET = GIZMO_CIRCLE_SIZE + 0.3;
118
119 constexpr real_t ZOOM_FREELOOK_MIN = 0.01;
120 constexpr real_t ZOOM_FREELOOK_MULTIPLIER = 1.08;
121 constexpr real_t ZOOM_FREELOOK_INDICATOR_DELAY_S = 1.5;
122
123 #ifdef REAL_T_IS_DOUBLE
124 constexpr double ZOOM_FREELOOK_MAX = 1'000'000'000'000;
125 #else
126 constexpr float ZOOM_FREELOOK_MAX = 10'000;
127 #endif
128
129 constexpr real_t MIN_Z = 0.01;
130 constexpr real_t MAX_Z = 1000000.0;
131
132 constexpr real_t MIN_FOV = 0.01;
133 constexpr real_t MAX_FOV = 179;
134
135 void ViewportNavigationControl::_notification(int p_what) {
136 switch (p_what) {
137 case NOTIFICATION_DRAW: {
138 if (viewport != nullptr) {
139 _draw();
140 _update_navigation();
141 }
142 } break;
143
144 case NOTIFICATION_MOUSE_ENTER: {
145 hovered = true;
146 queue_redraw();
147 } break;
148
149 case NOTIFICATION_MOUSE_EXIT: {
150 hovered = false;
151 queue_redraw();
152 } break;
153 }
154 }
155
156 void ViewportNavigationControl::_draw() {
157 if (nav_mode == Node3DEditorViewport::NAVIGATION_NONE) {
158 return;
159 }
160
161 Vector2 center = get_size() / 2.0;
162 float radius = get_size().x / 2.0;
163
164 const bool focused = focused_index != -1;
165 draw_circle(center, radius, Color(0.5, 0.5, 0.5, focused || hovered ? 0.35 : 0.15));
166
167 const Color c = focused ? Color(0.9, 0.9, 0.9, 0.9) : Color(0.5, 0.5, 0.5, 0.25);
168
169 Vector2 circle_pos = focused ? center.move_toward(focused_pos, radius) : center;
170
171 draw_circle(circle_pos, AXIS_CIRCLE_RADIUS, c);
172 draw_circle(circle_pos, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4));
173 }
174
175 void ViewportNavigationControl::_process_click(int p_index, Vector2 p_position, bool p_pressed) {
176 hovered = false;
177 queue_redraw();
178
179 if (focused_index != -1 && focused_index != p_index) {
180 return;
181 }
182 if (p_pressed) {
183 if (p_position.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
184 focused_pos = p_position;
185 focused_index = p_index;
186 queue_redraw();
187 }
188 } else {
189 focused_index = -1;
190 if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
191 Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
192 Input::get_singleton()->warp_mouse(focused_mouse_start);
193 }
194 }
195 }
196
197 void ViewportNavigationControl::_process_drag(int p_index, Vector2 p_position, Vector2 p_relative_position) {
198 if (focused_index == p_index) {
199 if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
200 Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
201 focused_mouse_start = p_position;
202 }
203 focused_pos += p_relative_position;
204 queue_redraw();
205 }
206 }
207
208 void ViewportNavigationControl::gui_input(const Ref<InputEvent> &p_event) {
209 // Mouse events
210 const Ref<InputEventMouseButton> mouse_button = p_event;
211 if (mouse_button.is_valid() && mouse_button->get_button_index() == MouseButton::LEFT) {
212 _process_click(100, mouse_button->get_position(), mouse_button->is_pressed());
213 }
214
215 const Ref<InputEventMouseMotion> mouse_motion = p_event;
216 if (mouse_motion.is_valid()) {
217 _process_drag(100, mouse_motion->get_global_position(), viewport->_get_warped_mouse_motion(mouse_motion));
218 }
219
220 // Touch events
221 const Ref<InputEventScreenTouch> screen_touch = p_event;
222 if (screen_touch.is_valid()) {
223 _process_click(screen_touch->get_index(), screen_touch->get_position(), screen_touch->is_pressed());
224 }
225
226 const Ref<InputEventScreenDrag> screen_drag = p_event;
227 if (screen_drag.is_valid()) {
228 _process_drag(screen_drag->get_index(), screen_drag->get_position(), screen_drag->get_relative());
229 }
230 }
231
232 void ViewportNavigationControl::_update_navigation() {
233 if (focused_index == -1) {
234 return;
235 }
236
237 Vector2 delta = focused_pos - (get_size() / 2.0);
238 Vector2 delta_normalized = delta.normalized();
239 switch (nav_mode) {
240 case Node3DEditorViewport::NavigationMode::NAVIGATION_MOVE: {
241 real_t speed_multiplier = MIN(delta.length() / (get_size().x * 100.0), 3.0);
242 real_t speed = viewport->freelook_speed * speed_multiplier;
243
244 const Node3DEditorViewport::FreelookNavigationScheme navigation_scheme = (Node3DEditorViewport::FreelookNavigationScheme)EDITOR_GET("editors/3d/freelook/freelook_navigation_scheme").operator int();
245
246 Vector3 forward;
247 if (navigation_scheme == Node3DEditorViewport::FreelookNavigationScheme::FREELOOK_FULLY_AXIS_LOCKED) {
248 // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
249 forward = Vector3(0, 0, delta_normalized.y).rotated(Vector3(0, 1, 0), viewport->camera->get_rotation().y);
250 } else {
251 // Forward/backward keys will be relative to the camera pitch.
252 forward = viewport->camera->get_transform().basis.xform(Vector3(0, 0, delta_normalized.y));
253 }
254
255 const Vector3 right = viewport->camera->get_transform().basis.xform(Vector3(delta_normalized.x, 0, 0));
256
257 const Vector3 direction = forward + right;
258 const Vector3 motion = direction * speed;
259 viewport->cursor.pos += motion;
260 viewport->cursor.eye_pos += motion;
261 } break;
262
263 case Node3DEditorViewport::NavigationMode::NAVIGATION_LOOK: {
264 real_t speed_multiplier = MIN(delta.length() / (get_size().x * 2.5), 3.0);
265 real_t speed = viewport->freelook_speed * speed_multiplier;
266 viewport->_nav_look(nullptr, delta_normalized * speed);
267 } break;
268
269 case Node3DEditorViewport::NAVIGATION_PAN: {
270 real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
271 real_t speed = viewport->freelook_speed * speed_multiplier;
272 viewport->_nav_pan(nullptr, -delta_normalized * speed);
273 } break;
274 case Node3DEditorViewport::NAVIGATION_ZOOM: {
275 real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
276 real_t speed = viewport->freelook_speed * speed_multiplier;
277 viewport->_nav_zoom(nullptr, delta_normalized * speed);
278 } break;
279 case Node3DEditorViewport::NAVIGATION_ORBIT: {
280 real_t speed_multiplier = MIN(delta.length() / (get_size().x), 3.0);
281 real_t speed = viewport->freelook_speed * speed_multiplier;
282 viewport->_nav_orbit(nullptr, delta_normalized * speed);
283 } break;
284 case Node3DEditorViewport::NAVIGATION_NONE: {
285 } break;
286 }
287 }
288
289 void ViewportNavigationControl::set_navigation_mode(Node3DEditorViewport::NavigationMode p_nav_mode) {
290 nav_mode = p_nav_mode;
291 }
292
293 void ViewportNavigationControl::set_viewport(Node3DEditorViewport *p_viewport) {
294 viewport = p_viewport;
295 }
296
297 void ViewportRotationControl::_notification(int p_what) {
298 switch (p_what) {
299 case NOTIFICATION_ENTER_TREE: {
300 axis_menu_options.clear();
301 axis_menu_options.push_back(Node3DEditorViewport::VIEW_RIGHT);
302 axis_menu_options.push_back(Node3DEditorViewport::VIEW_TOP);
303 axis_menu_options.push_back(Node3DEditorViewport::VIEW_FRONT);
304 axis_menu_options.push_back(Node3DEditorViewport::VIEW_LEFT);
305 axis_menu_options.push_back(Node3DEditorViewport::VIEW_BOTTOM);
306 axis_menu_options.push_back(Node3DEditorViewport::VIEW_REAR);
307
308 axis_colors.clear();
309 axis_colors.push_back(get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor)));
310 axis_colors.push_back(get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor)));
311 axis_colors.push_back(get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor)));
312 queue_redraw();
313 } break;
314
315 case NOTIFICATION_DRAW: {
316 if (viewport != nullptr) {
317 _draw();
318 }
319 } break;
320
321 case NOTIFICATION_MOUSE_EXIT: {
322 focused_axis = -2;
323 queue_redraw();
324 } break;
325
326 case NOTIFICATION_WM_WINDOW_FOCUS_OUT: {
327 gizmo_activated = false;
328 } break;
329 }
330 }
331
332 void ViewportRotationControl::_draw() {
333 const Vector2 center = get_size() / 2.0;
334 const real_t radius = get_size().x / 2.0;
335
336 if (focused_axis > -2 || orbiting_index != -1) {
337 draw_circle(center, radius, Color(0.5, 0.5, 0.5, 0.25), true, -1.0, true);
338 }
339
340 Vector<Axis2D> axis_to_draw;
341 _get_sorted_axis(axis_to_draw);
342 for (int i = 0; i < axis_to_draw.size(); ++i) {
343 _draw_axis(axis_to_draw[i]);
344 }
345 }
346
347 void ViewportRotationControl::_draw_axis(const Axis2D &p_axis) {
348 const bool focused = focused_axis == p_axis.axis;
349 const bool positive = p_axis.is_positive;
350 const int direction = p_axis.axis % 3;
351
352 const Color axis_color = axis_colors[direction];
353 const double min_alpha = 0.35;
354 const double alpha = focused ? 1.0 : Math::remap((p_axis.z_axis + 1.0) / 2.0, 0, 0.5, min_alpha, 1.0);
355 const Color c = focused ? Color(axis_color.lightened(0.25), 1.0) : Color(axis_color, alpha);
356
357 // Highlight positive axis text when hovered.
358 const Color c_positive_axis = focused ? Color(1.0, 1.0, 1.0, alpha) : Color(0.0, 0.0, 0.0, alpha * 0.6);
359
360 // Highlight negative axis text when hovered, but hide when not focused.
361 const Color c_negative_axis = focused ? Color(1.0, 1.0, 1.0, alpha) : Color(axis_color, 0);
362
363 if (positive) {
364 // Draw axis lines for the positive axes.
365 const Vector2 center = get_size() / 2.0;
366 const Vector2 diff = p_axis.screen_point - center;
367 const float line_length = MAX(diff.length() - AXIS_CIRCLE_RADIUS - 0.5 * EDSCALE, 0);
368
369 draw_line(center + diff.limit_length(0.5 * EDSCALE), center + diff.limit_length(line_length), c, 1.5 * EDSCALE, true);
370
371 draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c, true, -1.0, true);
372
373 // Draw the axis letter for the positive axes.
374 const String axis_name = direction == 0 ? "X" : (direction == 1 ? "Y" : "Z");
375 const Ref<Font> &font = get_theme_font(SNAME("rotation_control"), EditorStringName(EditorFonts));
376 const int font_size = get_theme_font_size(SNAME("rotation_control_size"), EditorStringName(EditorFonts));
377 const Size2 char_size = font->get_char_size(axis_name[0], font_size);
378 const Vector2 char_offset = Vector2(-char_size.width / 2.0, char_size.height * 0.25);
379 draw_char(font, p_axis.screen_point + char_offset, axis_name, font_size, c_positive_axis);
380 } else {
381 // Draw an outline around the negative axes.
382 draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS, c, true, -1.0, true);
383 draw_circle(p_axis.screen_point, AXIS_CIRCLE_RADIUS * 0.8, c.darkened(0.4), true, -1.0, true);
384
385 // Draw the text for the negative axes.
386 const String axis_name = direction == 0 ? "-X" : (direction == 1 ? "-Y" : "-Z");
387 const Ref<Font> &font = get_theme_font(SNAME("rotation_control"), EditorStringName(EditorFonts));
388 const int font_size = get_theme_font_size(SNAME("rotation_control_size"), EditorStringName(EditorFonts));
389 const Size2 string_size = font->get_string_size(axis_name, HORIZONTAL_ALIGNMENT_LEFT, -1.0f, font_size);
390 const float font_ascent = font->get_ascent(font_size);
391 const float font_descent = font->get_descent(font_size);
392 const float string_height = font_ascent + font_descent;
393 const Vector2 offset(-string_size.width / 2.0, string_height * 0.25);
394 draw_string(font, p_axis.screen_point + offset, axis_name, HORIZONTAL_ALIGNMENT_LEFT, -1.0f, font_size, c_negative_axis);
395 }
396 }
397
398 void ViewportRotationControl::_get_sorted_axis(Vector<Axis2D> &r_axis) {
399 const Vector2 center = get_size() / 2.0;
400 const real_t radius = get_size().x / 2.0 - AXIS_CIRCLE_RADIUS - 2.0 * EDSCALE;
401 const Basis camera_basis = viewport->to_camera_transform(viewport->cursor).get_basis().inverse();
402
403 for (int i = 0; i < 3; ++i) {
404 Vector3 axis_3d = camera_basis.get_column(i);
405 Vector2 axis_vector = Vector2(axis_3d.x, -axis_3d.y) * radius;
406
407 if (Math::abs(axis_3d.z) < 1.0) {
408 Axis2D pos_axis;
409 pos_axis.axis = i;
410 pos_axis.screen_point = center + axis_vector;
411 pos_axis.z_axis = axis_3d.z;
412 pos_axis.is_positive = true;
413 r_axis.push_back(pos_axis);
414
415 Axis2D neg_axis;
416 neg_axis.axis = i + 3;
417 neg_axis.screen_point = center - axis_vector;
418 neg_axis.z_axis = -axis_3d.z;
419 neg_axis.is_positive = false;
420 r_axis.push_back(neg_axis);
421 } else {
422 // Special case when the camera is aligned with one axis.
423 Axis2D axis;
424 axis.axis = i + (axis_3d.z <= 0 ? 0 : 3);
425 axis.screen_point = center;
426 axis.z_axis = 1.0;
427 // Invert display style to fix aligned axis rendering.
428 axis.is_positive = (axis_3d.z > 0);
429 r_axis.push_back(axis);
430 }
431 }
432
433 r_axis.sort_custom<Axis2DCompare>();
434 }
435
436 void ViewportRotationControl::_process_click(int p_index, Vector2 p_position, bool p_pressed) {
437 if (orbiting_index != -1 && orbiting_index != p_index) {
438 return;
439 }
440 if (p_pressed) {
441 if (p_position.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
442 orbiting_index = p_index;
443 }
444 } else {
445 if (focused_axis > -1 && gizmo_activated) {
446 viewport->_menu_option(axis_menu_options[focused_axis]);
447 _update_focus();
448 }
449 orbiting_index = -1;
450 if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
451 Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
452 Input::get_singleton()->warp_mouse(orbiting_mouse_start);
453 }
454 }
455 }
456
457 void ViewportRotationControl::_process_drag(Ref<InputEventWithModifiers> p_event, int p_index, Vector2 p_position, Vector2 p_relative_position) {
458 Point2 mouse_pos = get_local_mouse_position();
459 const bool movement_threshold_passed = original_mouse_pos.distance_to(mouse_pos) > 4 * EDSCALE;
460 if (orbiting_index == p_index && gizmo_activated && movement_threshold_passed) {
461 if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_VISIBLE) {
462 Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
463 orbiting_mouse_start = p_position;
464 viewport->previous_cursor = viewport->cursor;
465 }
466 viewport->_nav_orbit(p_event, p_relative_position);
467 focused_axis = -1;
468 } else {
469 _update_focus();
470 }
471 }
472
473 void ViewportRotationControl::gui_input(const Ref<InputEvent> &p_event) {
474 ERR_FAIL_COND(p_event.is_null());
475
476 // Key events
477 const Ref<InputEventKey> k = p_event;
478
479 if (k.is_valid() && k->is_action_pressed(SNAME("ui_cancel"), false, true)) {
480 if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
481 Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
482 Input::get_singleton()->warp_mouse(orbiting_mouse_start);
483 viewport->cursor = viewport->previous_cursor;
484 gizmo_activated = false;
485 }
486 }
487
488 // Mouse events
489 const Ref<InputEventMouseButton> mb = p_event;
490 if (mb.is_valid()) {
491 if (mb->get_button_index() == MouseButton::LEFT) {
492 _process_click(100, mb->get_position(), mb->is_pressed());
493 if (mb->is_pressed()) {
494 gizmo_activated = true;
495 original_mouse_pos = get_local_mouse_position();
496 grab_focus();
497 }
498 } else if (mb->get_button_index() == MouseButton::RIGHT) {
499 if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
500 Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
501 Input::get_singleton()->warp_mouse(orbiting_mouse_start);
502 viewport->cursor = viewport->previous_cursor;
503 gizmo_activated = false;
504 }
505 }
506 }
507
508 const Ref<InputEventMouseMotion> mm = p_event;
509 if (mm.is_valid()) {
510 _process_drag(mm, 100, mm->get_global_position(), viewport->_get_warped_mouse_motion(mm));
511 }
512
513 // Touch events
514 const Ref<InputEventScreenTouch> screen_touch = p_event;
515 if (screen_touch.is_valid()) {
516 _process_click(screen_touch->get_index(), screen_touch->get_position(), screen_touch->is_pressed());
517 }
518
519 const Ref<InputEventScreenDrag> screen_drag = p_event;
520 if (screen_drag.is_valid()) {
521 _process_drag(nullptr, screen_drag->get_index(), screen_drag->get_position(), screen_drag->get_relative());
522 }
523 }
524
525 void ViewportRotationControl::_update_focus() {
526 int original_focus = focused_axis;
527 focused_axis = -2;
528 Vector2 mouse_pos = get_local_mouse_position();
529
530 if (mouse_pos.distance_to(get_size() / 2.0) < get_size().x / 2.0) {
531 focused_axis = -1;
532 }
533
534 Vector<Axis2D> axes;
535 _get_sorted_axis(axes);
536
537 for (int i = 0; i < axes.size(); i++) {
538 const Axis2D &axis = axes[i];
539 if (mouse_pos.distance_to(axis.screen_point) < AXIS_CIRCLE_RADIUS) {
540 focused_axis = axis.axis;
541 }
542 }
543
544 if (focused_axis != original_focus) {
545 queue_redraw();
546 }
547 }
548
549 void ViewportRotationControl::set_viewport(Node3DEditorViewport *p_viewport) {
550 viewport = p_viewport;
551 }
552
553 void Node3DEditorViewport::_view_settings_confirmed(real_t p_interp_delta) {
554 // Set FOV override multiplier back to the default, so that the FOV
555 // setting specified in the View menu is correctly applied.
556 cursor.fov_scale = 1.0;
557
558 _update_camera(p_interp_delta);
559 }
560
561 void Node3DEditorViewport::_update_navigation_controls_visibility() {
562 bool show_viewport_rotation_gizmo = EDITOR_GET("editors/3d/navigation/show_viewport_rotation_gizmo") && (!previewing_cinema && !previewing_camera);
563 rotation_control->set_visible(show_viewport_rotation_gizmo);
564
565 bool show_viewport_navigation_gizmo = EDITOR_GET("editors/3d/navigation/show_viewport_navigation_gizmo") && (!previewing_cinema && !previewing_camera);
566 position_control->set_visible(show_viewport_navigation_gizmo);
567 look_control->set_visible(show_viewport_navigation_gizmo);
568 }
569
570 bool Node3DEditorViewport::_is_rotation_arc_visible() const {
571 return _edit.mode == TRANSFORM_ROTATE && _edit.accumulated_rotation_angle != 0.0 && _edit.gizmo_initiated;
572 }
573
574 void Node3DEditorViewport::_update_camera(real_t p_interp_delta) {
575 bool is_orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
576
577 Cursor old_camera_cursor = camera_cursor;
578 camera_cursor = cursor;
579
580 if (p_interp_delta > 0) {
581 //-------
582 // Perform smoothing
583
584 if (is_freelook_active()) {
585 // Higher inertia should increase "lag" (lerp with factor between 0 and 1)
586 // Inertia of zero should produce instant movement (lerp with factor of 1) in this case it returns a really high value and gets clamped to 1.
587 const real_t inertia = EDITOR_GET("editors/3d/freelook/freelook_inertia");
588 real_t factor = (1.0 / inertia) * p_interp_delta;
589
590 // We interpolate a different point here, because in freelook mode the focus point (cursor.pos) orbits around eye_pos
591 camera_cursor.eye_pos = old_camera_cursor.eye_pos.lerp(cursor.eye_pos, CLAMP(factor, 0, 1));
592
593 const real_t orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
594 camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
595 camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
596
597 if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
598 camera_cursor.x_rot = cursor.x_rot;
599 }
600
601 if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
602 camera_cursor.y_rot = cursor.y_rot;
603 }
604
605 Vector3 forward = to_camera_transform(camera_cursor).basis.xform(Vector3(0, 0, -1));
606 camera_cursor.pos = camera_cursor.eye_pos + forward * camera_cursor.distance;
607
608 } else {
609 const real_t orbit_inertia = EDITOR_GET("editors/3d/navigation_feel/orbit_inertia");
610 const real_t translation_inertia = EDITOR_GET("editors/3d/navigation_feel/translation_inertia");
611 const real_t zoom_inertia = EDITOR_GET("editors/3d/navigation_feel/zoom_inertia");
612
613 camera_cursor.x_rot = Math::lerp(old_camera_cursor.x_rot, cursor.x_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
614 camera_cursor.y_rot = Math::lerp(old_camera_cursor.y_rot, cursor.y_rot, MIN(1.f, p_interp_delta * (1 / orbit_inertia)));
615
616 if (Math::abs(camera_cursor.x_rot - cursor.x_rot) < 0.1) {
617 camera_cursor.x_rot = cursor.x_rot;
618 }
619
620 if (Math::abs(camera_cursor.y_rot - cursor.y_rot) < 0.1) {
621 camera_cursor.y_rot = cursor.y_rot;
622 }
623
624 camera_cursor.pos = old_camera_cursor.pos.lerp(cursor.pos, MIN(1.f, p_interp_delta * (1 / translation_inertia)));
625 camera_cursor.distance = Math::lerp(old_camera_cursor.distance, cursor.distance, MIN((real_t)1.0, p_interp_delta * (1 / zoom_inertia)));
626 }
627 }
628
629 //-------
630 // Apply camera transform
631
632 real_t tolerance = 0.001;
633 bool equal = true;
634 if (!Math::is_equal_approx(old_camera_cursor.x_rot, camera_cursor.x_rot, tolerance) || !Math::is_equal_approx(old_camera_cursor.y_rot, camera_cursor.y_rot, tolerance)) {
635 equal = false;
636 } else if (!old_camera_cursor.pos.is_equal_approx(camera_cursor.pos)) {
637 equal = false;
638 } else if (!Math::is_equal_approx(old_camera_cursor.distance, camera_cursor.distance, tolerance)) {
639 equal = false;
640 } else if (!Math::is_equal_approx(old_camera_cursor.fov_scale, camera_cursor.fov_scale, tolerance)) {
641 equal = false;
642 }
643
644 if (!equal || p_interp_delta == 0 || is_orthogonal != orthogonal) {
645 last_camera_transform = to_camera_transform(camera_cursor);
646 camera->set_global_transform(last_camera_transform);
647
648 if (orthogonal) {
649 float half_fov = Math::deg_to_rad(get_fov()) / 2.0;
650 float height = 2.0 * cursor.distance * Math::tan(half_fov);
651 camera->set_orthogonal(height, get_znear(), get_zfar());
652 } else {
653 camera->set_perspective(get_fov(), get_znear(), get_zfar());
654 }
655
656 update_transform_gizmo_view();
657 rotation_control->queue_redraw();
658 position_control->queue_redraw();
659 look_control->queue_redraw();
660 spatial_editor->update_grid();
661 }
662 }
663
664 Transform3D Node3DEditorViewport::to_camera_transform(const Cursor &p_cursor) const {
665 Transform3D camera_transform;
666 camera_transform.translate_local(p_cursor.pos);
667 camera_transform.basis.rotate(Vector3(1, 0, 0), -p_cursor.x_rot);
668 camera_transform.basis.rotate(Vector3(0, 1, 0), -p_cursor.y_rot);
669
670 if (orthogonal) {
671 camera_transform.translate_local(0, 0, (get_zfar() - get_znear()) / 2.0);
672 } else {
673 camera_transform.translate_local(0, 0, p_cursor.distance);
674 }
675
676 return camera_transform;
677 }
678
679 int Node3DEditorViewport::get_selected_count() const {
680 const HashMap<ObjectID, Object *> &selection = editor_selection->get_selection();
681
682 int count = 0;
683
684 for (const KeyValue<ObjectID, Object *> &E : selection) {
685 Node3D *sp = ObjectDB::get_instance<Node3D>(E.key);
686 if (!sp) {
687 continue;
688 }
689
690 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
691 if (!se) {
692 continue;
693 }
694
695 count++;
696 }
697
698 return count;
699 }
700
701 void Node3DEditorViewport::cancel_transform() {
702 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
703
704 for (Node *E : selection) {
705 Node3D *sp = Object::cast_to<Node3D>(E);
706 if (!sp) {
707 continue;
708 }
709
710 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
711 if (!se) {
712 continue;
713 }
714
715 if (se && se->gizmo.is_valid()) {
716 Vector<int> ids;
717 Vector<Transform3D> restore;
718
719 for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
720 ids.push_back(GE.key);
721 restore.push_back(GE.value);
722 }
723
724 se->gizmo->commit_subgizmos(ids, restore, true);
725 }
726
727 sp->set_global_transform(se->original);
728 }
729
730 collision_reposition = false;
731 finish_transform();
732 set_message(TTRC("Transform Aborted."), 3);
733 }
734
735 void Node3DEditorViewport::_update_shrink() {
736 const float scaling_3d_scale = GLOBAL_GET("rendering/scaling_3d/scale");
737 const float shrink_factor = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION)) ? 0.5 : 1.0;
738 viewport->set_scaling_3d_scale(MAX(0.25, scaling_3d_scale * shrink_factor));
739 }
740
741 float Node3DEditorViewport::get_znear() const {
742 return CLAMP(spatial_editor->get_znear(), MIN_Z, MAX_Z);
743 }
744
745 float Node3DEditorViewport::get_zfar() const {
746 return CLAMP(spatial_editor->get_zfar(), MIN_Z, MAX_Z);
747 }
748
749 float Node3DEditorViewport::get_fov() const {
750 return CLAMP(spatial_editor->get_fov() * cursor.fov_scale, MIN_FOV, MAX_FOV);
751 }
752
753 Transform3D Node3DEditorViewport::_get_camera_transform() const {
754 return camera->get_global_transform();
755 }
756
757 Vector3 Node3DEditorViewport::_get_camera_position() const {
758 return _get_camera_transform().origin;
759 }
760
761 Point2 Node3DEditorViewport::point_to_screen(const Vector3 &p_point) {
762 return camera->unproject_position(p_point);
763 }
764
765 Vector3 Node3DEditorViewport::get_ray_pos(const Vector2 &p_pos) const {
766 return camera->project_ray_origin(p_pos);
767 }
768
769 Vector3 Node3DEditorViewport::_get_camera_normal() const {
770 return -_get_camera_transform().basis.get_column(2);
771 }
772
773 Vector3 Node3DEditorViewport::get_ray(const Vector2 &p_pos) const {
774 return camera->project_ray_normal(p_pos);
775 }
776
777 void Node3DEditorViewport::_clear_selected() {
778 _edit.gizmo = Ref<EditorNode3DGizmo>();
779 _edit.gizmo_handle = -1;
780 _edit.gizmo_handle_secondary = false;
781 _edit.gizmo_initial_value = Variant();
782
783 Node3D *selected = spatial_editor->get_single_selected_node();
784 Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
785
786 if (se && se->gizmo.is_valid()) {
787 se->subgizmos.clear();
788 se->gizmo->redraw();
789 se->gizmo.unref();
790 spatial_editor->update_transform_gizmo();
791 } else {
792 editor_selection->clear();
793 Node3DEditor::get_singleton()->edit(nullptr);
794 }
795 }
796
797 void Node3DEditorViewport::_select_clicked(bool p_allow_locked) {
798 Node *node = ObjectDB::get_instance<Node3D>(clicked);
799 Node3D *selected = Object::cast_to<Node3D>(node);
800 clicked = ObjectID();
801
802 if (!selected) {
803 return;
804 }
805
806 Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
807
808 // Prevent selection of nodes not owned by the edited scene.
809 while (node && node != edited_scene->get_parent()) {
810 Node *node_owner = node->get_owner();
811 if (node_owner == edited_scene || node == edited_scene || (node_owner != nullptr && edited_scene->is_editable_instance(node_owner))) {
812 break;
813 }
814 node = node->get_parent();
815 selected = Object::cast_to<Node3D>(node);
816 }
817
818 if (!p_allow_locked) {
819 // Replace the node by the group if grouped
820 while (node && node != edited_scene->get_parent()) {
821 Node3D *selected_tmp = Object::cast_to<Node3D>(node);
822 if (selected_tmp && node->has_meta("_edit_group_")) {
823 selected = selected_tmp;
824 }
825 node = node->get_parent();
826 }
827 }
828
829 if (p_allow_locked || (selected != nullptr && !_is_node_locked(selected))) {
830 if (clicked_wants_append) {
831 const List<Node *> &top_node_list = editor_selection->get_top_selected_node_list();
832 const Node *active_node = top_node_list.is_empty() ? nullptr : top_node_list.back()->get();
833 if (editor_selection->is_selected(selected)) {
834 editor_selection->remove_node(selected);
835 if (selected != active_node) {
836 editor_selection->add_node(selected);
837 }
838 } else {
839 editor_selection->add_node(selected);
840 }
841 } else {
842 if (!editor_selection->is_selected(selected)) {
843 editor_selection->clear();
844 editor_selection->add_node(selected);
845 EditorNode::get_singleton()->edit_node(selected);
846 }
847 }
848
849 const List<Node *> &top_node_list = editor_selection->get_top_selected_node_list();
850 if (top_node_list.size() == 1) {
851 EditorNode::get_singleton()->edit_node(top_node_list.front()->get());
852 }
853 }
854 }
855
856 ObjectID Node3DEditorViewport::_select_ray(const Point2 &p_pos) const {
857 Vector3 ray = get_ray(p_pos);
858 Vector3 pos = get_ray_pos(p_pos);
859 Vector2 shrinked_pos = p_pos;
860
861 if (viewport->get_debug_draw() == Viewport::DEBUG_DRAW_SDFGI_PROBES) {
862 RS::get_singleton()->sdfgi_set_debug_probe_select(pos, ray);
863 }
864
865 HashSet<Ref<EditorNode3DGizmo>> found_gizmos;
866
867 Node *edited_scene = get_tree()->get_edited_scene_root();
868 ObjectID closest;
869 Node *item = nullptr;
870 float closest_dist = 1e20;
871
872 Vector<Node3D *> nodes_with_gizmos = Node3DEditor::get_singleton()->gizmo_bvh_ray_query(pos, pos + ray * camera->get_far());
873
874 for (Node3D *spat : nodes_with_gizmos) {
875 if (!spat || _is_node_locked(spat)) {
876 continue;
877 }
878
879 Vector<Ref<Node3DGizmo>> gizmos = spat->get_gizmos();
880
881 for (int j = 0; j < gizmos.size(); j++) {
882 Ref<EditorNode3DGizmo> seg = gizmos[j];
883
884 if (seg.is_null() || found_gizmos.has(seg)) {
885 continue;
886 }
887
888 found_gizmos.insert(seg);
889 Vector3 point;
890 Vector3 normal;
891
892 bool inters = seg->intersect_ray(camera, shrinked_pos, point, normal);
893
894 if (!inters) {
895 continue;
896 }
897
898 const real_t dist = pos.distance_to(point);
899
900 if (dist < 0) {
901 continue;
902 }
903
904 if (dist < closest_dist) {
905 item = Object::cast_to<Node>(spat);
906 if (item != edited_scene) {
907 item = edited_scene->get_deepest_editable_node(item);
908 }
909
910 closest = item->get_instance_id();
911 closest_dist = dist;
912 }
913 }
914 }
915
916 if (!item) {
917 return ObjectID();
918 }
919
920 return closest;
921 }
922
923 void Node3DEditorViewport::_find_items_at_pos(const Point2 &p_pos, Vector<_RayResult> &r_results, bool p_include_locked_nodes) {
924 Vector3 ray = get_ray(p_pos);
925 Vector3 pos = get_ray_pos(p_pos);
926
927 Vector<Node3D *> nodes_with_gizmos = Node3DEditor::get_singleton()->gizmo_bvh_ray_query(pos, pos + ray * camera->get_far());
928
929 HashSet<Node3D *> found_nodes;
930
931 for (Node3D *spat : nodes_with_gizmos) {
932 if (!spat) {
933 continue;
934 }
935
936 if (found_nodes.has(spat)) {
937 continue;
938 }
939
940 if (!p_include_locked_nodes && _is_node_locked(spat)) {
941 continue;
942 }
943
944 Vector<Ref<Node3DGizmo>> gizmos = spat->get_gizmos();
945 for (int j = 0; j < gizmos.size(); j++) {
946 Ref<EditorNode3DGizmo> seg = gizmos[j];
947
948 if (seg.is_null()) {
949 continue;
950 }
951
952 Vector3 point;
953 Vector3 normal;
954
955 bool inters = seg->intersect_ray(camera, p_pos, point, normal);
956
957 if (!inters) {
958 continue;
959 }
960
961 const real_t dist = pos.distance_to(point);
962
963 if (dist < 0) {
964 continue;
965 }
966
967 found_nodes.insert(spat);
968
969 _RayResult res;
970 res.item = spat;
971 res.depth = dist;
972 r_results.push_back(res);
973 break;
974 }
975 }
976
977 r_results.sort();
978 }
979
980 Vector3 Node3DEditorViewport::_get_screen_to_space(const Vector3 &p_vector3) {
981 Projection cm;
982 if (orthogonal) {
983 cm.set_orthogonal(camera->get_size(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
984 } else {
985 cm.set_perspective(get_fov(), get_size().aspect(), get_znear() + p_vector3.z, get_zfar());
986 }
987 Vector2 screen_he = cm.get_viewport_half_extents();
988
989 Transform3D camera_transform;
990 camera_transform.translate_local(cursor.pos);
991 camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
992 camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
993 camera_transform.translate_local(0, 0, cursor.distance);
994
995 return camera_transform.xform(Vector3(((p_vector3.x / get_size().width) * 2.0 - 1.0) * screen_he.x, ((1.0 - (p_vector3.y / get_size().height)) * 2.0 - 1.0) * screen_he.y, -(get_znear() + p_vector3.z)));
996 }
997
998 void Node3DEditorViewport::_select_region() {
999 if (cursor.region_begin == cursor.region_end) {
1000 if (!clicked_wants_append) {
1001 _clear_selected();
1002 }
1003 return; //nothing really
1004 }
1005
1006 const real_t z_offset = MAX(0.0, 5.0 - get_znear());
1007
1008 Vector3 box[4] = {
1009 Vector3(
1010 MIN(cursor.region_begin.x, cursor.region_end.x),
1011 MIN(cursor.region_begin.y, cursor.region_end.y),
1012 z_offset),
1013 Vector3(
1014 MAX(cursor.region_begin.x, cursor.region_end.x),
1015 MIN(cursor.region_begin.y, cursor.region_end.y),
1016 z_offset),
1017 Vector3(
1018 MAX(cursor.region_begin.x, cursor.region_end.x),
1019 MAX(cursor.region_begin.y, cursor.region_end.y),
1020 z_offset),
1021 Vector3(
1022 MIN(cursor.region_begin.x, cursor.region_end.x),
1023 MAX(cursor.region_begin.y, cursor.region_end.y),
1024 z_offset)
1025 };
1026
1027 Vector<Plane> frustum;
1028
1029 Vector3 cam_pos = _get_camera_position();
1030
1031 for (int i = 0; i < 4; i++) {
1032 Vector3 a = _get_screen_to_space(box[i]);
1033 Vector3 b = _get_screen_to_space(box[(i + 1) % 4]);
1034 if (orthogonal) {
1035 frustum.push_back(Plane((a - b).normalized(), a));
1036 } else {
1037 frustum.push_back(Plane(a, b, cam_pos));
1038 }
1039 }
1040
1041 Plane near_plane = Plane(-_get_camera_normal(), cam_pos);
1042 near_plane.d -= get_znear();
1043 frustum.push_back(near_plane);
1044
1045 Plane far_plane = -near_plane;
1046 far_plane.d += get_zfar();
1047 frustum.push_back(far_plane);
1048
1049 if (spatial_editor->get_single_selected_node()) {
1050 Node3D *single_selected = spatial_editor->get_single_selected_node();
1051 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(single_selected);
1052
1053 if (se) {
1054 Ref<EditorNode3DGizmo> old_gizmo;
1055 if (!clicked_wants_append) {
1056 se->subgizmos.clear();
1057 old_gizmo = se->gizmo;
1058 se->gizmo.unref();
1059 }
1060
1061 bool found_subgizmos = false;
1062 Vector<Ref<Node3DGizmo>> gizmos = single_selected->get_gizmos();
1063 for (int j = 0; j < gizmos.size(); j++) {
1064 Ref<EditorNode3DGizmo> seg = gizmos[j];
1065 if (seg.is_null()) {
1066 continue;
1067 }
1068
1069 if (se->gizmo.is_valid() && se->gizmo != seg) {
1070 continue;
1071 }
1072
1073 Vector<int> subgizmos = seg->subgizmos_intersect_frustum(camera, frustum);
1074 if (!subgizmos.is_empty()) {
1075 se->gizmo = seg;
1076 for (int i = 0; i < subgizmos.size(); i++) {
1077 int subgizmo_id = subgizmos[i];
1078 if (!se->subgizmos.has(subgizmo_id)) {
1079 se->subgizmos.insert(subgizmo_id, se->gizmo->get_subgizmo_transform(subgizmo_id));
1080 }
1081 }
1082 found_subgizmos = true;
1083 break;
1084 }
1085 }
1086
1087 if (!clicked_wants_append || found_subgizmos) {
1088 if (se->gizmo.is_valid()) {
1089 se->gizmo->redraw();
1090 }
1091
1092 if (old_gizmo != se->gizmo && old_gizmo.is_valid()) {
1093 old_gizmo->redraw();
1094 }
1095
1096 spatial_editor->update_transform_gizmo();
1097 }
1098
1099 if (found_subgizmos) {
1100 return;
1101 }
1102 }
1103 }
1104
1105 if (!clicked_wants_append) {
1106 _clear_selected();
1107 }
1108
1109 Vector<Node3D *> nodes_with_gizmos = Node3DEditor::get_singleton()->gizmo_bvh_frustum_query(frustum);
1110 HashSet<Node3D *> found_nodes;
1111 Vector<Node *> selected;
1112
1113 Node *edited_scene = get_tree()->get_edited_scene_root();
1114 if (edited_scene == nullptr) {
1115 return;
1116 }
1117
1118 for (Node3D *sp : nodes_with_gizmos) {
1119 if (!sp || _is_node_locked(sp)) {
1120 continue;
1121 }
1122
1123 if (found_nodes.has(sp)) {
1124 continue;
1125 }
1126 found_nodes.insert(sp);
1127
1128 Node *node = Object::cast_to<Node>(sp);
1129
1130 // Selection requires that the node is the edited scene or its descendant, and has an owner.
1131 if (node != edited_scene) {
1132 if (!node->get_owner() || !edited_scene->is_ancestor_of(node)) {
1133 continue;
1134 }
1135 node = edited_scene->get_deepest_editable_node(node);
1136 while (node != edited_scene) {
1137 Node *node_owner = node->get_owner();
1138 if (node_owner == edited_scene || (node_owner != nullptr && edited_scene->is_editable_instance(node_owner))) {
1139 break;
1140 }
1141 node = node->get_parent();
1142 }
1143 }
1144
1145 // Replace the node by the group if grouped
1146 if (node->is_class("Node3D")) {
1147 Node3D *sel = Object::cast_to<Node3D>(node);
1148 while (node && node != EditorNode::get_singleton()->get_edited_scene()->get_parent()) {
1149 Node3D *selected_tmp = Object::cast_to<Node3D>(node);
1150 if (selected_tmp && node->has_meta("_edit_group_")) {
1151 sel = selected_tmp;
1152 }
1153 node = node->get_parent();
1154 }
1155 node = sel;
1156 }
1157
1158 if (_is_node_locked(node)) {
1159 continue;
1160 }
1161
1162 Vector<Ref<Node3DGizmo>> gizmos = sp->get_gizmos();
1163 for (int j = 0; j < gizmos.size(); j++) {
1164 Ref<EditorNode3DGizmo> seg = gizmos[j];
1165 if (seg.is_null()) {
1166 continue;
1167 }
1168
1169 if (seg->intersect_frustum(camera, frustum)) {
1170 selected.push_back(node);
1171 }
1172 }
1173 }
1174
1175 for (int i = 0; i < selected.size(); i++) {
1176 if (!editor_selection->is_selected(selected[i])) {
1177 editor_selection->add_node(selected[i]);
1178 }
1179 }
1180
1181 const List<Node *> &top_node_list = editor_selection->get_top_selected_node_list();
1182 if (top_node_list.size() == 1) {
1183 EditorNode::get_singleton()->edit_node(top_node_list.front()->get());
1184 }
1185 }
1186
1187 void Node3DEditorViewport::_update_name() {
1188 String name;
1189
1190 switch (view_type) {
1191 case VIEW_TYPE_USER: {
1192 if (orthogonal) {
1193 name = TTR("Orthogonal");
1194 } else {
1195 name = TTR("Perspective");
1196 }
1197 } break;
1198 case VIEW_TYPE_TOP: {
1199 if (orthogonal) {
1200 name = TTR("Top Orthogonal");
1201 } else {
1202 name = TTR("Top Perspective");
1203 }
1204 } break;
1205 case VIEW_TYPE_BOTTOM: {
1206 if (orthogonal) {
1207 name = TTR("Bottom Orthogonal");
1208 } else {
1209 name = TTR("Bottom Perspective");
1210 }
1211 } break;
1212 case VIEW_TYPE_LEFT: {
1213 if (orthogonal) {
1214 name = TTR("Left Orthogonal");
1215 } else {
1216 name = TTR("Left Perspective");
1217 }
1218 } break;
1219 case VIEW_TYPE_RIGHT: {
1220 if (orthogonal) {
1221 name = TTR("Right Orthogonal");
1222 } else {
1223 name = TTR("Right Perspective");
1224 }
1225 } break;
1226 case VIEW_TYPE_FRONT: {
1227 if (orthogonal) {
1228 name = TTR("Front Orthogonal");
1229 } else {
1230 name = TTR("Front Perspective");
1231 }
1232 } break;
1233 case VIEW_TYPE_REAR: {
1234 if (orthogonal) {
1235 name = TTR("Rear Orthogonal");
1236 } else {
1237 name = TTR("Rear Perspective");
1238 }
1239 } break;
1240 }
1241
1242 if (orthogonal && auto_orthogonal) {
1243 // TRANSLATORS: This will be appended to the view name when Auto Orthogonal is enabled.
1244 name += " " + TTR("[auto]");
1245 }
1246
1247 view_display_menu->set_text(name);
1248 view_display_menu->reset_size();
1249 }
1250
1251 void Node3DEditorViewport::_compute_edit(const Point2 &p_point) {
1252 _edit.original_local = spatial_editor->are_local_coords_enabled();
1253 _edit.click_ray = get_ray(p_point);
1254 _edit.click_ray_pos = get_ray_pos(p_point);
1255 _edit.plane = TRANSFORM_VIEW;
1256 spatial_editor->update_transform_gizmo();
1257 _edit.center = spatial_editor->get_gizmo_transform().origin;
1258
1259 Node3D *selected = spatial_editor->get_single_selected_node();
1260 Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
1261
1262 if (se && se->gizmo.is_valid()) {
1263 for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
1264 int subgizmo_id = E.key;
1265 se->subgizmos[subgizmo_id] = se->gizmo->get_subgizmo_transform(subgizmo_id);
1266 }
1267 se->original_local = selected->get_transform();
1268 se->original = selected->get_global_transform();
1269 } else {
1270 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
1271
1272 for (Node *E : selection) {
1273 Node3D *sp = Object::cast_to<Node3D>(E);
1274 if (!sp) {
1275 continue;
1276 }
1277
1278 Node3DEditorSelectedItem *sel_item = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
1279
1280 if (!sel_item) {
1281 continue;
1282 }
1283
1284 sel_item->original_local = sel_item->sp->get_local_gizmo_transform();
1285 sel_item->original = sel_item->sp->get_global_gizmo_transform();
1286 }
1287 }
1288 }
1289
1290 static Key _get_key_modifier_setting(const String &p_property) {
1291 switch (EDITOR_GET(p_property).operator int()) {
1292 case 0:
1293 return Key::NONE;
1294 case 1:
1295 return Key::SHIFT;
1296 case 2:
1297 return Key::ALT;
1298 case 3:
1299 return Key::META;
1300 case 4:
1301 return Key::CTRL;
1302 }
1303 return Key::NONE;
1304 }
1305
1306 static Key _get_key_modifier(Ref<InputEventWithModifiers> e) {
1307 if (e->is_shift_pressed()) {
1308 return Key::SHIFT;
1309 }
1310 if (e->is_alt_pressed()) {
1311 return Key::ALT;
1312 }
1313 if (e->is_ctrl_pressed()) {
1314 return Key::CTRL;
1315 }
1316 if (e->is_meta_pressed()) {
1317 return Key::META;
1318 }
1319 return Key::NONE;
1320 }
1321
1322 bool Node3DEditorViewport::_transform_gizmo_select(const Vector2 &p_screenpos, bool p_highlight_only) {
1323 if (!spatial_editor->is_gizmo_visible()) {
1324 return false;
1325 }
1326 if (get_selected_count() == 0) {
1327 if (p_highlight_only) {
1328 spatial_editor->select_gizmo_highlight_axis(-1);
1329 }
1330 return false;
1331 }
1332
1333 Vector3 ray_pos = get_ray_pos(p_screenpos);
1334 Vector3 ray = get_ray(p_screenpos);
1335
1336 Transform3D gt = spatial_editor->get_gizmo_transform();
1337
1338 if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_TRANSFORM || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE) {
1339 int col_axis = -1;
1340 real_t col_d = 1e20;
1341
1342 for (int i = 0; i < 3; i++) {
1343 const Vector3 grabber_pos = gt.origin + gt.basis.get_column(i).normalized() * gizmo_scale * (GIZMO_ARROW_OFFSET + (GIZMO_ARROW_SIZE * 0.5));
1344 const real_t grabber_radius = gizmo_scale * GIZMO_ARROW_SIZE;
1345
1346 Vector3 r;
1347
1348 if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
1349 const real_t d = r.distance_to(ray_pos);
1350 if (d < col_d) {
1351 col_d = d;
1352 col_axis = i;
1353 }
1354 }
1355 }
1356
1357 bool is_plane_translate = false;
1358 // plane select
1359 if (col_axis == -1) {
1360 col_d = 1e20;
1361
1362 for (int i = 0; i < 3; i++) {
1363 Vector3 ivec2 = gt.basis.get_column((i + 1) % 3).normalized();
1364 Vector3 ivec3 = gt.basis.get_column((i + 2) % 3).normalized();
1365
1366 // Allow some tolerance to make the plane easier to click,
1367 // even if the click is actually slightly outside the plane.
1368 const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gizmo_scale * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
1369
1370 Vector3 r;
1371 Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
1372
1373 if (plane.intersects_ray(ray_pos, ray, &r)) {
1374 const real_t dist = r.distance_to(grabber_pos);
1375 // Allow some tolerance to make the plane easier to click,
1376 // even if the click is actually slightly outside the plane.
1377 if (dist < (gizmo_scale * GIZMO_PLANE_SIZE * 1.5)) {
1378 const real_t d = ray_pos.distance_to(r);
1379 if (d < col_d) {
1380 col_d = d;
1381 col_axis = i;
1382
1383 is_plane_translate = true;
1384 }
1385 }
1386 }
1387 }
1388 }
1389
1390 if (col_axis != -1) {
1391 if (p_highlight_only) {
1392 spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_translate ? 6 : 0));
1393
1394 } else {
1395 //handle plane translate
1396 _edit.mode = TRANSFORM_TRANSLATE;
1397 _compute_edit(p_screenpos);
1398 _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_translate ? 3 : 0));
1399 }
1400 return true;
1401 }
1402 }
1403
1404 if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_TRANSFORM || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE) {
1405 int col_axis = -1;
1406 bool view_rotation_selected = false;
1407
1408 Vector3 hit_position;
1409 Vector3 hit_normal;
1410 real_t ray_length = gt.origin.distance_to(ray_pos) + (GIZMO_CIRCLE_SIZE * gizmo_scale) * 4.0f;
1411 if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * ray_length, gt.origin, gizmo_scale * (GIZMO_CIRCLE_SIZE), &hit_position, &hit_normal)) {
1412 if (hit_normal.dot(_get_camera_normal()) < 0.05) {
1413 hit_position = gt.xform_inv(hit_position).abs();
1414 int min_axis = hit_position.min_axis_index();
1415 if (hit_position[min_axis] < gizmo_scale * GIZMO_RING_HALF_WIDTH) {
1416 col_axis = min_axis;
1417 }
1418 }
1419 }
1420
1421 if (col_axis == -1) {
1422 float col_d = 1e20;
1423
1424 for (int i = 0; i < 3; i++) {
1425 Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
1426 Vector3 r;
1427 if (!plane.intersects_ray(ray_pos, ray, &r)) {
1428 continue;
1429 }
1430
1431 const real_t dist = r.distance_to(gt.origin);
1432 const Vector3 r_dir = (r - gt.origin).normalized();
1433
1434 if (_get_camera_normal().dot(r_dir) <= 0.005) {
1435 if (dist > gizmo_scale * (GIZMO_CIRCLE_SIZE - GIZMO_RING_HALF_WIDTH) && dist < gizmo_scale * (GIZMO_CIRCLE_SIZE + GIZMO_RING_HALF_WIDTH)) {
1436 const real_t d = ray_pos.distance_to(r);
1437 if (d < col_d) {
1438 col_d = d;
1439 col_axis = i;
1440 }
1441 }
1442 }
1443 }
1444 }
1445
1446 if (col_axis == -1) {
1447 Vector3 ray_to_center = gt.origin - ray_pos;
1448 real_t ray_length_to_center = ray_to_center.dot(ray);
1449 Vector3 closest_point_on_ray = ray_pos + ray * ray_length_to_center;
1450 real_t distance_ray_to_center = closest_point_on_ray.distance_to(gt.origin);
1451
1452 real_t view_rotation_radius = gizmo_scale * GIZMO_VIEW_ROTATION_SIZE;
1453 real_t circumference_tolerance = gizmo_scale * GIZMO_RING_HALF_WIDTH;
1454
1455 if (Math::abs(distance_ray_to_center - view_rotation_radius) < circumference_tolerance &&
1456 ray_length_to_center > 0) {
1457 view_rotation_selected = true;
1458 }
1459 }
1460
1461 if (view_rotation_selected) {
1462 if (p_highlight_only) {
1463 spatial_editor->select_gizmo_highlight_axis(15);
1464 } else {
1465 _edit.mode = TRANSFORM_ROTATE;
1466 _compute_edit(p_screenpos);
1467 _edit.plane = TRANSFORM_VIEW;
1468 _edit.accumulated_rotation_angle = 0.0;
1469 _edit.rotation_axis = _get_camera_normal();
1470 _edit.view_axis_local = spatial_editor->get_gizmo_transform().basis.xform_inv(_get_camera_normal()).normalized();
1471 _edit.gizmo_initiated = true;
1472 }
1473 return true;
1474 } else if (col_axis != -1) {
1475 if (p_highlight_only) {
1476 spatial_editor->select_gizmo_highlight_axis(col_axis + 3);
1477 } else {
1478 //handle axis-specific rotate
1479 _edit.mode = TRANSFORM_ROTATE;
1480 _compute_edit(p_screenpos);
1481 _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis);
1482 _edit.accumulated_rotation_angle = 0.0;
1483 _edit.rotation_axis = gt.basis.get_column(col_axis).normalized();
1484 _edit.gizmo_initiated = true;
1485 }
1486 return true;
1487 }
1488 }
1489
1490 if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE) {
1491 int col_axis = -1;
1492 float col_d = 1e20;
1493
1494 for (int i = 0; i < 3; i++) {
1495 const Vector3 grabber_pos = gt.origin + gt.basis.get_column(i).normalized() * gizmo_scale * GIZMO_SCALE_OFFSET;
1496 const real_t grabber_radius = gizmo_scale * GIZMO_ARROW_SIZE;
1497
1498 Vector3 r;
1499
1500 if (Geometry3D::segment_intersects_sphere(ray_pos, ray_pos + ray * MAX_Z, grabber_pos, grabber_radius, &r)) {
1501 const real_t d = r.distance_to(ray_pos);
1502 if (d < col_d) {
1503 col_d = d;
1504 col_axis = i;
1505 }
1506 }
1507 }
1508
1509 bool is_plane_scale = false;
1510 // plane select
1511 if (col_axis == -1) {
1512 col_d = 1e20;
1513
1514 for (int i = 0; i < 3; i++) {
1515 const Vector3 ivec2 = gt.basis.get_column((i + 1) % 3).normalized();
1516 const Vector3 ivec3 = gt.basis.get_column((i + 2) % 3).normalized();
1517
1518 // Allow some tolerance to make the plane easier to click,
1519 // even if the click is actually slightly outside the plane.
1520 const Vector3 grabber_pos = gt.origin + (ivec2 + ivec3) * gizmo_scale * (GIZMO_PLANE_SIZE + GIZMO_PLANE_DST * 0.6667);
1521
1522 Vector3 r;
1523 Plane plane(gt.basis.get_column(i).normalized(), gt.origin);
1524
1525 if (plane.intersects_ray(ray_pos, ray, &r)) {
1526 const real_t dist = r.distance_to(grabber_pos);
1527 // Allow some tolerance to make the plane easier to click,
1528 // even if the click is actually slightly outside the plane.
1529 if (dist < (gizmo_scale * GIZMO_PLANE_SIZE * 1.5)) {
1530 const real_t d = ray_pos.distance_to(r);
1531 if (d < col_d) {
1532 col_d = d;
1533 col_axis = i;
1534
1535 is_plane_scale = true;
1536 }
1537 }
1538 }
1539 }
1540 }
1541
1542 if (col_axis != -1) {
1543 if (p_highlight_only) {
1544 spatial_editor->select_gizmo_highlight_axis(col_axis + (is_plane_scale ? 12 : 9));
1545
1546 } else {
1547 //handle scale
1548 _edit.mode = TRANSFORM_SCALE;
1549 _compute_edit(p_screenpos);
1550 _edit.plane = TransformPlane(TRANSFORM_X_AXIS + col_axis + (is_plane_scale ? 3 : 0));
1551 }
1552 return true;
1553 }
1554 }
1555
1556 if (p_highlight_only) {
1557 spatial_editor->select_gizmo_highlight_axis(-1);
1558 }
1559
1560 return false;
1561 }
1562
1563 void Node3DEditorViewport::_transform_gizmo_apply(Node3D *p_node, const Transform3D &p_transform, bool p_local) {
1564 if (p_transform.basis.determinant() == 0) {
1565 return;
1566 }
1567
1568 if (p_local) {
1569 p_node->set_transform(p_transform);
1570 } else {
1571 p_node->set_global_transform(p_transform);
1572 }
1573 }
1574
1575 Transform3D Node3DEditorViewport::_compute_transform(TransformMode p_mode, const Transform3D &p_original, const Transform3D &p_original_local, Vector3 p_motion, double p_extra, bool p_local, bool p_orthogonal, bool p_view_axis) {
1576 switch (p_mode) {
1577 case TRANSFORM_SCALE: {
1578 if (_edit.snap || spatial_editor->is_snap_enabled()) {
1579 p_motion.snapf(p_extra);
1580 }
1581 Transform3D s;
1582 if (p_local) {
1583 s.basis = p_original_local.basis.scaled_local(p_motion + Vector3(1, 1, 1));
1584 s.origin = p_original_local.origin;
1585 } else {
1586 s.basis.scale(p_motion + Vector3(1, 1, 1));
1587 Transform3D base = Transform3D(Basis(), _edit.center);
1588 s = base * (s * (base.inverse() * p_original));
1589
1590 // Recalculate orthogonalized scale without moving origin.
1591 if (p_orthogonal) {
1592 s.basis = p_original.basis.scaled_orthogonal(p_motion + Vector3(1, 1, 1));
1593 }
1594 }
1595
1596 return s;
1597 }
1598 case TRANSFORM_TRANSLATE: {
1599 if (_edit.snap || spatial_editor->is_snap_enabled()) {
1600 p_motion.snapf(p_extra);
1601 }
1602
1603 if (p_local) {
1604 return p_original_local.translated_local(p_motion);
1605 }
1606
1607 return p_original.translated(p_motion);
1608 }
1609 case TRANSFORM_ROTATE: {
1610 Transform3D r;
1611
1612 Basis parent_global_basis = p_original.basis * p_original_local.basis.inverse();
1613
1614 Vector3 axis;
1615 if (p_local && !p_view_axis) {
1616 axis = p_original_local.basis.xform(p_motion);
1617 } else {
1618 axis = parent_global_basis.xform_inv(p_motion);
1619 }
1620
1621 if (p_local) {
1622 r.basis = Basis(axis.normalized(), p_extra) * p_original_local.basis;
1623 r.origin = p_original_local.origin;
1624 } else {
1625 r.basis = parent_global_basis * Basis(axis.normalized(), p_extra) * p_original_local.basis;
1626 r.origin = Basis(p_motion, p_extra).xform(p_original.origin - _edit.center) + _edit.center;
1627 }
1628
1629 return r;
1630 }
1631 default: {
1632 ERR_FAIL_V_MSG(Transform3D(), "Invalid mode in '_compute_transform'");
1633 }
1634 }
1635 }
1636
1637 void Node3DEditorViewport::_reset_transform(TransformType p_type) {
1638 List<Node *> selection = editor_selection->get_full_selected_node_list();
1639 if (selection.is_empty()) {
1640 return;
1641 }
1642 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
1643 undo_redo->create_action(TTR("Reset Transform"));
1644 for (Node *node : selection) {
1645 Node3D *sp = Object::cast_to<Node3D>(node);
1646 if (!sp) {
1647 continue;
1648 }
1649
1650 switch (p_type) {
1651 case TransformType::POSITION:
1652 undo_redo->add_undo_method(sp, "set_position", sp->get_position());
1653 undo_redo->add_do_method(sp, "set_position", Vector3());
1654 break;
1655 case TransformType::ROTATION:
1656 undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
1657 undo_redo->add_do_method(sp, "set_rotation", Vector3());
1658 break;
1659 case TransformType::SCALE:
1660 undo_redo->add_undo_method(sp, "set_scale", sp->get_scale());
1661 undo_redo->add_do_method(sp, "set_scale", Vector3(1, 1, 1));
1662 break;
1663 }
1664 }
1665 undo_redo->commit_action();
1666 }
1667
1668 void Node3DEditorViewport::_surface_mouse_enter() {
1669 if (Input::get_singleton()->get_mouse_mode() == Input::MOUSE_MODE_CAPTURED) {
1670 return;
1671 }
1672
1673 if (!surface->has_focus() && (!get_viewport()->gui_get_focus_owner() || !get_viewport()->gui_get_focus_owner()->is_text_field())) {
1674 surface->grab_focus();
1675 }
1676 }
1677
1678 void Node3DEditorViewport::_surface_mouse_exit() {
1679 _remove_preview_node();
1680 _reset_preview_material();
1681 _remove_preview_material();
1682 }
1683
1684 void Node3DEditorViewport::_surface_focus_enter() {
1685 view_display_menu->set_disable_shortcuts(false);
1686 }
1687
1688 void Node3DEditorViewport::_surface_focus_exit() {
1689 view_display_menu->set_disable_shortcuts(true);
1690 }
1691
1692 bool Node3DEditorViewport::_is_node_locked(const Node *p_node) const {
1693 return p_node->get_meta("_edit_lock_", false);
1694 }
1695
1696 void Node3DEditorViewport::_list_select(Ref<InputEventMouseButton> b) {
1697 Vector<_RayResult> potential_selection_results;
1698 _find_items_at_pos(b->get_position(), potential_selection_results, b->is_alt_pressed());
1699
1700 Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
1701
1702 // Filter to a list of nodes which include either the edited scene or nodes directly owned by the edited scene.
1703 // If a node has an invalid owner, recursively check their parents until a valid node is found.
1704 for (int i = 0; i < potential_selection_results.size(); i++) {
1705 Node3D *node = potential_selection_results[i].item;
1706 while (true) {
1707 if (node == nullptr || node == edited_scene->get_parent()) {
1708 break;
1709 } else {
1710 Node *node_owner = node->get_owner();
1711 if (node == edited_scene || node_owner == edited_scene || (node_owner != nullptr && edited_scene->is_editable_instance(node_owner))) {
1712 if (!selection_results.has(node)) {
1713 selection_results.append(node);
1714 }
1715 break;
1716 }
1717 }
1718 node = Object::cast_to<Node3D>(node->get_parent());
1719 }
1720 }
1721
1722 clicked_wants_append = b->is_shift_pressed();
1723
1724 if (selection_results.size() == 1) {
1725 clicked = selection_results[0]->get_instance_id();
1726 selection_results.clear();
1727
1728 if (clicked.is_valid()) {
1729 _select_clicked(b->is_alt_pressed());
1730 }
1731 } else if (!selection_results.is_empty()) {
1732 NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
1733 StringName root_name = root_path.get_name(root_path.get_name_count() - 1);
1734
1735 for (int i = 0; i < selection_results.size(); i++) {
1736 Node3D *spat = selection_results[i];
1737
1738 Ref<Texture2D> icon = EditorNode::get_singleton()->get_object_icon(spat);
1739
1740 String node_path = "/" + root_name + "/" + String(root_path.rel_path_to(spat->get_path()));
1741
1742 int locked = 0;
1743 if (_is_node_locked(spat)) {
1744 locked = 1;
1745 } else {
1746 Node *ed_scene = EditorNode::get_singleton()->get_edited_scene();
1747 Node *node = spat;
1748
1749 while (node && node != ed_scene->get_parent()) {
1750 Node3D *selected_tmp = Object::cast_to<Node3D>(node);
1751 if (selected_tmp && node->has_meta("_edit_group_")) {
1752 locked = 2;
1753 }
1754 node = node->get_parent();
1755 }
1756 }
1757
1758 String suffix;
1759 if (locked == 1) {
1760 suffix = " (" + TTR("Locked") + ")";
1761 } else if (locked == 2) {
1762 suffix = " (" + TTR("Grouped") + ")";
1763 }
1764 selection_menu->add_item((String)spat->get_name() + suffix);
1765 selection_menu->set_item_icon(i, icon);
1766 selection_menu->set_item_metadata(i, node_path);
1767 selection_menu->set_item_tooltip(i, String(spat->get_name()) + "\nType: " + spat->get_class() + "\nPath: " + node_path);
1768 }
1769
1770 selection_results_menu = selection_results;
1771 selection_menu->set_position(get_screen_position() + b->get_position());
1772 selection_menu->reset_size();
1773 selection_menu->popup();
1774 }
1775 }
1776
1777 // Helper function to redirect mouse events to the active freelook viewport
1778 static bool _redirect_freelook_input(const Ref<InputEvent> &p_event, Node3DEditorViewport *p_exclude_viewport = nullptr) {
1779 if (Input::get_singleton()->get_mouse_mode() != Input::MOUSE_MODE_CAPTURED) {
1780 return false;
1781 }
1782
1783 Node3DEditor *editor = Node3DEditor::get_singleton();
1784 if (!editor->get_freelook_viewport()) {
1785 return false;
1786 }
1787
1788 Node3DEditorViewport *freelook_vp = editor->get_freelook_viewport();
1789 if (freelook_vp == p_exclude_viewport) {
1790 return false;
1791 }
1792
1793 Ref<InputEventMouse> mouse_event = p_event;
1794 if (!mouse_event.is_valid()) {
1795 return false;
1796 }
1797
1798 Control *target_surface = freelook_vp->get_surface();
1799
1800 target_surface->emit_signal(SceneStringName(gui_input), p_event);
1801 return true;
1802 }
1803
1804 // This is only active during instant transforms,
1805 // to capture and wrap mouse events outside the control.
1806 void Node3DEditorViewport::input(const Ref<InputEvent> &p_event) {
1807 ERR_FAIL_COND(!_edit.instant);
1808 Ref<InputEventMouseMotion> m = p_event;
1809
1810 if (m.is_valid()) {
1811 _edit.mouse_pos += _get_warped_mouse_motion(p_event);
1812 update_transform(_get_key_modifier(m) == Key::SHIFT);
1813 }
1814 }
1815
1816 void Node3DEditorViewport::_sinput(const Ref<InputEvent> &p_event) {
1817 const Ref<InputEventKey> k = p_event;
1818
1819 if (k.is_valid() && k->is_pressed() && EDITOR_GET("editors/3d/navigation/emulate_numpad")) {
1820 const Key code = k->get_physical_keycode();
1821 if (code >= Key::KEY_0 && code <= Key::KEY_9) {
1822 k->set_keycode(code - Key::KEY_0 + Key::KP_0);
1823 }
1824 }
1825
1826 if (previewing || get_viewport()->gui_get_drag_data()) {
1827 // Disable all input actions when previewing a camera or during drag-and-drop.
1828 return;
1829 }
1830
1831 if (_redirect_freelook_input(p_event, this)) {
1832 return;
1833 }
1834
1835 EditorPlugin::AfterGUIInput after = EditorPlugin::AFTER_GUI_INPUT_PASS;
1836 {
1837 EditorNode *en = EditorNode::get_singleton();
1838
1839 switch (en->get_editor_plugins_force_input_forwarding()->forward_3d_gui_input(camera, p_event, true)) {
1840 case EditorPlugin::AFTER_GUI_INPUT_PASS: {
1841 // Continue processing.
1842 } break;
1843
1844 case EditorPlugin::AFTER_GUI_INPUT_STOP: {
1845 return; // Stop processing.
1846 } break;
1847
1848 case EditorPlugin::AFTER_GUI_INPUT_CUSTOM: {
1849 after = EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
1850 } break;
1851 }
1852
1853 switch (en->get_editor_plugins_over()->forward_3d_gui_input(camera, p_event, false)) {
1854 case EditorPlugin::AFTER_GUI_INPUT_PASS: {
1855 // Continue processing.
1856 } break;
1857
1858 case EditorPlugin::AFTER_GUI_INPUT_STOP: {
1859 return; // Stop processing.
1860 } break;
1861
1862 case EditorPlugin::AFTER_GUI_INPUT_CUSTOM: {
1863 after = EditorPlugin::AFTER_GUI_INPUT_CUSTOM;
1864 } break;
1865 }
1866 }
1867
1868 Ref<InputEventMouseButton> b = p_event;
1869
1870 if (b.is_valid()) {
1871 emit_signal(SNAME("clicked"));
1872
1873 ViewportNavMouseButton orbit_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/orbit_mouse_button").operator int();
1874 ViewportNavMouseButton pan_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/pan_mouse_button").operator int();
1875 ViewportNavMouseButton zoom_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/zoom_mouse_button").operator int();
1876
1877 const real_t zoom_factor = 1 + (ZOOM_FREELOOK_MULTIPLIER - 1) * b->get_factor();
1878 switch (b->get_button_index()) {
1879 case MouseButton::WHEEL_UP: {
1880 if (is_freelook_active()) {
1881 scale_freelook_speed(zoom_factor);
1882 } else {
1883 scale_cursor_distance(1.0 / zoom_factor);
1884 }
1885 } break;
1886 case MouseButton::WHEEL_DOWN: {
1887 if (is_freelook_active()) {
1888 scale_freelook_speed(1.0 / zoom_factor);
1889 } else {
1890 scale_cursor_distance(zoom_factor);
1891 }
1892 } break;
1893 case MouseButton::RIGHT: {
1894 if (b->is_pressed()) {
1895 if (_edit.gizmo.is_valid()) {
1896 // Restore.
1897 _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, true);
1898 _edit.gizmo = Ref<EditorNode3DGizmo>();
1899 }
1900
1901 if (_edit.mode == TRANSFORM_NONE) {
1902 if (orbit_mouse_preference == NAVIGATION_RIGHT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_2")) {
1903 break;
1904 } else if (pan_mouse_preference == NAVIGATION_RIGHT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_2")) {
1905 break;
1906 } else if (zoom_mouse_preference == NAVIGATION_RIGHT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_2")) {
1907 break;
1908 }
1909 }
1910
1911 if (b->is_alt_pressed()) {
1912 _list_select(b);
1913 return;
1914 }
1915
1916 if (_edit.mode != TRANSFORM_NONE) {
1917 cancel_transform();
1918 break;
1919 }
1920
1921 const Key mod = _get_key_modifier(b);
1922 if (!orthogonal) {
1923 if (mod == _get_key_modifier_setting("editors/3d/freelook/freelook_activation_modifier")) {
1924 set_freelook_active(true);
1925 }
1926 }
1927 } else {
1928 set_freelook_active(false);
1929 }
1930
1931 if (freelook_active && !surface->has_focus()) {
1932 // Focus usually doesn't trigger on right-click, but in case of freelook it should,
1933 // otherwise using keyboard navigation would misbehave
1934 surface->grab_focus();
1935 }
1936
1937 } break;
1938 case MouseButton::MIDDLE: {
1939 if (b->is_pressed() && _edit.mode != TRANSFORM_NONE) {
1940 if (orbit_mouse_preference == NAVIGATION_MIDDLE_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_2")) {
1941 break;
1942 } else if (pan_mouse_preference == NAVIGATION_MIDDLE_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_2")) {
1943 break;
1944 } else if (zoom_mouse_preference == NAVIGATION_MIDDLE_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_2")) {
1945 break;
1946 }
1947
1948 switch (_edit.plane) {
1949 case TRANSFORM_VIEW: {
1950 _edit.plane = TRANSFORM_X_AXIS;
1951 set_message(TTR("X-Axis Transform."), 2);
1952 view_type = VIEW_TYPE_USER;
1953 _update_name();
1954 } break;
1955 case TRANSFORM_X_AXIS: {
1956 _edit.plane = TRANSFORM_Y_AXIS;
1957 set_message(TTR("Y-Axis Transform."), 2);
1958
1959 } break;
1960 case TRANSFORM_Y_AXIS: {
1961 _edit.plane = TRANSFORM_Z_AXIS;
1962 set_message(TTR("Z-Axis Transform."), 2);
1963
1964 } break;
1965 case TRANSFORM_Z_AXIS: {
1966 _edit.plane = TRANSFORM_VIEW;
1967 // TRANSLATORS: This refers to the transform of the view plane.
1968 set_message(TTR("View Plane Transform."), 2);
1969
1970 } break;
1971 case TRANSFORM_YZ:
1972 case TRANSFORM_XZ:
1973 case TRANSFORM_XY: {
1974 } break;
1975 }
1976 }
1977 } break;
1978 case MouseButton::LEFT: {
1979 if (b->is_pressed()) {
1980 clicked_wants_append = b->is_shift_pressed();
1981
1982 if (_edit.mode != TRANSFORM_NONE && (_edit.instant || collision_reposition)) {
1983 commit_transform();
1984 break; // just commit the edit, stop processing the event so we don't deselect the object
1985 }
1986 if (orbit_mouse_preference == NAVIGATION_LEFT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_2")) {
1987 break;
1988 } else if (pan_mouse_preference == NAVIGATION_LEFT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_2")) {
1989 break;
1990 } else if (zoom_mouse_preference == NAVIGATION_LEFT_MOUSE && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_2")) {
1991 break;
1992 }
1993
1994 if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_RULER) {
1995 EditorNode::get_singleton()->get_scene_root()->add_child(ruler);
1996 collision_reposition = true;
1997 break;
1998 }
1999
2000 if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_LIST_SELECT) {
2001 _list_select(b);
2002 break;
2003 }
2004
2005 _edit.mouse_pos = b->get_position();
2006 _edit.original_mouse_pos = b->get_position();
2007 _edit.snap = spatial_editor->is_snap_enabled();
2008 _edit.mode = TRANSFORM_NONE;
2009 _edit.original = spatial_editor->get_gizmo_transform(); // To prevent to break when flipping with scale.
2010
2011 bool can_select_gizmos = spatial_editor->get_single_selected_node();
2012
2013 {
2014 int idx = view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS);
2015 int idx2 = view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO);
2016 can_select_gizmos = can_select_gizmos && view_display_menu->get_popup()->is_item_checked(idx);
2017 transform_gizmo_visible = view_display_menu->get_popup()->is_item_checked(idx2);
2018 }
2019
2020 // Gizmo handles
2021 if (can_select_gizmos) {
2022 Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
2023
2024 bool intersected_handle = false;
2025 for (int i = 0; i < gizmos.size(); i++) {
2026 Ref<EditorNode3DGizmo> seg = gizmos[i];
2027
2028 if (seg.is_null()) {
2029 continue;
2030 }
2031
2032 int gizmo_handle = -1;
2033 bool gizmo_secondary = false;
2034 seg->handles_intersect_ray(camera, _edit.mouse_pos, b->is_shift_pressed(), gizmo_handle, gizmo_secondary);
2035 if (gizmo_handle != -1) {
2036 _edit.gizmo = seg;
2037 seg->begin_handle_action(gizmo_handle, gizmo_secondary);
2038 _edit.gizmo_handle = gizmo_handle;
2039 _edit.gizmo_handle_secondary = gizmo_secondary;
2040 _edit.gizmo_initial_value = seg->get_handle_value(gizmo_handle, gizmo_secondary);
2041 intersected_handle = true;
2042 break;
2043 }
2044 }
2045
2046 if (intersected_handle) {
2047 break;
2048 }
2049 }
2050
2051 // Transform gizmo
2052 if (transform_gizmo_visible && _transform_gizmo_select(_edit.mouse_pos)) {
2053 break;
2054 }
2055
2056 // Subgizmos
2057 if (can_select_gizmos) {
2058 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(spatial_editor->get_single_selected_node());
2059 Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
2060
2061 bool intersected_subgizmo = false;
2062 for (int i = 0; i < gizmos.size(); i++) {
2063 Ref<EditorNode3DGizmo> seg = gizmos[i];
2064
2065 if (seg.is_null()) {
2066 continue;
2067 }
2068
2069 int subgizmo_id = seg->subgizmos_intersect_ray(camera, _edit.mouse_pos);
2070 if (subgizmo_id != -1) {
2071 ERR_CONTINUE(!se);
2072 if (b->is_shift_pressed()) {
2073 if (se->subgizmos.has(subgizmo_id)) {
2074 se->subgizmos.erase(subgizmo_id);
2075 } else {
2076 se->subgizmos.insert(subgizmo_id, seg->get_subgizmo_transform(subgizmo_id));
2077 }
2078 } else {
2079 se->subgizmos.clear();
2080 se->subgizmos.insert(subgizmo_id, seg->get_subgizmo_transform(subgizmo_id));
2081 }
2082
2083 if (se->subgizmos.is_empty()) {
2084 se->gizmo = Ref<EditorNode3DGizmo>();
2085 } else {
2086 se->gizmo = seg;
2087 }
2088
2089 seg->redraw();
2090 spatial_editor->update_transform_gizmo();
2091 intersected_subgizmo = true;
2092 break;
2093 }
2094 }
2095
2096 if (intersected_subgizmo) {
2097 break;
2098 }
2099 }
2100
2101 clicked = ObjectID();
2102
2103 bool node_selected = get_selected_count() > 0;
2104
2105 if (after != EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
2106 // Single item selection.
2107 clicked = _select_ray(b->get_position());
2108
2109 if (clicked.is_valid() && !editor_selection->is_selected(ObjectDB::get_instance<Node>(clicked))) {
2110 if (!node_selected || (!b->is_alt_pressed() && !(spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_TRANSFORM && b->is_command_or_control_pressed()))) {
2111 selection_in_progress = true;
2112 break;
2113 }
2114 }
2115
2116 if (clicked.is_null()) {
2117 if (node_selected) {
2118 TransformMode mode = TRANSFORM_NONE;
2119
2120 if (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_TRANSFORM) {
2121 if (b->is_command_or_control_pressed()) {
2122 mode = TRANSFORM_ROTATE;
2123 } else if (b->is_alt_pressed()) {
2124 mode = TRANSFORM_TRANSLATE;
2125 }
2126 } else if (b->is_alt_pressed()) {
2127 switch (spatial_editor->get_tool_mode()) {
2128 case Node3DEditor::TOOL_MODE_ROTATE:
2129 mode = TRANSFORM_ROTATE;
2130 break;
2131 case Node3DEditor::TOOL_MODE_MOVE:
2132 mode = TRANSFORM_TRANSLATE;
2133 break;
2134 case Node3DEditor::TOOL_MODE_SCALE:
2135 mode = TRANSFORM_SCALE;
2136 break;
2137 default:
2138 break;
2139 }
2140 }
2141
2142 if (mode != TRANSFORM_NONE) {
2143 begin_transform(mode, false);
2144 break;
2145 }
2146 }
2147
2148 // Default to region select.
2149 cursor.region_select = true;
2150 cursor.region_begin = b->get_position();
2151 cursor.region_end = b->get_position();
2152 break;
2153 }
2154 }
2155
2156 if (clicked.is_valid() && !clicked_wants_append) {
2157 bool is_clicked_node_selected = editor_selection->is_selected(ObjectDB::get_instance<Node>(clicked));
2158 TransformMode mode = TRANSFORM_NONE;
2159
2160 switch (spatial_editor->get_tool_mode()) {
2161 case Node3DEditor::TOOL_MODE_TRANSFORM:
2162 if (b->is_command_or_control_pressed() && node_selected) {
2163 mode = TRANSFORM_ROTATE;
2164 } else if (b->is_alt_pressed() && node_selected) {
2165 mode = TRANSFORM_TRANSLATE;
2166 } else if (is_clicked_node_selected) {
2167 mode = TRANSFORM_TRANSLATE;
2168 }
2169 break;
2170 case Node3DEditor::TOOL_MODE_ROTATE:
2171 if (is_clicked_node_selected || (b->is_alt_pressed() && node_selected)) {
2172 mode = TRANSFORM_ROTATE;
2173 }
2174 break;
2175 case Node3DEditor::TOOL_MODE_MOVE:
2176 if (is_clicked_node_selected || (b->is_alt_pressed() && node_selected)) {
2177 mode = TRANSFORM_TRANSLATE;
2178 }
2179 break;
2180 case Node3DEditor::TOOL_MODE_SCALE:
2181 if (is_clicked_node_selected || (b->is_alt_pressed() && node_selected)) {
2182 mode = TRANSFORM_SCALE;
2183 }
2184 break;
2185 default:
2186 break;
2187 }
2188
2189 if (mode != TRANSFORM_NONE) {
2190 begin_transform(mode, false);
2191 break;
2192 }
2193 }
2194
2195 surface->queue_redraw();
2196 } else {
2197 if (ruler->is_inside_tree()) {
2198 EditorNode::get_singleton()->get_scene_root()->remove_child(ruler);
2199 ruler_start_point->set_visible(false);
2200 ruler_end_point->set_visible(false);
2201 ruler_label->set_visible(false);
2202 collision_reposition = false;
2203 break;
2204 }
2205
2206 if (_edit.gizmo.is_valid()) {
2207 // Certain gizmo plugins should be able to commit handles without dragging them.
2208 if (_edit.original_mouse_pos != _edit.mouse_pos || _edit.gizmo->get_plugin()->can_commit_handle_on_click()) {
2209 _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, false);
2210 }
2211 Node3D *selected_node = spatial_editor->get_single_selected_node();
2212 if (selected_node) {
2213 selected_node->update_gizmos();
2214 }
2215 _edit.gizmo = Ref<EditorNode3DGizmo>();
2216 break;
2217 }
2218
2219 if (after != EditorPlugin::AFTER_GUI_INPUT_CUSTOM) {
2220 selection_in_progress = false;
2221
2222 if (clicked.is_valid() && _edit.mode == TRANSFORM_NONE) {
2223 _select_clicked(false);
2224 } else if (cursor.region_select) {
2225 _select_region();
2226 surface->queue_redraw();
2227 }
2228
2229 movement_threshold_passed = false;
2230 cursor.region_select = false;
2231 }
2232
2233 if (!_edit.instant && _edit.mode != TRANSFORM_NONE) {
2234 Node3D *selected = spatial_editor->get_single_selected_node();
2235 Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
2236
2237 if (se && se->gizmo.is_valid()) {
2238 Vector<int> ids;
2239 Vector<Transform3D> restore;
2240
2241 for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
2242 ids.push_back(GE.key);
2243 restore.push_back(GE.value);
2244 }
2245
2246 se->gizmo->commit_subgizmos(ids, restore, false);
2247 } else {
2248 if (_edit.original_mouse_pos != _edit.mouse_pos) {
2249 commit_transform();
2250 }
2251 }
2252 _edit.mode = TRANSFORM_NONE;
2253 set_message("");
2254 spatial_editor->update_transform_gizmo();
2255 }
2256 }
2257
2258 } break;
2259 default:
2260 break;
2261 }
2262 }
2263
2264 Vector<ShortcutCheckSet> shortcut_check_sets;
2265
2266 if (Input::get_singleton()->get_mouse_mode() != Input::MOUSE_MODE_CAPTURED) {
2267 ViewportNavMouseButton orbit_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/orbit_mouse_button").operator int();
2268 ViewportNavMouseButton pan_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/pan_mouse_button").operator int();
2269 ViewportNavMouseButton zoom_mouse_preference = (ViewportNavMouseButton)EDITOR_GET("editors/3d/navigation/zoom_mouse_button").operator int();
2270 bool orbit_mod_pressed = _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_modifier_2");
2271 bool pan_mod_pressed = _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_pan_modifier_2");
2272 bool zoom_mod_pressed = _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_zoom_modifier_2");
2273 int orbit_mod_input_count = _get_shortcut_input_count("spatial_editor/viewport_orbit_modifier_1") + _get_shortcut_input_count("spatial_editor/viewport_orbit_modifier_2");
2274 int pan_mod_input_count = _get_shortcut_input_count("spatial_editor/viewport_pan_modifier_1") + _get_shortcut_input_count("spatial_editor/viewport_pan_modifier_2");
2275 int zoom_mod_input_count = _get_shortcut_input_count("spatial_editor/viewport_zoom_modifier_1") + _get_shortcut_input_count("spatial_editor/viewport_zoom_modifier_2");
2276 bool orbit_not_empty = !_is_shortcut_empty("spatial_editor/viewport_orbit_modifier_1") || !_is_shortcut_empty("spatial_editor/viewport_orbit_modifier_2");
2277 bool pan_not_empty = !_is_shortcut_empty("spatial_editor/viewport_pan_modifier_1") || !_is_shortcut_empty("spatial_editor/viewport_pan_modifier_2");
2278 bool zoom_not_empty = !_is_shortcut_empty("spatial_editor/viewport_zoom_modifier_1") || !_is_shortcut_empty("spatial_editor/viewport_zoom_modifier_2");
2279 shortcut_check_sets.push_back(ShortcutCheckSet(orbit_mod_pressed, orbit_not_empty, orbit_mod_input_count, orbit_mouse_preference, NAVIGATION_ORBIT));
2280 shortcut_check_sets.push_back(ShortcutCheckSet(pan_mod_pressed, pan_not_empty, pan_mod_input_count, pan_mouse_preference, NAVIGATION_PAN));
2281 shortcut_check_sets.push_back(ShortcutCheckSet(zoom_mod_pressed, zoom_not_empty, zoom_mod_input_count, zoom_mouse_preference, NAVIGATION_ZOOM));
2282 shortcut_check_sets.sort_custom<ShortcutCheckSetComparator>();
2283 }
2284
2285 Ref<InputEventMouseMotion> m = p_event;
2286
2287 // Instant transforms process mouse motion in input() to handle wrapping.
2288 if (m.is_valid() && !_edit.instant) {
2289 _edit.mouse_pos = m->get_position();
2290
2291 if (spatial_editor->get_single_selected_node()) {
2292 Vector<Ref<Node3DGizmo>> gizmos = spatial_editor->get_single_selected_node()->get_gizmos();
2293
2294 Ref<EditorNode3DGizmo> found_gizmo;
2295 int found_handle = -1;
2296 bool found_handle_secondary = false;
2297
2298 for (int i = 0; i < gizmos.size(); i++) {
2299 Ref<EditorNode3DGizmo> seg = gizmos[i];
2300 if (seg.is_null()) {
2301 continue;
2302 }
2303
2304 seg->handles_intersect_ray(camera, _edit.mouse_pos, false, found_handle, found_handle_secondary);
2305
2306 if (found_handle != -1) {
2307 found_gizmo = seg;
2308 break;
2309 }
2310 }
2311
2312 if (found_gizmo.is_valid()) {
2313 spatial_editor->select_gizmo_highlight_axis(-1);
2314 }
2315
2316 bool current_hover_handle_secondary = false;
2317 int current_hover_handle = spatial_editor->get_current_hover_gizmo_handle(current_hover_handle_secondary);
2318 if (found_gizmo != spatial_editor->get_current_hover_gizmo() || found_handle != current_hover_handle || found_handle_secondary != current_hover_handle_secondary) {
2319 spatial_editor->set_current_hover_gizmo(found_gizmo);
2320 spatial_editor->set_current_hover_gizmo_handle(found_handle, found_handle_secondary);
2321 spatial_editor->get_single_selected_node()->update_gizmos();
2322 }
2323 }
2324
2325 if (transform_gizmo_visible && spatial_editor->get_current_hover_gizmo().is_null() && !m->get_button_mask().has_flag(MouseButtonMask::LEFT) && _edit.gizmo.is_null()) {
2326 _transform_gizmo_select(_edit.mouse_pos, true);
2327 }
2328
2329 NavigationMode nav_mode = NAVIGATION_NONE;
2330
2331 if (_edit.gizmo.is_valid()) {
2332 _edit.gizmo->set_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, camera, m->get_position());
2333 Variant v = _edit.gizmo->get_handle_value(_edit.gizmo_handle, _edit.gizmo_handle_secondary);
2334 String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle, _edit.gizmo_handle_secondary);
2335 set_message(n + ": " + String(v));
2336
2337 } else if (m->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
2338 NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_LEFT_MOUSE, shortcut_check_sets, false);
2339 if (change_nav_from_shortcut != NAVIGATION_NONE) {
2340 nav_mode = change_nav_from_shortcut;
2341 } else {
2342 movement_threshold_passed = _edit.original_mouse_pos.distance_to(_edit.mouse_pos) > 8 * EDSCALE;
2343
2344 if ((selection_in_progress || clicked_wants_append || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SELECT) && movement_threshold_passed && clicked.is_valid()) {
2345 cursor.region_select = true;
2346 cursor.region_begin = _edit.original_mouse_pos;
2347 clicked = ObjectID();
2348 }
2349
2350 if (cursor.region_select) {
2351 cursor.region_end = m->get_position();
2352 surface->queue_redraw();
2353 return;
2354 }
2355
2356 if (clicked.is_valid() && movement_threshold_passed && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_TRANSFORM || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE)) {
2357 bool is_select_mode = (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_TRANSFORM);
2358 bool is_clicked_selected = editor_selection->is_selected(ObjectDB::get_instance<Node>(clicked));
2359
2360 if (_edit.mode == TRANSFORM_NONE && (is_select_mode || is_clicked_selected)) {
2361 _compute_edit(_edit.original_mouse_pos);
2362 clicked = ObjectID();
2363 _edit.mode = TRANSFORM_TRANSLATE;
2364 }
2365 }
2366
2367 if (_edit.mode == TRANSFORM_NONE || _edit.numeric_input != 0 || _edit.numeric_next_decimal != 0) {
2368 return;
2369 }
2370
2371 if (!selection_in_progress) {
2372 update_transform(_get_key_modifier(m) == Key::SHIFT);
2373 }
2374 }
2375 } else if (m->get_button_mask().has_flag(MouseButtonMask::RIGHT) || freelook_active) {
2376 NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_RIGHT_MOUSE, shortcut_check_sets, false);
2377 if (m->get_button_mask().has_flag(MouseButtonMask::RIGHT) && change_nav_from_shortcut != NAVIGATION_NONE) {
2378 nav_mode = change_nav_from_shortcut;
2379 } else if (freelook_active) {
2380 nav_mode = NAVIGATION_LOOK;
2381 } else if (orthogonal) {
2382 nav_mode = NAVIGATION_PAN;
2383 }
2384
2385 } else if (m->get_button_mask().has_flag(MouseButtonMask::MIDDLE)) {
2386 NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_MIDDLE_MOUSE, shortcut_check_sets, false);
2387 if (change_nav_from_shortcut != NAVIGATION_NONE) {
2388 nav_mode = change_nav_from_shortcut;
2389 }
2390
2391 } else if (m->get_button_mask().has_flag(MouseButtonMask::MB_XBUTTON1)) {
2392 NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_MOUSE_4, shortcut_check_sets, false);
2393 if (change_nav_from_shortcut != NAVIGATION_NONE) {
2394 nav_mode = change_nav_from_shortcut;
2395 }
2396
2397 } else if (m->get_button_mask().has_flag(MouseButtonMask::MB_XBUTTON2)) {
2398 NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_MOUSE_5, shortcut_check_sets, false);
2399 if (change_nav_from_shortcut != NAVIGATION_NONE) {
2400 nav_mode = change_nav_from_shortcut;
2401 }
2402
2403 } else if (EDITOR_GET("editors/3d/navigation/emulate_3_button_mouse")) {
2404 // Handle trackpad (no external mouse) use case
2405 NavigationMode change_nav_from_shortcut = _get_nav_mode_from_shortcut_check(NAVIGATION_LEFT_MOUSE, shortcut_check_sets, true);
2406 if (change_nav_from_shortcut != NAVIGATION_NONE) {
2407 nav_mode = change_nav_from_shortcut;
2408 }
2409 }
2410
2411 switch (nav_mode) {
2412 case NAVIGATION_PAN: {
2413 _nav_pan(m, _get_warped_mouse_motion(m));
2414
2415 } break;
2416
2417 case NAVIGATION_ZOOM: {
2418 _nav_zoom(m, m->get_relative());
2419
2420 } break;
2421
2422 case NAVIGATION_ORBIT: {
2423 _nav_orbit(m, _get_warped_mouse_motion(m));
2424
2425 } break;
2426
2427 case NAVIGATION_LOOK: {
2428 _nav_look(m, _get_warped_mouse_motion(m));
2429
2430 } break;
2431
2432 default: {
2433 }
2434 }
2435 }
2436
2437 Ref<InputEventMagnifyGesture> magnify_gesture = p_event;
2438 if (magnify_gesture.is_valid()) {
2439 if (is_freelook_active()) {
2440 scale_freelook_speed(magnify_gesture->get_factor());
2441 } else {
2442 scale_cursor_distance(1.0 / magnify_gesture->get_factor());
2443 }
2444 }
2445
2446 Ref<InputEventPanGesture> pan_gesture = p_event;
2447 if (pan_gesture.is_valid()) {
2448 NavigationMode nav_mode = NAVIGATION_NONE;
2449
2450 for (const ShortcutCheckSet &shortcut_check_set : shortcut_check_sets) {
2451 if (shortcut_check_set.mod_pressed) {
2452 nav_mode = shortcut_check_set.result_nav_mode;
2453 break;
2454 }
2455 }
2456
2457 switch (nav_mode) {
2458 case NAVIGATION_PAN: {
2459 _nav_pan(pan_gesture, -pan_gesture->get_delta());
2460
2461 } break;
2462
2463 case NAVIGATION_ZOOM: {
2464 _nav_zoom(pan_gesture, pan_gesture->get_delta());
2465
2466 } break;
2467
2468 case NAVIGATION_ORBIT: {
2469 _nav_orbit(pan_gesture, -pan_gesture->get_delta());
2470
2471 } break;
2472
2473 case NAVIGATION_LOOK: {
2474 _nav_look(pan_gesture, pan_gesture->get_delta());
2475
2476 } break;
2477
2478 default: {
2479 }
2480 }
2481 }
2482
2483 if (k.is_valid()) {
2484 if (!k->is_pressed()) {
2485 return;
2486 }
2487
2488 if (_edit.instant) {
2489 // In a Blender-style transform, numbers set the magnitude of the transform.
2490 // E.g. pressing g4.5x means "translate 4.5 units along the X axis".
2491 bool processed = true;
2492 Key keycode = k->get_keycode();
2493 Key physical_keycode = k->get_physical_keycode();
2494
2495 // Use physical keycode for main keyboard numbers (for non-QWERTY layouts like AZERTY)
2496 // but regular keycode for numpad numbers.
2497 if ((physical_keycode >= Key::KEY_0 && physical_keycode <= Key::KEY_9) || (keycode >= Key::KP_0 && keycode <= Key::KP_9)) {
2498 uint32_t value;
2499 if (physical_keycode >= Key::KEY_0 && physical_keycode <= Key::KEY_9) {
2500 value = uint32_t(physical_keycode - Key::KEY_0);
2501 } else {
2502 value = uint32_t(keycode - Key::KP_0);
2503 }
2504
2505 if (_edit.numeric_next_decimal < 0) {
2506 _edit.numeric_input = _edit.numeric_input + value * Math::pow(10.0, _edit.numeric_next_decimal--);
2507 } else {
2508 _edit.numeric_input = _edit.numeric_input * 10 + value;
2509 }
2510 update_transform_numeric();
2511 } else if (keycode == Key::MINUS || keycode == Key::KP_SUBTRACT) {
2512 _edit.numeric_negate = !_edit.numeric_negate;
2513 update_transform_numeric();
2514 } else if (keycode == Key::PERIOD || physical_keycode == Key::KP_PERIOD) {
2515 // Use physical keycode for KP_PERIOD to ensure numpad period works consistently
2516 // across different keyboard layouts (like nordic keyboards).
2517 if (_edit.numeric_next_decimal == 0) {
2518 _edit.numeric_next_decimal = -1;
2519 }
2520 } else if (keycode == Key::ENTER || keycode == Key::KP_ENTER || keycode == Key::SPACE) {
2521 commit_transform();
2522 } else {
2523 processed = false;
2524 }
2525
2526 if (processed) {
2527 // Ignore mouse inputs once we receive a numeric input.
2528 set_process_input(false);
2529 accept_event();
2530 return;
2531 }
2532 }
2533
2534 Ref<InputEvent> event_mod = p_event;
2535 if (EDITOR_GET("editors/3d/navigation/emulate_numpad")) {
2536 const Key code = k->get_physical_keycode();
2537 if (code >= Key::KEY_0 && code <= Key::KEY_9) {
2538 event_mod = p_event->duplicate();
2539 Ref<InputEventKey> k_mod = event_mod;
2540 k_mod->set_keycode(code - Key::KEY_0 + Key::KP_0);
2541 }
2542 }
2543
2544 if (_edit.mode == TRANSFORM_NONE) {
2545 if (_edit.gizmo.is_null() && is_freelook_active() && k->get_keycode() == Key::ESCAPE) {
2546 set_freelook_active(false);
2547 return;
2548 }
2549
2550 if (_edit.gizmo.is_valid() && (k->get_keycode() == Key::ESCAPE || k->get_keycode() == Key::BACKSPACE)) {
2551 // Restore.
2552 _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, true);
2553 _edit.gizmo = Ref<EditorNode3DGizmo>();
2554 }
2555 if (k->get_keycode() == Key::ESCAPE && !cursor.region_select && !k->is_echo()) {
2556 _clear_selected();
2557 return;
2558 }
2559 } else {
2560 // We're actively transforming, handle keys specially
2561 TransformPlane new_plane = TRANSFORM_VIEW;
2562 if (ED_IS_SHORTCUT("spatial_editor/lock_transform_x", event_mod)) {
2563 new_plane = TRANSFORM_X_AXIS;
2564 } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_y", event_mod)) {
2565 new_plane = TRANSFORM_Y_AXIS;
2566 } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_z", event_mod)) {
2567 new_plane = TRANSFORM_Z_AXIS;
2568 } else if (_edit.mode != TRANSFORM_ROTATE) { // rotating on a plane doesn't make sense
2569 if (ED_IS_SHORTCUT("spatial_editor/lock_transform_yz", event_mod)) {
2570 new_plane = TRANSFORM_YZ;
2571 } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xz", event_mod)) {
2572 new_plane = TRANSFORM_XZ;
2573 } else if (ED_IS_SHORTCUT("spatial_editor/lock_transform_xy", event_mod)) {
2574 new_plane = TRANSFORM_XY;
2575 }
2576 }
2577
2578 if (new_plane != TRANSFORM_VIEW) {
2579 if (new_plane != _edit.plane) {
2580 // lock me once and get a global constraint
2581 _edit.plane = new_plane;
2582 spatial_editor->set_local_coords_enabled(false);
2583 } else if (!spatial_editor->are_local_coords_enabled()) {
2584 // lock me twice and get a local constraint
2585 spatial_editor->set_local_coords_enabled(true);
2586 } else {
2587 // lock me thrice and we're back where we started
2588 _edit.plane = TRANSFORM_VIEW;
2589 spatial_editor->set_local_coords_enabled(false);
2590 }
2591 if (_edit.numeric_input != 0 || _edit.numeric_next_decimal != 0) {
2592 update_transform_numeric();
2593 } else {
2594 update_transform(Input::get_singleton()->is_key_pressed(Key::SHIFT));
2595 }
2596 accept_event();
2597 return;
2598 }
2599 }
2600 if (ED_IS_SHORTCUT("spatial_editor/snap", event_mod)) {
2601 if (_edit.mode != TRANSFORM_NONE) {
2602 _edit.snap = !_edit.snap;
2603 }
2604 }
2605 if (ED_IS_SHORTCUT("spatial_editor/bottom_view", event_mod)) {
2606 _menu_option(VIEW_BOTTOM);
2607 }
2608 if (ED_IS_SHORTCUT("spatial_editor/top_view", event_mod)) {
2609 _menu_option(VIEW_TOP);
2610 }
2611 if (ED_IS_SHORTCUT("spatial_editor/rear_view", event_mod)) {
2612 _menu_option(VIEW_REAR);
2613 }
2614 if (ED_IS_SHORTCUT("spatial_editor/front_view", event_mod)) {
2615 _menu_option(VIEW_FRONT);
2616 }
2617 if (ED_IS_SHORTCUT("spatial_editor/left_view", event_mod)) {
2618 _menu_option(VIEW_LEFT);
2619 }
2620 if (ED_IS_SHORTCUT("spatial_editor/right_view", event_mod)) {
2621 _menu_option(VIEW_RIGHT);
2622 }
2623 if (ED_IS_SHORTCUT("spatial_editor/orbit_view_down", event_mod)) {
2624 // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
2625 cursor.x_rot = CLAMP(cursor.x_rot - Math::PI / 12.0, -1.57, 1.57);
2626 cursor.unsnapped_x_rot = cursor.x_rot;
2627 view_type = VIEW_TYPE_USER;
2628 _update_name();
2629 }
2630 if (ED_IS_SHORTCUT("spatial_editor/orbit_view_up", event_mod)) {
2631 // Clamp rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
2632 cursor.x_rot = CLAMP(cursor.x_rot + Math::PI / 12.0, -1.57, 1.57);
2633 cursor.unsnapped_x_rot = cursor.x_rot;
2634 view_type = VIEW_TYPE_USER;
2635 _update_name();
2636 }
2637 if (ED_IS_SHORTCUT("spatial_editor/orbit_view_right", event_mod)) {
2638 cursor.y_rot -= Math::PI / 12.0;
2639 cursor.unsnapped_y_rot = cursor.y_rot;
2640 view_type = VIEW_TYPE_USER;
2641 _update_name();
2642 }
2643 if (ED_IS_SHORTCUT("spatial_editor/orbit_view_left", event_mod)) {
2644 cursor.y_rot += Math::PI / 12.0;
2645 cursor.unsnapped_y_rot = cursor.y_rot;
2646 view_type = VIEW_TYPE_USER;
2647 _update_name();
2648 }
2649 if (ED_IS_SHORTCUT("spatial_editor/orbit_view_180", event_mod)) {
2650 cursor.y_rot += Math::PI;
2651 cursor.unsnapped_y_rot = cursor.y_rot;
2652 view_type = VIEW_TYPE_USER;
2653 _update_name();
2654 }
2655 if (ED_IS_SHORTCUT("spatial_editor/focus_origin", event_mod)) {
2656 _menu_option(VIEW_CENTER_TO_ORIGIN);
2657 }
2658 if (ED_IS_SHORTCUT("spatial_editor/focus_selection", event_mod)) {
2659 _menu_option(VIEW_CENTER_TO_SELECTION);
2660 }
2661 if (ED_IS_SHORTCUT("spatial_editor/align_transform_with_view", event_mod)) {
2662 _menu_option(VIEW_ALIGN_TRANSFORM_WITH_VIEW);
2663 }
2664 if (ED_IS_SHORTCUT("spatial_editor/align_rotation_with_view", event_mod)) {
2665 _menu_option(VIEW_ALIGN_ROTATION_WITH_VIEW);
2666 }
2667 if (ED_IS_SHORTCUT("spatial_editor/insert_anim_key", event_mod)) {
2668 if (!get_selected_count() || _edit.mode != TRANSFORM_NONE) {
2669 return;
2670 }
2671
2672 if (!AnimationPlayerEditor::get_singleton()->get_track_editor()->has_keying()) {
2673 set_message(TTR("Keying is disabled (no key inserted)."));
2674 return;
2675 }
2676
2677 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
2678
2679 for (Node *E : selection) {
2680 Node3D *sp = Object::cast_to<Node3D>(E);
2681 if (!sp) {
2682 continue;
2683 }
2684
2685 spatial_editor->emit_signal(SNAME("transform_key_request"), sp, "", sp->get_transform());
2686 }
2687
2688 set_message(TTR("Animation Key Inserted."));
2689 }
2690 if (ED_IS_SHORTCUT("spatial_editor/cancel_transform", event_mod) && _edit.mode != TRANSFORM_NONE) {
2691 cancel_transform();
2692 }
2693 if (!is_freelook_active() && !k->is_echo()) {
2694 if (ED_IS_SHORTCUT("spatial_editor/reset_transform_position", event_mod)) {
2695 _reset_transform(TransformType::POSITION);
2696 }
2697 if (ED_IS_SHORTCUT("spatial_editor/reset_transform_rotation", event_mod)) {
2698 _reset_transform(TransformType::ROTATION);
2699 }
2700 if (ED_IS_SHORTCUT("spatial_editor/reset_transform_scale", event_mod)) {
2701 _reset_transform(TransformType::SCALE);
2702 }
2703 if (ED_IS_SHORTCUT("spatial_editor/instant_translate", event_mod) && (_edit.mode != TRANSFORM_TRANSLATE || collision_reposition)) {
2704 if (_edit.mode == TRANSFORM_NONE) {
2705 begin_transform(TRANSFORM_TRANSLATE, true);
2706 } else if (_edit.instant || collision_reposition) {
2707 commit_transform();
2708 begin_transform(TRANSFORM_TRANSLATE, true);
2709 }
2710 }
2711 if (ED_IS_SHORTCUT("spatial_editor/instant_rotate", event_mod) && _edit.mode != TRANSFORM_ROTATE) {
2712 if (_edit.mode == TRANSFORM_NONE) {
2713 begin_transform(TRANSFORM_ROTATE, true);
2714 } else if (_edit.instant || collision_reposition) {
2715 commit_transform();
2716 begin_transform(TRANSFORM_ROTATE, true);
2717 }
2718 }
2719 if (ED_IS_SHORTCUT("spatial_editor/instant_scale", event_mod) && _edit.mode != TRANSFORM_SCALE) {
2720 if (_edit.mode == TRANSFORM_NONE) {
2721 begin_transform(TRANSFORM_SCALE, true);
2722 } else if (_edit.instant || collision_reposition) {
2723 commit_transform();
2724 begin_transform(TRANSFORM_SCALE, true);
2725 }
2726 }
2727 if (ED_IS_SHORTCUT("spatial_editor/collision_reposition", event_mod) && editor_selection->get_top_selected_node_list().size() == 1 && !collision_reposition) {
2728 if (_edit.mode == TRANSFORM_NONE || _edit.instant) {
2729 if (_edit.mode == TRANSFORM_NONE) {
2730 _compute_edit(_edit.mouse_pos);
2731 } else {
2732 commit_transform();
2733 _compute_edit(_edit.mouse_pos);
2734 }
2735 _edit.mode = TRANSFORM_TRANSLATE;
2736 collision_reposition = true;
2737 }
2738 }
2739 }
2740
2741 // Freelook doesn't work in orthogonal mode.
2742 if (!orthogonal && ED_IS_SHORTCUT("spatial_editor/freelook_toggle", event_mod)) {
2743 set_freelook_active(!is_freelook_active());
2744
2745 } else if (k->get_keycode() == Key::ESCAPE) {
2746 set_freelook_active(false);
2747 }
2748
2749 if (k->get_keycode() == Key::SPACE) {
2750 if (!k->is_pressed()) {
2751 emit_signal(SNAME("toggle_maximize_view"), this);
2752 }
2753 }
2754
2755 if (ED_IS_SHORTCUT("spatial_editor/decrease_fov", event_mod)) {
2756 scale_fov(-0.05);
2757 }
2758
2759 if (ED_IS_SHORTCUT("spatial_editor/increase_fov", event_mod)) {
2760 scale_fov(0.05);
2761 }
2762
2763 if (ED_IS_SHORTCUT("spatial_editor/reset_fov", event_mod)) {
2764 reset_fov();
2765 }
2766 }
2767
2768 // freelook uses most of the useful shortcuts, like save, so its ok
2769 // to consider freelook active as end of the line for future events.
2770 if (freelook_active) {
2771 accept_event();
2772 }
2773 }
2774
2775 int Node3DEditorViewport::_get_shortcut_input_count(const String &p_name) {
2776 Ref<Shortcut> check_shortcut = ED_GET_SHORTCUT(p_name);
2777
2778 ERR_FAIL_COND_V_MSG(check_shortcut.is_null(), 0, "The Shortcut was null, possible name mismatch.");
2779
2780 return check_shortcut->get_events().size();
2781 }
2782
2783 Node3DEditorViewport::NavigationMode Node3DEditorViewport::_get_nav_mode_from_shortcut_check(ViewportNavMouseButton p_mouse_button, Vector<ShortcutCheckSet> p_shortcut_check_sets, bool p_use_not_empty) {
2784 if (p_use_not_empty) {
2785 for (const ShortcutCheckSet &shortcut_check_set : p_shortcut_check_sets) {
2786 if (shortcut_check_set.mod_pressed && shortcut_check_set.shortcut_not_empty) {
2787 return shortcut_check_set.result_nav_mode;
2788 }
2789 }
2790 } else {
2791 for (const ShortcutCheckSet &shortcut_check_set : p_shortcut_check_sets) {
2792 if (shortcut_check_set.mouse_preference == p_mouse_button && shortcut_check_set.mod_pressed) {
2793 return shortcut_check_set.result_nav_mode;
2794 }
2795 }
2796 }
2797
2798 return NAVIGATION_NONE;
2799 }
2800
2801 void Node3DEditorViewport::_nav_pan(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
2802 const NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
2803 const real_t translation_sensitivity = EDITOR_GET("editors/3d/navigation_feel/translation_sensitivity");
2804
2805 real_t pan_speed = translation_sensitivity / 150.0;
2806 if (p_event.is_valid() && nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
2807 pan_speed *= 10;
2808 }
2809
2810 Transform3D camera_transform;
2811
2812 camera_transform.translate_local(cursor.pos);
2813 camera_transform.basis.rotate(Vector3(1, 0, 0), -cursor.x_rot);
2814 camera_transform.basis.rotate(Vector3(0, 1, 0), -cursor.y_rot);
2815 const bool invert_x_axis = EDITOR_GET("editors/3d/navigation/invert_x_axis");
2816 const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
2817 Vector3 translation(
2818 (invert_x_axis ? -1 : 1) * -p_relative.x * pan_speed,
2819 (invert_y_axis ? -1 : 1) * p_relative.y * pan_speed,
2820 0);
2821 translation *= cursor.distance / DISTANCE_DEFAULT;
2822 camera_transform.translate_local(translation);
2823 cursor.pos = camera_transform.origin;
2824 }
2825
2826 void Node3DEditorViewport::_nav_zoom(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
2827 const NavigationScheme nav_scheme = (NavigationScheme)EDITOR_GET("editors/3d/navigation/navigation_scheme").operator int();
2828
2829 real_t zoom_speed = 1 / 80.0;
2830 if (p_event.is_valid() && nav_scheme == NAVIGATION_MAYA && p_event->is_shift_pressed()) {
2831 zoom_speed *= 10;
2832 }
2833
2834 NavigationZoomStyle zoom_style = (NavigationZoomStyle)EDITOR_GET("editors/3d/navigation/zoom_style").operator int();
2835 if (zoom_style == NAVIGATION_ZOOM_HORIZONTAL) {
2836 if (p_relative.x > 0) {
2837 scale_cursor_distance(1 - p_relative.x * zoom_speed);
2838 } else if (p_relative.x < 0) {
2839 scale_cursor_distance(1.0 / (1 + p_relative.x * zoom_speed));
2840 }
2841 } else {
2842 if (p_relative.y > 0) {
2843 scale_cursor_distance(1 + p_relative.y * zoom_speed);
2844 } else if (p_relative.y < 0) {
2845 scale_cursor_distance(1.0 / (1 - p_relative.y * zoom_speed));
2846 }
2847 }
2848 }
2849
2850 void Node3DEditorViewport::_nav_orbit(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
2851 if (lock_rotation) {
2852 _nav_pan(p_event, p_relative);
2853 return;
2854 }
2855
2856 const real_t degrees_per_pixel = EDITOR_GET("editors/3d/navigation_feel/orbit_sensitivity");
2857 const real_t radians_per_pixel = Math::deg_to_rad(degrees_per_pixel);
2858 const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
2859 const bool invert_x_axis = EDITOR_GET("editors/3d/navigation/invert_x_axis");
2860
2861 cursor.unsnapped_x_rot += p_relative.y * radians_per_pixel * (invert_y_axis ? -1 : 1);
2862 cursor.unsnapped_x_rot = CLAMP(cursor.unsnapped_x_rot, -1.57, 1.57);
2863 cursor.unsnapped_y_rot += p_relative.x * radians_per_pixel * (invert_x_axis ? -1 : 1);
2864
2865 cursor.x_rot = cursor.unsnapped_x_rot;
2866 cursor.y_rot = cursor.unsnapped_y_rot;
2867
2868 bool snap_modifier_configured = !_is_shortcut_empty("spatial_editor/viewport_orbit_snap_modifier_1") || !_is_shortcut_empty("spatial_editor/viewport_orbit_snap_modifier_2");
2869
2870 if (snap_modifier_configured && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_snap_modifier_1") && _is_nav_modifier_pressed("spatial_editor/viewport_orbit_snap_modifier_2")) {
2871 const real_t snap_angle = Math::deg_to_rad(45.0);
2872 const real_t snap_threshold = Math::deg_to_rad((real_t)EDITOR_GET("editors/3d/navigation_feel/angle_snap_threshold"));
2873
2874 real_t x_rot_snapped = Math::snapped(cursor.unsnapped_x_rot, snap_angle);
2875 real_t y_rot_snapped = Math::snapped(cursor.unsnapped_y_rot, snap_angle);
2876
2877 real_t x_dist = Math::abs(cursor.unsnapped_x_rot - x_rot_snapped);
2878 real_t y_dist = Math::abs(cursor.unsnapped_y_rot - y_rot_snapped);
2879
2880 if (x_dist < snap_threshold && y_dist < snap_threshold) {
2881 cursor.x_rot = x_rot_snapped;
2882 cursor.y_rot = y_rot_snapped;
2883
2884 real_t y_rot_wrapped = Math::wrapf(y_rot_snapped, (real_t)-Math::PI, (real_t)Math::PI);
2885
2886 if (Math::abs(x_rot_snapped) < snap_threshold) {
2887 if (Math::abs(y_rot_wrapped) < snap_threshold) {
2888 view_type = VIEW_TYPE_FRONT;
2889 } else if (Math::abs(Math::abs(y_rot_wrapped) - Math::PI) < snap_threshold) {
2890 view_type = VIEW_TYPE_REAR;
2891 } else if (Math::abs(y_rot_wrapped - Math::PI / 2.0) < snap_threshold) {
2892 view_type = VIEW_TYPE_LEFT;
2893 } else if (Math::abs(y_rot_wrapped + Math::PI / 2.0) < snap_threshold) {
2894 view_type = VIEW_TYPE_RIGHT;
2895 } else {
2896 // Only switch to ortho for 90-degree views.
2897 return;
2898 }
2899 _set_auto_orthogonal();
2900 _update_name();
2901 } else if (Math::abs(Math::abs(x_rot_snapped) - Math::PI / 2.0) < snap_threshold) {
2902 if (Math::abs(y_rot_wrapped) < snap_threshold ||
2903 Math::abs(Math::abs(y_rot_wrapped) - Math::PI) < snap_threshold ||
2904 Math::abs(y_rot_wrapped - Math::PI / 2.0) < snap_threshold ||
2905 Math::abs(y_rot_wrapped + Math::PI / 2.0) < snap_threshold) {
2906 view_type = x_rot_snapped > 0 ? VIEW_TYPE_TOP : VIEW_TYPE_BOTTOM;
2907 _set_auto_orthogonal();
2908 _update_name();
2909 }
2910 }
2911
2912 return;
2913 }
2914 }
2915
2916 view_type = VIEW_TYPE_USER;
2917 if (orthogonal && auto_orthogonal) {
2918 _menu_option(VIEW_PERSPECTIVE);
2919 }
2920 }
2921
2922 void Node3DEditorViewport::_nav_look(Ref<InputEventWithModifiers> p_event, const Vector2 &p_relative) {
2923 if (orthogonal) {
2924 _nav_pan(p_event, p_relative);
2925 return;
2926 }
2927
2928 if (orthogonal && auto_orthogonal) {
2929 _menu_option(VIEW_PERSPECTIVE);
2930 }
2931
2932 // Scale mouse sensitivity with camera FOV scale when zoomed in to make it easier to point at things.
2933 const real_t degrees_per_pixel = real_t(EDITOR_GET("editors/3d/freelook/freelook_sensitivity")) * MIN(1.0, cursor.fov_scale);
2934 const real_t radians_per_pixel = Math::deg_to_rad(degrees_per_pixel);
2935 const bool invert_y_axis = EDITOR_GET("editors/3d/navigation/invert_y_axis");
2936
2937 // Note: do NOT assume the camera has the "current" transform, because it is interpolated and may have "lag".
2938 const Transform3D prev_camera_transform = to_camera_transform(cursor);
2939
2940 if (invert_y_axis) {
2941 cursor.x_rot -= p_relative.y * radians_per_pixel;
2942 } else {
2943 cursor.x_rot += p_relative.y * radians_per_pixel;
2944 }
2945 // Clamp the Y rotation to roughly -90..90 degrees so the user can't look upside-down and end up disoriented.
2946 cursor.x_rot = CLAMP(cursor.x_rot, -1.57, 1.57);
2947 cursor.unsnapped_x_rot = cursor.x_rot;
2948
2949 cursor.y_rot += p_relative.x * radians_per_pixel;
2950 cursor.unsnapped_y_rot = cursor.y_rot;
2951
2952 // Look is like the opposite of Orbit: the focus point rotates around the camera
2953 Transform3D camera_transform = to_camera_transform(cursor);
2954 Vector3 pos = camera_transform.xform(Vector3(0, 0, 0));
2955 Vector3 prev_pos = prev_camera_transform.xform(Vector3(0, 0, 0));
2956 Vector3 diff = prev_pos - pos;
2957 cursor.pos += diff;
2958
2959 view_type = VIEW_TYPE_USER;
2960 _update_name();
2961 }
2962
2963 void Node3DEditorViewport::set_freelook_active(bool active_now) {
2964 if (!freelook_active && active_now) {
2965 // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
2966 cursor = camera_cursor;
2967
2968 // Make sure eye_pos is synced, because freelook referential is eye pos rather than orbit pos
2969 Vector3 forward = to_camera_transform(cursor).basis.xform(Vector3(0, 0, -1));
2970 cursor.eye_pos = cursor.pos - cursor.distance * forward;
2971 // Also sync the camera cursor, otherwise switching to freelook will be trippy if inertia is active
2972 camera_cursor.eye_pos = cursor.eye_pos;
2973
2974 if (EDITOR_GET("editors/3d/freelook/freelook_speed_zoom_link")) {
2975 // Re-adjust freelook speed from the current zoom level
2976 real_t base_speed = EDITOR_GET("editors/3d/freelook/freelook_base_speed");
2977 freelook_speed = base_speed * cursor.distance;
2978 }
2979
2980 previous_mouse_position = get_local_mouse_position();
2981
2982 spatial_editor->set_freelook_viewport(this);
2983
2984 // Hide mouse like in an FPS (warping doesn't work)
2985 Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
2986
2987 } else if (freelook_active && !active_now) {
2988 // Sync camera cursor to cursor to "cut" interpolation jumps due to changing referential
2989 cursor = camera_cursor;
2990
2991 spatial_editor->set_freelook_viewport(nullptr);
2992
2993 // Restore mouse
2994 Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
2995
2996 // Restore the previous mouse position when leaving freelook mode.
2997 // This is done because leaving `Input.MOUSE_MODE_CAPTURED` will center the cursor
2998 // due to OS limitations.
2999 warp_mouse(previous_mouse_position);
3000 }
3001
3002 freelook_active = active_now;
3003 }
3004
3005 void Node3DEditorViewport::scale_fov(real_t p_fov_offset) {
3006 cursor.fov_scale = CLAMP(cursor.fov_scale + p_fov_offset, 0.1, 2.5);
3007 surface->queue_redraw();
3008 }
3009
3010 void Node3DEditorViewport::reset_fov() {
3011 cursor.fov_scale = 1.0;
3012 surface->queue_redraw();
3013 }
3014
3015 void Node3DEditorViewport::scale_cursor_distance(real_t scale) {
3016 real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
3017 real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
3018 if (unlikely(min_distance > max_distance)) {
3019 cursor.distance = (min_distance + max_distance) / 2;
3020 } else {
3021 cursor.distance = CLAMP(cursor.distance * scale, min_distance, max_distance);
3022 }
3023
3024 if (cursor.distance == max_distance || cursor.distance == min_distance) {
3025 zoom_failed_attempts_count++;
3026 } else {
3027 zoom_failed_attempts_count = 0;
3028 }
3029
3030 zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
3031 surface->queue_redraw();
3032 }
3033
3034 void Node3DEditorViewport::scale_freelook_speed(real_t scale) {
3035 real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
3036 real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
3037 if (unlikely(min_speed > max_speed)) {
3038 freelook_speed = (min_speed + max_speed) / 2;
3039 } else {
3040 freelook_speed = CLAMP(freelook_speed * scale, min_speed, max_speed);
3041 }
3042
3043 zoom_indicator_delay = ZOOM_FREELOOK_INDICATOR_DELAY_S;
3044 surface->queue_redraw();
3045 }
3046
3047 bool Node3DEditorViewport::_is_nav_modifier_pressed(const String &p_name) {
3048 return _is_shortcut_empty(p_name) || Input::get_singleton()->is_action_pressed(p_name);
3049 }
3050
3051 bool Node3DEditorViewport::_is_shortcut_empty(const String &p_name) {
3052 Ref<Shortcut> check_shortcut = ED_GET_SHORTCUT(p_name);
3053
3054 ERR_FAIL_COND_V_MSG(check_shortcut.is_null(), true, "The Shortcut was null, possible name mismatch.");
3055
3056 return check_shortcut->get_events().is_empty();
3057 }
3058
3059 Point2 Node3DEditorViewport::_get_warped_mouse_motion(const Ref<InputEventMouseMotion> &p_ev_mouse_motion) const {
3060 Point2 relative;
3061 if (bool(EDITOR_GET("editors/3d/navigation/warped_mouse_panning"))) {
3062 relative = Input::get_singleton()->warp_mouse_motion(p_ev_mouse_motion, surface->get_global_rect());
3063 } else {
3064 relative = p_ev_mouse_motion->get_relative();
3065 }
3066 return relative;
3067 }
3068
3069 void Node3DEditorViewport::_update_freelook(real_t delta) {
3070 if (!is_freelook_active()) {
3071 return;
3072 }
3073
3074 const FreelookNavigationScheme navigation_scheme = (FreelookNavigationScheme)EDITOR_GET("editors/3d/freelook/freelook_navigation_scheme").operator int();
3075
3076 Vector3 forward;
3077 if (navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
3078 // Forward/backward keys will always go straight forward/backward, never moving on the Y axis.
3079 forward = Vector3(0, 0, -1).rotated(Vector3(0, 1, 0), camera->get_rotation().y);
3080 } else {
3081 // Forward/backward keys will be relative to the camera pitch.
3082 forward = camera->get_transform().basis.xform(Vector3(0, 0, -1));
3083 }
3084
3085 const Vector3 right = camera->get_transform().basis.xform(Vector3(1, 0, 0));
3086
3087 Vector3 up;
3088 if (navigation_scheme == FREELOOK_PARTIALLY_AXIS_LOCKED || navigation_scheme == FREELOOK_FULLY_AXIS_LOCKED) {
3089 // Up/down keys will always go up/down regardless of camera pitch.
3090 up = Vector3(0, 1, 0);
3091 } else {
3092 // Up/down keys will be relative to the camera pitch.
3093 up = camera->get_transform().basis.xform(Vector3(0, 1, 0));
3094 }
3095
3096 Vector3 direction;
3097
3098 // Use actions from the inputmap, as this is the only way to reliably detect input in this method.
3099 // See #54469 for more discussion and explanation.
3100 Input *inp = Input::get_singleton();
3101 if (inp->is_action_pressed("spatial_editor/freelook_left")) {
3102 direction -= right;
3103 }
3104 if (inp->is_action_pressed("spatial_editor/freelook_right")) {
3105 direction += right;
3106 }
3107 if (inp->is_action_pressed("spatial_editor/freelook_forward")) {
3108 direction += forward;
3109 }
3110 if (inp->is_action_pressed("spatial_editor/freelook_backwards")) {
3111 direction -= forward;
3112 }
3113 if (inp->is_action_pressed("spatial_editor/freelook_up")) {
3114 direction += up;
3115 }
3116 if (inp->is_action_pressed("spatial_editor/freelook_down")) {
3117 direction -= up;
3118 }
3119
3120 real_t speed = freelook_speed;
3121
3122 if (inp->is_action_pressed("spatial_editor/freelook_speed_modifier")) {
3123 speed *= 3.0;
3124 }
3125 if (inp->is_action_pressed("spatial_editor/freelook_slow_modifier")) {
3126 speed *= 0.333333;
3127 }
3128
3129 const Vector3 motion = direction * speed * delta;
3130 cursor.pos += motion;
3131 cursor.eye_pos += motion;
3132 }
3133
3134 void Node3DEditorViewport::set_message(const String &p_message, float p_time) {
3135 message = p_message;
3136 message_time = p_time;
3137 }
3138
3139 void Node3DEditorPlugin::edited_scene_changed() {
3140 for (uint32_t i = 0; i < Node3DEditor::VIEWPORTS_COUNT; i++) {
3141 Node3DEditorViewport *viewport = Node3DEditor::get_singleton()->get_editor_viewport(i);
3142 if (viewport->is_visible()) {
3143 viewport->notification(Control::NOTIFICATION_VISIBILITY_CHANGED);
3144 }
3145 }
3146 }
3147
3148 void Node3DEditorViewport::_project_settings_changed() {
3149 // Update shadow atlas if changed.
3150 int shadowmap_size = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_size");
3151 bool shadowmap_16_bits = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_16_bits");
3152 int atlas_q0 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv");
3153 int atlas_q1 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv");
3154 int atlas_q2 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv");
3155 int atlas_q3 = GLOBAL_GET("rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv");
3156
3157 viewport->set_positional_shadow_atlas_size(shadowmap_size);
3158 viewport->set_positional_shadow_atlas_16_bits(shadowmap_16_bits);
3159 viewport->set_positional_shadow_atlas_quadrant_subdiv(0, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q0));
3160 viewport->set_positional_shadow_atlas_quadrant_subdiv(1, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q1));
3161 viewport->set_positional_shadow_atlas_quadrant_subdiv(2, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q2));
3162 viewport->set_positional_shadow_atlas_quadrant_subdiv(3, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q3));
3163
3164 // Update MSAA, screen-space AA and debanding if changed
3165
3166 const int msaa_mode = GLOBAL_GET("rendering/anti_aliasing/quality/msaa_3d");
3167 viewport->set_msaa_3d(Viewport::MSAA(msaa_mode));
3168 const int ssaa_mode = GLOBAL_GET("rendering/anti_aliasing/quality/screen_space_aa");
3169 viewport->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode));
3170 const bool use_taa = GLOBAL_GET("rendering/anti_aliasing/quality/use_taa");
3171 viewport->set_use_taa(use_taa);
3172
3173 const bool transparent_background = GLOBAL_GET("rendering/viewport/transparent_background");
3174 viewport->set_transparent_background(transparent_background);
3175
3176 const bool use_hdr_2d = GLOBAL_GET("rendering/viewport/hdr_2d");
3177 viewport->set_use_hdr_2d(use_hdr_2d);
3178
3179 const bool use_debanding = GLOBAL_GET("rendering/anti_aliasing/quality/use_debanding");
3180 viewport->set_use_debanding(use_debanding);
3181
3182 const bool use_occlusion_culling = GLOBAL_GET("rendering/occlusion_culling/use_occlusion_culling");
3183 viewport->set_use_occlusion_culling(use_occlusion_culling);
3184
3185 const float mesh_lod_threshold = GLOBAL_GET("rendering/mesh_lod/lod_change/threshold_pixels");
3186 viewport->set_mesh_lod_threshold(mesh_lod_threshold);
3187
3188 const Viewport::Scaling3DMode scaling_3d_mode = Viewport::Scaling3DMode(int(GLOBAL_GET("rendering/scaling_3d/mode")));
3189 viewport->set_scaling_3d_mode(scaling_3d_mode);
3190
3191 _update_shrink();
3192
3193 const float fsr_sharpness = GLOBAL_GET("rendering/scaling_3d/fsr_sharpness");
3194 viewport->set_fsr_sharpness(fsr_sharpness);
3195
3196 const float texture_mipmap_bias = GLOBAL_GET("rendering/textures/default_filters/texture_mipmap_bias");
3197 viewport->set_texture_mipmap_bias(texture_mipmap_bias);
3198
3199 const Viewport::AnisotropicFiltering anisotropic_filtering_level = Viewport::AnisotropicFiltering(int(GLOBAL_GET("rendering/textures/default_filters/anisotropic_filtering_level")));
3200 viewport->set_anisotropic_filtering_level(anisotropic_filtering_level);
3201 }
3202
3203 static void override_label_colors(Control *p_control) {
3204 p_control->begin_bulk_theme_override();
3205 p_control->add_theme_color_override(SceneStringName(font_color), p_control->get_theme_color(SNAME("font_dark_background_color"), EditorStringName(Editor)));
3206 p_control->add_theme_color_override("font_hover_color", p_control->get_theme_color(SNAME("font_dark_background_hover_color"), EditorStringName(Editor)));
3207 p_control->add_theme_color_override("font_focus_color", p_control->get_theme_color(SNAME("font_dark_background_focus_color"), EditorStringName(Editor)));
3208 p_control->add_theme_color_override("font_pressed_color", p_control->get_theme_color(SNAME("font_dark_background_pressed_color"), EditorStringName(Editor)));
3209 p_control->add_theme_color_override("font_hover_pressed_color", p_control->get_theme_color(SNAME("font_dark_background_hover_pressed_color"), EditorStringName(Editor)));
3210 p_control->end_bulk_theme_override();
3211 }
3212
3213 static void override_button_stylebox(Button *p_button, const Ref<StyleBox> p_stylebox) {
3214 p_button->begin_bulk_theme_override();
3215 p_button->add_theme_style_override(CoreStringName(normal), p_stylebox);
3216 p_button->add_theme_style_override("normal_mirrored", p_stylebox);
3217 p_button->add_theme_style_override(SceneStringName(hover), p_stylebox);
3218 p_button->add_theme_style_override("hover_mirrored", p_stylebox);
3219 p_button->add_theme_style_override("hover_pressed", p_stylebox);
3220 p_button->add_theme_style_override("hover_pressed_mirrored", p_stylebox);
3221 p_button->add_theme_style_override(SceneStringName(pressed), p_stylebox);
3222 p_button->add_theme_style_override("pressed_mirrored", p_stylebox);
3223 p_button->add_theme_style_override("focus", p_stylebox);
3224 p_button->add_theme_style_override("focus_mirrored", p_stylebox);
3225 p_button->add_theme_style_override("disabled", p_stylebox);
3226 p_button->add_theme_style_override("disabled_mirrored", p_stylebox);
3227 p_button->end_bulk_theme_override();
3228 }
3229
3230 void Node3DEditorViewport::_notification(int p_what) {
3231 switch (p_what) {
3232 case NOTIFICATION_TRANSLATION_CHANGED: {
3233 _update_name();
3234 _update_centered_labels();
3235 message_time = MIN(message_time, 0.001); // Make it disappear.
3236
3237 Key key = OS::prefer_meta_over_ctrl() ? Key::META : Key::CTRL;
3238 preview_material_label_desc->set_text(vformat(TTR("Drag and drop to override the material of any geometry node.\nHold %s when dropping to override a specific surface."), find_keycode_name(key)));
3239
3240 const int item_count = display_submenu->get_item_count();
3241 for (int i = 0; i < item_count; i++) {
3242 const Array item_data = display_submenu->get_item_metadata(i);
3243 if (item_data.is_empty()) {
3244 continue;
3245 }
3246
3247 SupportedRenderingMethods rendering_methods = item_data[0];
3248 String base_tooltip = item_data[1];
3249
3250 bool disabled = false;
3251 String disabled_tooltip;
3252 switch (rendering_methods) {
3253 case SupportedRenderingMethods::ALL:
3254 break;
3255 case SupportedRenderingMethods::FORWARD_PLUS_MOBILE:
3256 disabled = OS::get_singleton()->get_current_rendering_method() == "gl_compatibility";
3257 disabled_tooltip = TTR("This debug draw mode is only supported when using the Forward+ or Mobile renderer.");
3258 break;
3259 case SupportedRenderingMethods::FORWARD_PLUS:
3260 disabled = OS::get_singleton()->get_current_rendering_method() == "gl_compatibility" || OS::get_singleton()->get_current_rendering_method() == "mobile";
3261 disabled_tooltip = TTR("This debug draw mode is only supported when using the Forward+ renderer.");
3262 break;
3263 }
3264
3265 display_submenu->set_item_disabled(i, disabled);
3266 String tooltip = TTR(base_tooltip);
3267 if (disabled) {
3268 if (tooltip.is_empty()) {
3269 tooltip = disabled_tooltip;
3270 } else {
3271 tooltip += "\n\n" + disabled_tooltip;
3272 }
3273 }
3274 display_submenu->set_item_tooltip(i, tooltip);
3275 }
3276 } break;
3277
3278 case NOTIFICATION_READY: {
3279 ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditorViewport::_project_settings_changed));
3280 _update_navigation_controls_visibility();
3281 } break;
3282
3283 case NOTIFICATION_VISIBILITY_CHANGED: {
3284 bool vp_visible = is_visible_in_tree();
3285
3286 set_process(vp_visible);
3287 set_physics_process(vp_visible);
3288
3289 if (vp_visible) {
3290 orthogonal = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL));
3291 _update_name();
3292 _update_camera(0);
3293 } else {
3294 set_freelook_active(false);
3295 }
3296 callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
3297 } break;
3298
3299 case NOTIFICATION_RESIZED: {
3300 callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
3301 } break;
3302
3303 case NOTIFICATION_PROCESS: {
3304 if (ruler->is_inside_tree()) {
3305 Vector3 start_pos = ruler_start_point->get_global_position();
3306 Vector3 end_pos = ruler_end_point->get_global_position();
3307
3308 geometry->clear_surfaces();
3309 geometry->surface_begin(Mesh::PRIMITIVE_LINES);
3310 geometry->surface_add_vertex(start_pos);
3311 geometry->surface_add_vertex(end_pos);
3312 geometry->surface_end();
3313
3314 float distance = start_pos.distance_to(end_pos);
3315 ruler_label->set_text(TranslationServer::get_singleton()->format_number(vformat("%.3f m", distance), _get_locale()));
3316
3317 Vector3 center = (start_pos + end_pos) / 2;
3318 Vector2 screen_position = camera->unproject_position(center) - (ruler_label->get_custom_minimum_size() / 2);
3319 ruler_label->set_position(screen_position);
3320 }
3321
3322 real_t delta = get_process_delta_time();
3323
3324 if (zoom_indicator_delay > 0) {
3325 zoom_indicator_delay -= delta;
3326 if (zoom_indicator_delay <= 0) {
3327 surface->queue_redraw();
3328 zoom_limit_label->hide();
3329 }
3330 }
3331
3332 _update_freelook(delta);
3333
3334 Node *scene_root = SceneTreeDock::get_singleton()->get_editor_data()->get_edited_scene_root();
3335 if (previewing_cinema && scene_root != nullptr) {
3336 Camera3D *cam = scene_root->get_viewport()->get_camera_3d();
3337 if (cam != nullptr && cam != previewing) {
3338 //then switch the viewport's camera to the scene's viewport camera
3339 if (previewing != nullptr) {
3340 previewing->disconnect(SceneStringName(tree_exited), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
3341 previewing->disconnect(CoreStringName(property_list_changed), callable_mp(this, &Node3DEditorViewport::_preview_camera_property_changed));
3342 }
3343 previewing = cam;
3344 previewing->connect(SceneStringName(tree_exited), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
3345 previewing->connect(CoreStringName(property_list_changed), callable_mp(this, &Node3DEditorViewport::_preview_camera_property_changed));
3346 RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), cam->get_camera());
3347 surface->queue_redraw();
3348 }
3349 }
3350
3351 if (_camera_moved_externally()) {
3352 // If camera moved after this plugin last set it, presumably a tool script has moved it, accept the new camera transform as the cursor position.
3353 _apply_camera_transform_to_cursor();
3354 _update_camera(0);
3355 } else {
3356 _update_camera(delta);
3357 }
3358
3359 const HashMap<ObjectID, Object *> &selection = editor_selection->get_selection();
3360
3361 bool changed = false;
3362 bool exist = false;
3363
3364 for (const KeyValue<ObjectID, Object *> &E : selection) {
3365 Node3D *sp = ObjectDB::get_instance<Node3D>(E.key);
3366 if (!sp) {
3367 continue;
3368 }
3369
3370 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
3371 if (!se) {
3372 continue;
3373 }
3374
3375 Transform3D t = sp->get_global_gizmo_transform();
3376 if (!t.is_finite()) {
3377 continue;
3378 }
3379 AABB new_aabb = _calculate_spatial_bounds(sp);
3380
3381 exist = true;
3382 if (se->last_xform == t && se->aabb == new_aabb && !se->last_xform_dirty) {
3383 continue;
3384 }
3385 changed = true;
3386 se->last_xform_dirty = false;
3387 se->last_xform = t;
3388
3389 se->aabb = new_aabb;
3390
3391 Transform3D t_offset = t;
3392
3393 // apply AABB scaling before item's global transform
3394 {
3395 const Vector3 offset(0.005, 0.005, 0.005);
3396 Basis aabb_s;
3397 aabb_s.scale(se->aabb.size + offset);
3398 t.translate_local(se->aabb.position - offset / 2);
3399 t.basis = t.basis * aabb_s;
3400 }
3401 {
3402 const Vector3 offset(0.01, 0.01, 0.01);
3403 Basis aabb_s;
3404 aabb_s.scale(se->aabb.size + offset);
3405 t_offset.translate_local(se->aabb.position - offset / 2);
3406 t_offset.basis = t_offset.basis * aabb_s;
3407 }
3408
3409 RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance, t);
3410 RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_offset, t_offset);
3411 RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray, t);
3412 RenderingServer::get_singleton()->instance_set_transform(se->sbox_instance_xray_offset, t_offset);
3413 }
3414
3415 if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
3416 spatial_editor->update_transform_gizmo();
3417 }
3418
3419 if (message_time > 0) {
3420 if (message != last_message) {
3421 surface->queue_redraw();
3422 last_message = message;
3423 }
3424
3425 message_time -= get_process_delta_time();
3426 if (message_time < 0) {
3427 surface->queue_redraw();
3428 }
3429 }
3430
3431 bool show_info = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_INFORMATION));
3432 if (show_info != info_panel->is_visible()) {
3433 info_panel->set_visible(show_info);
3434 }
3435
3436 Camera3D *current_camera;
3437
3438 if (previewing) {
3439 current_camera = previewing;
3440 } else {
3441 current_camera = camera;
3442 }
3443
3444 if (show_info) {
3445 const String viewport_size = vformat(U"%d × %d", viewport->get_size().x * viewport->get_scaling_3d_scale(), viewport->get_size().y * viewport->get_scaling_3d_scale());
3446 String text;
3447 text += vformat(TTR("X: %s"), rtos(current_camera->get_position().x).pad_decimals(1)) + "\n";
3448 text += vformat(TTR("Y: %s"), rtos(current_camera->get_position().y).pad_decimals(1)) + "\n";
3449 text += vformat(TTR("Z: %s"), rtos(current_camera->get_position().z).pad_decimals(1)) + "\n";
3450 text += "\n";
3451 text += vformat(
3452 TTR("Size: %s (%.1fMP)") + "\n",
3453 viewport_size,
3454 viewport->get_size().x * viewport->get_size().y * Math::pow(viewport->get_scaling_3d_scale(), 2) * 0.000001);
3455
3456 text += "\n";
3457 text += vformat(TTR("Objects: %d"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_OBJECTS_IN_FRAME)) + "\n";
3458 text += vformat(TTR("Primitives: %d"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_PRIMITIVES_IN_FRAME)) + "\n";
3459 text += vformat(TTR("Draw Calls: %d"), viewport->get_render_info(Viewport::RENDER_INFO_TYPE_VISIBLE, Viewport::RENDER_INFO_DRAW_CALLS_IN_FRAME));
3460
3461 info_label->set_text(text);
3462 }
3463
3464 // FPS Counter.
3465 bool show_fps = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_FRAME_TIME));
3466
3467 if (show_fps != frame_time_panel->is_visible()) {
3468 frame_time_panel->set_visible(show_fps);
3469 RS::get_singleton()->viewport_set_measure_render_time(viewport->get_viewport_rid(), show_fps);
3470 for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
3471 // Initialize to 120 FPS, so that the initial estimation until we get enough data is always reasonable.
3472 cpu_time_history[i] = 8.333333;
3473 gpu_time_history[i] = 8.333333;
3474 }
3475 cpu_time_history_index = 0;
3476 gpu_time_history_index = 0;
3477 }
3478 if (show_fps) {
3479 cpu_time_history[cpu_time_history_index] = RS::get_singleton()->viewport_get_measured_render_time_cpu(viewport->get_viewport_rid());
3480 cpu_time_history_index = (cpu_time_history_index + 1) % FRAME_TIME_HISTORY;
3481 double cpu_time = 0.0;
3482 for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
3483 cpu_time += cpu_time_history[i];
3484 }
3485 cpu_time /= FRAME_TIME_HISTORY;
3486 // Prevent unrealistically low values.
3487 cpu_time = MAX(0.01, cpu_time);
3488
3489 gpu_time_history[gpu_time_history_index] = RS::get_singleton()->viewport_get_measured_render_time_gpu(viewport->get_viewport_rid());
3490 gpu_time_history_index = (gpu_time_history_index + 1) % FRAME_TIME_HISTORY;
3491 double gpu_time = 0.0;
3492 for (int i = 0; i < FRAME_TIME_HISTORY; i++) {
3493 gpu_time += gpu_time_history[i];
3494 }
3495 gpu_time /= FRAME_TIME_HISTORY;
3496 // Prevent division by zero for the FPS counter (and unrealistically low values).
3497 // This limits the reported FPS to 100000.
3498 gpu_time = MAX(0.01, gpu_time);
3499
3500 // Color labels depending on performance level ("good" = green, "OK" = yellow, "bad" = red).
3501 // Middle point is at 15 ms.
3502 cpu_time_label->set_text(vformat(TTR("CPU Time: %s ms"), rtos(cpu_time).pad_decimals(2)));
3503 cpu_time_label->add_theme_color_override(
3504 SceneStringName(font_color),
3505 frame_time_gradient->get_color_at_offset(
3506 Math::remap(cpu_time, 0, 30, 0, 1)));
3507
3508 gpu_time_label->set_text(vformat(TTR("GPU Time: %s ms"), rtos(gpu_time).pad_decimals(2)));
3509 // Middle point is at 15 ms.
3510 gpu_time_label->add_theme_color_override(
3511 SceneStringName(font_color),
3512 frame_time_gradient->get_color_at_offset(
3513 Math::remap(gpu_time, 0, 30, 0, 1)));
3514
3515 const double fps = 1000.0 / gpu_time;
3516 fps_label->set_text(vformat(TTR("FPS: %d"), fps));
3517 // Middle point is at 60 FPS.
3518 fps_label->add_theme_color_override(
3519 SceneStringName(font_color),
3520 frame_time_gradient->get_color_at_offset(
3521 Math::remap(fps, 110, 10, 0, 1)));
3522 }
3523 } break;
3524
3525 case NOTIFICATION_PHYSICS_PROCESS: {
3526 if (collision_reposition) {
3527 Node3D *selected_node = nullptr;
3528
3529 if (ruler->is_inside_tree()) {
3530 if (ruler_start_point->is_visible()) {
3531 selected_node = ruler_end_point;
3532 } else {
3533 selected_node = ruler_start_point;
3534 }
3535 } else {
3536 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
3537 if (selection.size() == 1) {
3538 selected_node = Object::cast_to<Node3D>(selection.front()->get());
3539 }
3540 }
3541
3542 if (selected_node) {
3543 if (!ruler->is_inside_tree()) {
3544 double snap = EDITOR_GET("interface/inspector/default_float_step");
3545 int snap_step_decimals = Math::range_step_decimals(snap);
3546 set_message(TTR("Translating:") + " (" + String::num(selected_node->get_global_position().x, snap_step_decimals) + ", " +
3547 String::num(selected_node->get_global_position().y, snap_step_decimals) + ", " + String::num(selected_node->get_global_position().z, snap_step_decimals) + ")");
3548 }
3549
3550 selected_node->set_global_position(spatial_editor->snap_point(_get_instance_position(_edit.mouse_pos, selected_node)));
3551
3552 if (ruler->is_inside_tree() && !ruler_start_point->is_visible()) {
3553 ruler_end_point->set_global_position(ruler_start_point->get_global_position());
3554 ruler_start_point->set_visible(true);
3555 ruler_end_point->set_visible(true);
3556 ruler_label->set_visible(true);
3557 }
3558 }
3559 }
3560
3561 if (!update_preview_node) {
3562 return;
3563 }
3564 if (preview_node->is_inside_tree()) {
3565 preview_node_pos = spatial_editor->snap_point(_get_instance_position(preview_node_viewport_pos, preview_node));
3566 double snap = EDITOR_GET("interface/inspector/default_float_step");
3567 int snap_step_decimals = Math::range_step_decimals(snap);
3568 set_message(TTR("Instantiating:") + " (" + String::num(preview_node_pos.x, snap_step_decimals) + ", " +
3569 String::num(preview_node_pos.y, snap_step_decimals) + ", " + String::num(preview_node_pos.z, snap_step_decimals) + ")");
3570 Transform3D preview_gl_transform = Transform3D(Basis(), preview_node_pos);
3571 preview_node->set_global_transform(preview_gl_transform);
3572 if (!preview_node->is_visible()) {
3573 preview_node->show();
3574 }
3575 }
3576 update_preview_node = false;
3577 } break;
3578
3579 case NOTIFICATION_APPLICATION_FOCUS_OUT:
3580 case NOTIFICATION_WM_WINDOW_FOCUS_OUT: {
3581 set_freelook_active(false);
3582 cursor.region_select = false;
3583 surface->queue_redraw();
3584
3585 // Commit the drag if the window is focused out.
3586 if (_edit.mode != TRANSFORM_NONE) {
3587 commit_transform();
3588 return;
3589 }
3590
3591 if (_edit.gizmo.is_valid()) {
3592 // Certain gizmo plugins should be able to commit handles without dragging them.
3593 if (_edit.original_mouse_pos != _edit.mouse_pos || _edit.gizmo->get_plugin()->can_commit_handle_on_click()) {
3594 _edit.gizmo->commit_handle(_edit.gizmo_handle, _edit.gizmo_handle_secondary, _edit.gizmo_initial_value, false);
3595 }
3596
3597 spatial_editor->get_single_selected_node()->update_gizmos();
3598 _edit.gizmo = Ref<EditorNode3DGizmo>();
3599 }
3600 } break;
3601
3602 case NOTIFICATION_ENTER_TREE: {
3603 surface->connect(SceneStringName(draw), callable_mp(this, &Node3DEditorViewport::_draw));
3604 surface->connect(SceneStringName(gui_input), callable_mp(this, &Node3DEditorViewport::_sinput));
3605 surface->connect(SceneStringName(mouse_entered), callable_mp(this, &Node3DEditorViewport::_surface_mouse_enter));
3606 surface->connect(SceneStringName(mouse_exited), callable_mp(this, &Node3DEditorViewport::_surface_mouse_exit));
3607 surface->connect(SceneStringName(focus_entered), callable_mp(this, &Node3DEditorViewport::_surface_focus_enter));
3608 surface->connect(SceneStringName(focus_exited), callable_mp(this, &Node3DEditorViewport::_surface_focus_exit));
3609
3610 _init_gizmo_instance(index);
3611 } break;
3612
3613 case NOTIFICATION_EXIT_TREE: {
3614 _finish_gizmo_instances();
3615 } break;
3616
3617 case NOTIFICATION_THEME_CHANGED: {
3618 _update_centered_labels();
3619
3620 view_display_menu->set_button_icon(get_editor_theme_icon(SNAME("GuiTabMenuHlDarkBackground")));
3621 preview_camera->set_button_icon(get_editor_theme_icon(SNAME("Camera3DDarkBackground")));
3622 Control *gui_base = EditorNode::get_singleton()->get_gui_base();
3623
3624 const Ref<StyleBox> &information_3d_stylebox = gui_base->get_theme_stylebox(SNAME("Information3dViewport"), EditorStringName(EditorStyles));
3625
3626 override_button_stylebox(view_display_menu, information_3d_stylebox);
3627 override_label_colors(view_display_menu);
3628 override_button_stylebox(translation_preview_button, information_3d_stylebox);
3629 override_label_colors(translation_preview_button);
3630 override_button_stylebox(preview_camera, information_3d_stylebox);
3631 override_label_colors(preview_camera);
3632
3633 frame_time_gradient->set_color(0, get_theme_color(SNAME("success_color_dark_background"), EditorStringName(Editor)));
3634 frame_time_gradient->set_color(1, get_theme_color(SNAME("warning_color_dark_background"), EditorStringName(Editor)));
3635 frame_time_gradient->set_color(2, get_theme_color(SNAME("error_color_dark_background"), EditorStringName(Editor)));
3636
3637 info_panel->add_theme_style_override(SceneStringName(panel), information_3d_stylebox);
3638 override_label_colors(info_label);
3639
3640 frame_time_panel->add_theme_style_override(SceneStringName(panel), information_3d_stylebox);
3641 // Set a minimum width to prevent the width from changing all the time
3642 // when numbers vary rapidly. This minimum width is set based on a
3643 // GPU time of 999.99 ms in the current editor language.
3644 const float min_width = get_theme_font(SNAME("main"), EditorStringName(EditorFonts))->get_string_size(vformat(TTR("GPU Time: %s ms"), 999.99)).x;
3645 frame_time_panel->set_custom_minimum_size(Size2(min_width, 0) * EDSCALE);
3646 frame_time_vbox->add_theme_constant_override("separation", Math::round(-1 * EDSCALE));
3647
3648 cinema_label->add_theme_style_override(CoreStringName(normal), information_3d_stylebox);
3649 locked_label->add_theme_style_override(CoreStringName(normal), information_3d_stylebox);
3650
3651 ruler_label->add_theme_color_override(SceneStringName(font_color), Color(1.0, 0.9, 0.0, 1.0));
3652 ruler_label->add_theme_color_override("font_outline_color", Color(0.0, 0.0, 0.0, 1.0));
3653 ruler_label->add_theme_constant_override("outline_size", 4 * EDSCALE);
3654 ruler_label->add_theme_font_size_override(SceneStringName(font_size), 15 * EDSCALE);
3655 ruler_label->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("bold"), EditorStringName(EditorFonts)));
3656 } break;
3657
3658 case NOTIFICATION_DRAG_END: {
3659 // Clear preview material when dropped outside applicable object.
3660 if (spatial_editor->get_preview_material().is_valid() && !is_drag_successful()) {
3661 _reset_preview_material();
3662 _remove_preview_material();
3663 } else {
3664 _remove_preview_node();
3665 }
3666 } break;
3667
3668 case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
3669 if (EditorSettings::get_singleton()->check_changed_settings_in_group("editors/3d")) {
3670 _update_navigation_controls_visibility();
3671 }
3672 } break;
3673 }
3674 }
3675
3676 static void draw_indicator_bar(Control &p_surface, real_t p_fill, const Ref<Texture2D> p_icon, const Ref<Font> p_font, int p_font_size, const String &p_text, const Color &p_color) {
3677 // Adjust bar size from control height
3678 const Vector2 surface_size = p_surface.get_size();
3679 const real_t h = surface_size.y / 2.0;
3680 const real_t y = (surface_size.y - h) / 2.0;
3681
3682 const Rect2 r(10 * EDSCALE, y, 6 * EDSCALE, h);
3683 const real_t sy = r.size.y * p_fill;
3684
3685 // Note: because this bar appears over the viewport, it has to stay readable for any background color
3686 // Draw both neutral dark and bright colors to account this
3687 p_surface.draw_rect(r, p_color * Color(1, 1, 1, 0.2));
3688 p_surface.draw_rect(Rect2(r.position.x, r.position.y + r.size.y - sy, r.size.x, sy), p_color * Color(1, 1, 1, 0.6));
3689 p_surface.draw_rect(r.grow(1), Color(0, 0, 0, 0.7), false, Math::round(EDSCALE));
3690
3691 const Vector2 icon_size = p_icon->get_size();
3692 const Vector2 icon_pos = Vector2(r.position.x - (icon_size.x - r.size.x) / 2, r.position.y + r.size.y + 2 * EDSCALE);
3693 p_surface.draw_texture(p_icon, icon_pos, p_color);
3694
3695 // Draw text below the bar (for speed/zoom information).
3696 p_surface.draw_string_outline(p_font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), p_text, HORIZONTAL_ALIGNMENT_LEFT, -1.f, p_font_size, Math::round(4 * EDSCALE), Color(0, 0, 0));
3697 p_surface.draw_string(p_font, Vector2(icon_pos.x, icon_pos.y + icon_size.y + 16 * EDSCALE), p_text, HORIZONTAL_ALIGNMENT_LEFT, -1.f, p_font_size, p_color);
3698 }
3699
3700 void Node3DEditorViewport::_draw() {
3701 EditorNode::get_singleton()->get_editor_plugins_over()->forward_3d_draw_over_viewport(surface);
3702 EditorNode::get_singleton()->get_editor_plugins_force_over()->forward_3d_force_draw_over_viewport(surface);
3703
3704 if (surface->has_focus() || rotation_control->has_focus()) {
3705 Size2 size = surface->get_size();
3706 Rect2 r = Rect2(Point2(), size);
3707 get_theme_stylebox(SNAME("FocusViewport"), EditorStringName(EditorStyles))->draw(surface->get_canvas_item(), r);
3708 }
3709
3710 if (cursor.region_select && movement_threshold_passed) {
3711 const Rect2 selection_rect = Rect2(cursor.region_begin, cursor.region_end - cursor.region_begin);
3712
3713 surface->draw_rect(
3714 selection_rect,
3715 get_theme_color(SNAME("box_selection_fill_color"), EditorStringName(Editor)));
3716
3717 surface->draw_rect(
3718 selection_rect,
3719 get_theme_color(SNAME("box_selection_stroke_color"), EditorStringName(Editor)),
3720 false,
3721 Math::round(EDSCALE));
3722 }
3723
3724 RID ci = surface->get_canvas_item();
3725
3726 if (message_time > 0) {
3727 Ref<Font> font = get_theme_font(SceneStringName(font), SNAME("Label"));
3728 int font_size = get_theme_font_size(SceneStringName(font_size), SNAME("Label"));
3729 Point2 msgpos = Point2(10 * EDSCALE, get_size().y - 14 * EDSCALE);
3730 font->draw_string(ci, msgpos + Point2(1, 1), message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(0, 0, 0, 0.8));
3731 font->draw_string(ci, msgpos + Point2(-1, -1), message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(0, 0, 0, 0.8));
3732 font->draw_string(ci, msgpos, message, HORIZONTAL_ALIGNMENT_LEFT, -1, font_size, Color(1, 1, 1, 1));
3733 }
3734
3735 if (_edit.mode == TRANSFORM_ROTATE) {
3736 Point2 center = point_to_screen(_edit.center);
3737
3738 Color handle_color;
3739 switch (_edit.plane) {
3740 case TRANSFORM_VIEW:
3741 handle_color = Color(1.0, 1.0, 1.0, 1.0);
3742 break;
3743 case TRANSFORM_X_AXIS:
3744 handle_color = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
3745 break;
3746 case TRANSFORM_Y_AXIS:
3747 handle_color = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
3748 break;
3749 case TRANSFORM_Z_AXIS:
3750 handle_color = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
3751 break;
3752 default:
3753 handle_color = get_theme_color(SNAME("accent_color"), EditorStringName(Editor));
3754 break;
3755 }
3756
3757 if (_is_rotation_arc_visible() && !_edit.initial_click_vector.is_zero_approx()) {
3758 Vector3 up = _edit.rotation_axis;
3759 Vector3 right = _edit.initial_click_vector;
3760
3761 right = right - up * up.dot(right);
3762 right.normalize();
3763 Vector3 forward = up.cross(right);
3764
3765 real_t rotation_radius = (_edit.plane == TRANSFORM_VIEW) ? GIZMO_VIEW_ROTATION_SIZE : GIZMO_CIRCLE_SIZE;
3766
3767 const int circle_segments = 64;
3768 Vector<Point2> circle_points;
3769 for (int i = 0; i <= circle_segments; i++) {
3770 float angle = (float(i) / float(circle_segments)) * Math::TAU;
3771 Vector3 point_3d = _edit.center + gizmo_scale * rotation_radius * (right * Math::cos(angle) + forward * Math::sin(angle));
3772 Point2 point_2d = point_to_screen(point_3d);
3773 circle_points.push_back(point_2d);
3774 }
3775
3776 Color circle_color = (_edit.plane == TRANSFORM_VIEW) ? Color(1.0, 1.0, 1.0, 0.8) : handle_color.from_hsv(handle_color.get_h(), 0.6, 1.0, 0.8);
3777 for (int i = 0; i < circle_points.size() - 1; i++) {
3778 RenderingServer::get_singleton()->canvas_item_add_line(
3779 ci,
3780 circle_points[i],
3781 circle_points[i + 1],
3782 circle_color,
3783 Math::round(2 * EDSCALE));
3784 }
3785
3786 const int segments = 64;
3787 float display_angle = _edit.display_rotation_angle;
3788
3789 float abs_angle = Math::abs(display_angle);
3790 if (abs_angle > Math::TAU) {
3791 float remainder = Math::fmod((double)abs_angle, Math::TAU);
3792 remainder = remainder < 0.01 ? Math::TAU : remainder;
3793 display_angle = SIGN(display_angle) * remainder;
3794 abs_angle = remainder;
3795 }
3796
3797 int num_segments = MAX(8, int(abs_angle / (Math::TAU / segments) * segments));
3798 num_segments = MIN(num_segments, segments);
3799
3800 Color fill_color = Color(1.0, 1.0, 1.0, 0.2);
3801
3802 bool is_counterclockwise = display_angle > 0;
3803 float start_angle = is_counterclockwise ? 0.0f : display_angle;
3804 float end_angle = is_counterclockwise ? display_angle : 0.0f;
3805
3806 for (int i = 0; i < num_segments; i++) {
3807 float t1 = float(i) / float(num_segments);
3808 float t2 = float(i + 1) / float(num_segments);
3809 float angle1 = Math::lerp(start_angle, end_angle, t1);
3810 float angle2 = Math::lerp(start_angle, end_angle, t2);
3811
3812 Vector3 point1_3d = _edit.center + gizmo_scale * rotation_radius * (right * Math::cos(angle1) + forward * Math::sin(angle1));
3813 Vector3 point2_3d = _edit.center + gizmo_scale * rotation_radius * (right * Math::cos(angle2) + forward * Math::sin(angle2));
3814
3815 Point2 center_2d = center;
3816 Point2 point1_2d = point_to_screen(point1_3d);
3817 Point2 point2_2d = point_to_screen(point2_3d);
3818
3819 Vector<Point2> triangle_points;
3820 triangle_points.push_back(center_2d);
3821 triangle_points.push_back(point1_2d);
3822 triangle_points.push_back(point2_2d);
3823
3824 Vector<Color> triangle_colors;
3825 triangle_colors.push_back(fill_color);
3826 triangle_colors.push_back(fill_color);
3827 triangle_colors.push_back(fill_color);
3828
3829 RenderingServer::get_singleton()->canvas_item_add_polygon(ci, triangle_points, triangle_colors);
3830 }
3831
3832 Color edge_color = (_edit.plane == TRANSFORM_VIEW) ? Color(1.0, 1.0, 1.0, 0.7) : handle_color.from_hsv(handle_color.get_h(), 0.8, 1.0, 0.7);
3833
3834 Vector3 start_point_3d = _edit.center + gizmo_scale * rotation_radius * right;
3835 Point2 start_point_2d = point_to_screen(start_point_3d);
3836 RenderingServer::get_singleton()->canvas_item_add_line(
3837 ci,
3838 center,
3839 start_point_2d,
3840 edge_color,
3841 Math::round(2 * EDSCALE));
3842
3843 Vector3 end_point_3d = _edit.center + gizmo_scale * rotation_radius * (right * Math::cos(_edit.accumulated_rotation_angle) + forward * Math::sin(_edit.accumulated_rotation_angle));
3844 Point2 end_point_2d = point_to_screen(end_point_3d);
3845 RenderingServer::get_singleton()->canvas_item_add_line(
3846 ci,
3847 center,
3848 end_point_2d,
3849 edge_color,
3850 Math::round(2 * EDSCALE));
3851 }
3852
3853 if (_edit.show_rotation_line) {
3854 handle_color = handle_color.from_hsv(handle_color.get_h(), 0.25, 1.0, 1);
3855 RenderingServer::get_singleton()->canvas_item_add_line(
3856 ci,
3857 _edit.mouse_pos,
3858 center,
3859 handle_color,
3860 Math::round(2 * EDSCALE));
3861 }
3862 }
3863 if (previewing) {
3864 Size2 ss = Size2(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"));
3865 float aspect = ss.aspect();
3866 Size2 s = get_size();
3867
3868 Rect2 draw_rect;
3869
3870 switch (previewing->get_keep_aspect_mode()) {
3871 case Camera3D::KEEP_WIDTH: {
3872 draw_rect.size = Size2(s.width, s.width / aspect);
3873 draw_rect.position.x = 0;
3874 draw_rect.position.y = (s.height - draw_rect.size.y) * 0.5;
3875
3876 } break;
3877 case Camera3D::KEEP_HEIGHT: {
3878 draw_rect.size = Size2(s.height * aspect, s.height);
3879 draw_rect.position.y = 0;
3880 draw_rect.position.x = (s.width - draw_rect.size.x) * 0.5;
3881
3882 } break;
3883 }
3884
3885 draw_rect = Rect2(Vector2(), s).intersection(draw_rect);
3886
3887 surface->draw_rect(draw_rect, Color(0.6, 0.6, 0.1, 0.5), false, Math::round(2 * EDSCALE));
3888
3889 } else {
3890 if (zoom_indicator_delay > 0.0) {
3891 if (is_freelook_active()) {
3892 // Show speed
3893
3894 real_t min_speed = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
3895 real_t max_speed = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
3896 real_t scale_length = (max_speed - min_speed);
3897
3898 if (!Math::is_zero_approx(scale_length)) {
3899 real_t logscale_t = 1.0 - Math::log1p(freelook_speed - min_speed) / Math::log1p(scale_length);
3900
3901 // Display the freelook speed to help the user get a better sense of scale.
3902 const int precision = freelook_speed < 1.0 ? 2 : 1;
3903 draw_indicator_bar(
3904 *surface,
3905 1.0 - logscale_t,
3906 get_editor_theme_icon(SNAME("ViewportSpeed")),
3907 get_theme_font("bold", EditorStringName(EditorFonts)),
3908 get_theme_font_size(SceneStringName(font_size), SNAME("Label")),
3909 vformat("%s m/s", String::num(freelook_speed).pad_decimals(precision)),
3910 Color(1.0, 0.95, 0.7));
3911 }
3912
3913 } else {
3914 // Show zoom
3915 zoom_limit_label->set_visible(zoom_failed_attempts_count > 15);
3916
3917 real_t min_distance = MAX(camera->get_near() * 4, ZOOM_FREELOOK_MIN);
3918 real_t max_distance = MIN(camera->get_far() / 4, ZOOM_FREELOOK_MAX);
3919 real_t scale_length = (max_distance - min_distance);
3920
3921 if (!Math::is_zero_approx(scale_length)) {
3922 real_t logscale_t = 1.0 - Math::log1p(cursor.distance - min_distance) / Math::log1p(scale_length);
3923
3924 // Display the zoom center distance to help the user get a better sense of scale.
3925 const int precision = cursor.distance < 1.0 ? 2 : 1;
3926 draw_indicator_bar(
3927 *surface,
3928 logscale_t,
3929 get_editor_theme_icon(SNAME("ViewportZoom")),
3930 get_theme_font("bold", EditorStringName(EditorFonts)),
3931 get_theme_font_size(SceneStringName(font_size), SNAME("Label")),
3932 vformat("%s m", String::num(cursor.distance).pad_decimals(precision)),
3933 Color(0.7, 0.95, 1.0));
3934 }
3935 }
3936 }
3937 }
3938 }
3939
3940 bool Node3DEditorViewport::_camera_moved_externally() {
3941 Transform3D t = camera->get_global_transform();
3942 return !t.is_equal_approx(last_camera_transform);
3943 }
3944
3945 void Node3DEditorViewport::_apply_camera_transform_to_cursor() {
3946 // Effectively the reverse of to_camera_transform, use camera transform to set cursor position and rotation.
3947 const Transform3D camera_transform = camera->get_camera_transform();
3948 const Basis basis = camera_transform.basis;
3949
3950 real_t distance;
3951 if (orthogonal) {
3952 distance = (get_zfar() - get_znear()) / 2.0;
3953 } else {
3954 distance = cursor.distance;
3955 }
3956
3957 cursor.pos = camera_transform.origin - basis.get_column(2) * distance;
3958
3959 cursor.x_rot = -camera_transform.basis.get_euler().x;
3960 cursor.y_rot = -camera_transform.basis.get_euler().y;
3961 cursor.unsnapped_x_rot = cursor.x_rot;
3962 cursor.unsnapped_y_rot = cursor.y_rot;
3963 }
3964
3965 void Node3DEditorViewport::_menu_option(int p_option) {
3966 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
3967 switch (p_option) {
3968 case VIEW_TOP: {
3969 cursor.y_rot = 0;
3970 cursor.x_rot = Math::PI / 2.0;
3971 cursor.unsnapped_y_rot = cursor.y_rot;
3972 cursor.unsnapped_x_rot = cursor.x_rot;
3973 set_message(TTR("Top View."), 2);
3974 view_type = VIEW_TYPE_TOP;
3975 _set_auto_orthogonal();
3976 _update_name();
3977
3978 } break;
3979 case VIEW_BOTTOM: {
3980 cursor.y_rot = 0;
3981 cursor.x_rot = -Math::PI / 2.0;
3982 cursor.unsnapped_y_rot = cursor.y_rot;
3983 cursor.unsnapped_x_rot = cursor.x_rot;
3984 set_message(TTR("Bottom View."), 2);
3985 view_type = VIEW_TYPE_BOTTOM;
3986 _set_auto_orthogonal();
3987 _update_name();
3988
3989 } break;
3990 case VIEW_LEFT: {
3991 cursor.x_rot = 0;
3992 cursor.y_rot = Math::PI / 2.0;
3993 cursor.unsnapped_x_rot = cursor.x_rot;
3994 cursor.unsnapped_y_rot = cursor.y_rot;
3995 set_message(TTR("Left View."), 2);
3996 view_type = VIEW_TYPE_LEFT;
3997 _set_auto_orthogonal();
3998 _update_name();
3999
4000 } break;
4001 case VIEW_RIGHT: {
4002 cursor.x_rot = 0;
4003 cursor.y_rot = -Math::PI / 2.0;
4004 cursor.unsnapped_x_rot = cursor.x_rot;
4005 cursor.unsnapped_y_rot = cursor.y_rot;
4006 set_message(TTR("Right View."), 2);
4007 view_type = VIEW_TYPE_RIGHT;
4008 _set_auto_orthogonal();
4009 _update_name();
4010
4011 } break;
4012 case VIEW_FRONT: {
4013 cursor.x_rot = 0;
4014 cursor.y_rot = 0;
4015 cursor.unsnapped_x_rot = cursor.x_rot;
4016 cursor.unsnapped_y_rot = cursor.y_rot;
4017 set_message(TTR("Front View."), 2);
4018 view_type = VIEW_TYPE_FRONT;
4019 _set_auto_orthogonal();
4020 _update_name();
4021
4022 } break;
4023 case VIEW_REAR: {
4024 cursor.x_rot = 0;
4025 cursor.y_rot = Math::PI;
4026 cursor.unsnapped_x_rot = cursor.x_rot;
4027 cursor.unsnapped_y_rot = cursor.y_rot;
4028 set_message(TTR("Rear View."), 2);
4029 view_type = VIEW_TYPE_REAR;
4030 _set_auto_orthogonal();
4031 _update_name();
4032
4033 } break;
4034 case VIEW_CENTER_TO_ORIGIN: {
4035 cursor.pos = Vector3(0, 0, 0);
4036
4037 } break;
4038 case VIEW_CENTER_TO_SELECTION: {
4039 focus_selection();
4040
4041 } break;
4042 case VIEW_ALIGN_TRANSFORM_WITH_VIEW: {
4043 if (!get_selected_count()) {
4044 break;
4045 }
4046
4047 Transform3D camera_transform = camera->get_global_transform();
4048
4049 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
4050
4051 undo_redo->create_action(TTR("Align Transform with View"));
4052 for (Node *E : selection) {
4053 Node3D *sp = Object::cast_to<Node3D>(E);
4054 if (!sp) {
4055 continue;
4056 }
4057
4058 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
4059 if (!se) {
4060 continue;
4061 }
4062
4063 Transform3D xform = camera_transform;
4064 if (orthogonal) {
4065 Vector3 offset = camera_transform.basis.xform(Vector3(0, 0, cursor.distance));
4066 xform.origin = cursor.pos + offset;
4067 } else {
4068 xform.scale_basis(sp->get_scale());
4069 }
4070
4071 if (Object::cast_to<Decal>(E)) {
4072 // Adjust rotation to match Decal's default orientation.
4073 // This makes the decal "look" in the same direction as the camera,
4074 // rather than pointing down relative to the camera orientation.
4075 xform.basis.rotate_local(Vector3(1, 0, 0), Math::TAU * 0.25);
4076 }
4077
4078 Node3D *parent = sp->get_parent_node_3d();
4079 Transform3D local_xform = parent ? parent->get_global_transform().affine_inverse() * xform : xform;
4080 undo_redo->add_do_method(sp, "set_transform", local_xform);
4081 undo_redo->add_undo_method(sp, "set_transform", sp->get_local_gizmo_transform());
4082 }
4083 undo_redo->commit_action();
4084
4085 } break;
4086 case VIEW_ALIGN_ROTATION_WITH_VIEW: {
4087 if (!get_selected_count()) {
4088 break;
4089 }
4090
4091 Transform3D camera_transform = camera->get_global_transform();
4092
4093 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
4094
4095 undo_redo->create_action(TTR("Align Rotation with View"));
4096 for (Node *E : selection) {
4097 Node3D *sp = Object::cast_to<Node3D>(E);
4098 if (!sp) {
4099 continue;
4100 }
4101
4102 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
4103 if (!se) {
4104 continue;
4105 }
4106
4107 Basis basis = camera_transform.basis;
4108
4109 if (Object::cast_to<Decal>(E)) {
4110 // Adjust rotation to match Decal's default orientation.
4111 // This makes the decal "look" in the same direction as the camera,
4112 // rather than pointing down relative to the camera orientation.
4113 basis.rotate_local(Vector3(1, 0, 0), Math::TAU * 0.25);
4114 }
4115
4116 undo_redo->add_do_method(sp, "set_rotation", basis.get_euler_normalized());
4117 undo_redo->add_undo_method(sp, "set_rotation", sp->get_rotation());
4118 }
4119 undo_redo->commit_action();
4120
4121 } break;
4122 case VIEW_ENVIRONMENT: {
4123 int idx = view_display_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
4124 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4125 current = !current;
4126 if (current) {
4127 camera->set_environment(Ref<Resource>());
4128 } else {
4129 camera->set_environment(Node3DEditor::get_singleton()->get_viewport_environment());
4130 }
4131
4132 view_display_menu->get_popup()->set_item_checked(idx, current);
4133
4134 } break;
4135 case VIEW_PERSPECTIVE: {
4136 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
4137 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false);
4138 orthogonal = false;
4139 auto_orthogonal = false;
4140 callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
4141 _update_camera(0);
4142 _update_name();
4143
4144 } break;
4145 case VIEW_ORTHOGONAL: {
4146 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false);
4147 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true);
4148 orthogonal = true;
4149 auto_orthogonal = false;
4150 callable_mp(this, &Node3DEditorViewport::update_transform_gizmo_view).call_deferred();
4151 _update_camera(0);
4152 _update_name();
4153 } break;
4154 case VIEW_SWITCH_PERSPECTIVE_ORTHOGONAL: {
4155 _menu_option(orthogonal ? VIEW_PERSPECTIVE : VIEW_ORTHOGONAL);
4156
4157 } break;
4158 case VIEW_AUTO_ORTHOGONAL: {
4159 int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL);
4160 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4161 current = !current;
4162 view_display_menu->get_popup()->set_item_checked(idx, current);
4163 if (auto_orthogonal) {
4164 auto_orthogonal = false;
4165 _update_name();
4166 }
4167 } break;
4168 case VIEW_LOCK_ROTATION: {
4169 int idx = view_display_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
4170 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4171 _set_lock_view_rotation(!current);
4172
4173 } break;
4174 case VIEW_AUDIO_LISTENER: {
4175 int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
4176 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4177 current = !current;
4178 viewport->set_as_audio_listener_3d(current);
4179 view_display_menu->get_popup()->set_item_checked(idx, current);
4180
4181 } break;
4182 case VIEW_AUDIO_DOPPLER: {
4183 int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
4184 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4185 current = !current;
4186 camera->set_doppler_tracking(current ? Camera3D::DOPPLER_TRACKING_IDLE_STEP : Camera3D::DOPPLER_TRACKING_DISABLED);
4187 view_display_menu->get_popup()->set_item_checked(idx, current);
4188
4189 } break;
4190 case VIEW_CINEMATIC_PREVIEW: {
4191 int idx = view_display_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
4192 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4193 current = !current;
4194 view_display_menu->get_popup()->set_item_checked(idx, current);
4195 _toggle_cinema_preview(current);
4196
4197 cinema_label->set_visible(current);
4198 _update_centered_labels();
4199 surface->queue_redraw();
4200
4201 if (current) {
4202 preview_camera->hide();
4203 } else {
4204 if (previewing != nullptr) {
4205 preview_camera->show();
4206 }
4207 }
4208 } break;
4209 case VIEW_GIZMOS: {
4210 int idx = view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS);
4211 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4212 current = !current;
4213 uint32_t layers = camera->get_cull_mask();
4214 layers &= ~(1 << GIZMO_EDIT_LAYER);
4215 if (current) {
4216 layers |= (1 << GIZMO_EDIT_LAYER);
4217 }
4218 camera->set_cull_mask(layers);
4219 view_display_menu->get_popup()->set_item_checked(idx, current);
4220
4221 } break;
4222 case VIEW_TRANSFORM_GIZMO: {
4223 int idx = view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO);
4224 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4225 current = !current;
4226 transform_gizmo_visible = current;
4227
4228 spatial_editor->update_transform_gizmo();
4229 view_display_menu->get_popup()->set_item_checked(idx, current);
4230 } break;
4231 case VIEW_HALF_RESOLUTION: {
4232 int idx = view_display_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
4233 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4234 view_display_menu->get_popup()->set_item_checked(idx, !current);
4235 _update_shrink();
4236 } break;
4237 case VIEW_INFORMATION: {
4238 int idx = view_display_menu->get_popup()->get_item_index(VIEW_INFORMATION);
4239 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4240 view_display_menu->get_popup()->set_item_checked(idx, !current);
4241
4242 } break;
4243 case VIEW_FRAME_TIME: {
4244 int idx = view_display_menu->get_popup()->get_item_index(VIEW_FRAME_TIME);
4245 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4246 view_display_menu->get_popup()->set_item_checked(idx, !current);
4247 } break;
4248 case VIEW_GRID: {
4249 int idx = view_display_menu->get_popup()->get_item_index(VIEW_GRID);
4250 bool current = view_display_menu->get_popup()->is_item_checked(idx);
4251 current = !current;
4252 uint32_t layers = camera->get_cull_mask();
4253 layers &= ~(1 << GIZMO_GRID_LAYER);
4254 if (current) {
4255 layers |= (1 << GIZMO_GRID_LAYER);
4256 }
4257 camera->set_cull_mask(layers);
4258 view_display_menu->get_popup()->set_item_checked(idx, current);
4259 } break;
4260 case VIEW_DISPLAY_NORMAL:
4261 case VIEW_DISPLAY_WIREFRAME:
4262 case VIEW_DISPLAY_OVERDRAW:
4263 case VIEW_DISPLAY_UNSHADED:
4264 case VIEW_DISPLAY_LIGHTING:
4265 case VIEW_DISPLAY_NORMAL_BUFFER:
4266 case VIEW_DISPLAY_DEBUG_SHADOW_ATLAS:
4267 case VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS:
4268 case VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO:
4269 case VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING:
4270 case VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION:
4271 case VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE:
4272 case VIEW_DISPLAY_DEBUG_SSAO:
4273 case VIEW_DISPLAY_DEBUG_SSIL:
4274 case VIEW_DISPLAY_DEBUG_PSSM_SPLITS:
4275 case VIEW_DISPLAY_DEBUG_DECAL_ATLAS:
4276 case VIEW_DISPLAY_DEBUG_SDFGI:
4277 case VIEW_DISPLAY_DEBUG_SDFGI_PROBES:
4278 case VIEW_DISPLAY_DEBUG_GI_BUFFER:
4279 case VIEW_DISPLAY_DEBUG_DISABLE_LOD:
4280 case VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS:
4281 case VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS:
4282 case VIEW_DISPLAY_DEBUG_CLUSTER_DECALS:
4283 case VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES:
4284 case VIEW_DISPLAY_DEBUG_OCCLUDERS:
4285 case VIEW_DISPLAY_MOTION_VECTORS:
4286 case VIEW_DISPLAY_INTERNAL_BUFFER: {
4287 static const int display_options[] = {
4288 VIEW_DISPLAY_NORMAL,
4289 VIEW_DISPLAY_WIREFRAME,
4290 VIEW_DISPLAY_OVERDRAW,
4291 VIEW_DISPLAY_UNSHADED,
4292 VIEW_DISPLAY_LIGHTING,
4293 VIEW_DISPLAY_NORMAL_BUFFER,
4294 VIEW_DISPLAY_DEBUG_SHADOW_ATLAS,
4295 VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS,
4296 VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO,
4297 VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING,
4298 VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION,
4299 VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE,
4300 VIEW_DISPLAY_DEBUG_SSAO,
4301 VIEW_DISPLAY_DEBUG_SSIL,
4302 VIEW_DISPLAY_DEBUG_GI_BUFFER,
4303 VIEW_DISPLAY_DEBUG_DISABLE_LOD,
4304 VIEW_DISPLAY_DEBUG_PSSM_SPLITS,
4305 VIEW_DISPLAY_DEBUG_DECAL_ATLAS,
4306 VIEW_DISPLAY_DEBUG_SDFGI,
4307 VIEW_DISPLAY_DEBUG_SDFGI_PROBES,
4308 VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS,
4309 VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS,
4310 VIEW_DISPLAY_DEBUG_CLUSTER_DECALS,
4311 VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES,
4312 VIEW_DISPLAY_DEBUG_OCCLUDERS,
4313 VIEW_DISPLAY_MOTION_VECTORS,
4314 VIEW_DISPLAY_INTERNAL_BUFFER,
4315 VIEW_MAX
4316 };
4317 static const Viewport::DebugDraw debug_draw_modes[] = {
4318 Viewport::DEBUG_DRAW_DISABLED,
4319 Viewport::DEBUG_DRAW_WIREFRAME,
4320 Viewport::DEBUG_DRAW_OVERDRAW,
4321 Viewport::DEBUG_DRAW_UNSHADED,
4322 Viewport::DEBUG_DRAW_LIGHTING,
4323 Viewport::DEBUG_DRAW_NORMAL_BUFFER,
4324 Viewport::DEBUG_DRAW_SHADOW_ATLAS,
4325 Viewport::DEBUG_DRAW_DIRECTIONAL_SHADOW_ATLAS,
4326 Viewport::DEBUG_DRAW_VOXEL_GI_ALBEDO,
4327 Viewport::DEBUG_DRAW_VOXEL_GI_LIGHTING,
4328 Viewport::DEBUG_DRAW_VOXEL_GI_EMISSION,
4329 Viewport::DEBUG_DRAW_SCENE_LUMINANCE,
4330 Viewport::DEBUG_DRAW_SSAO,
4331 Viewport::DEBUG_DRAW_SSIL,
4332 Viewport::DEBUG_DRAW_GI_BUFFER,
4333 Viewport::DEBUG_DRAW_DISABLE_LOD,
4334 Viewport::DEBUG_DRAW_PSSM_SPLITS,
4335 Viewport::DEBUG_DRAW_DECAL_ATLAS,
4336 Viewport::DEBUG_DRAW_SDFGI,
4337 Viewport::DEBUG_DRAW_SDFGI_PROBES,
4338 Viewport::DEBUG_DRAW_CLUSTER_OMNI_LIGHTS,
4339 Viewport::DEBUG_DRAW_CLUSTER_SPOT_LIGHTS,
4340 Viewport::DEBUG_DRAW_CLUSTER_DECALS,
4341 Viewport::DEBUG_DRAW_CLUSTER_REFLECTION_PROBES,
4342 Viewport::DEBUG_DRAW_OCCLUDERS,
4343 Viewport::DEBUG_DRAW_MOTION_VECTORS,
4344 Viewport::DEBUG_DRAW_INTERNAL_BUFFER,
4345 };
4346
4347 for (int idx = 0; display_options[idx] != VIEW_MAX; idx++) {
4348 int id = display_options[idx];
4349 int item_idx = view_display_menu->get_popup()->get_item_index(id);
4350 if (item_idx != -1) {
4351 view_display_menu->get_popup()->set_item_checked(item_idx, id == p_option);
4352 }
4353 item_idx = display_submenu->get_item_index(id);
4354 if (item_idx != -1) {
4355 display_submenu->set_item_checked(item_idx, id == p_option);
4356 }
4357
4358 if (id == p_option) {
4359 viewport->set_debug_draw(debug_draw_modes[idx]);
4360 }
4361 }
4362 } break;
4363 }
4364 }
4365
4366 void Node3DEditorViewport::_set_auto_orthogonal() {
4367 if (!orthogonal && view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL))) {
4368 _menu_option(VIEW_ORTHOGONAL);
4369 auto_orthogonal = true;
4370 }
4371 }
4372
4373 void Node3DEditorViewport::_preview_exited_scene() {
4374 preview_camera->disconnect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
4375 preview_camera->set_pressed(false);
4376 _toggle_camera_preview(false);
4377 preview_camera->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
4378 view_display_menu->show();
4379 }
4380
4381 void Node3DEditorViewport::_preview_camera_property_changed() {
4382 if (previewing) {
4383 surface->queue_redraw();
4384 }
4385 }
4386
4387 void Node3DEditorViewport::_update_centered_labels() {
4388 if (cinema_label->is_visible()) {
4389 cinema_label->reset_size();
4390 float cinema_half_width = cinema_label->get_size().width / 2.0f;
4391 cinema_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -cinema_half_width);
4392 }
4393
4394 if (locked_label->is_visible()) {
4395 locked_label->reset_size();
4396 float locked_half_width = locked_label->get_size().width / 2.0f;
4397 locked_label->set_anchor_and_offset(SIDE_LEFT, 0.5f, -locked_half_width);
4398 }
4399 }
4400
4401 void Node3DEditorViewport::_init_gizmo_instance(int p_idx) {
4402 uint32_t layer = 1 << (GIZMO_BASE_LAYER + p_idx);
4403
4404 for (int i = 0; i < 3; i++) {
4405 move_gizmo_instance[i] = RS::get_singleton()->instance_create();
4406 RS::get_singleton()->instance_set_base(move_gizmo_instance[i], spatial_editor->get_move_gizmo(i)->get_rid());
4407 RS::get_singleton()->instance_set_scenario(move_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
4408 RS::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
4409 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
4410 RS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i], layer);
4411 RS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
4412 RS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
4413
4414 move_plane_gizmo_instance[i] = RS::get_singleton()->instance_create();
4415 RS::get_singleton()->instance_set_base(move_plane_gizmo_instance[i], spatial_editor->get_move_plane_gizmo(i)->get_rid());
4416 RS::get_singleton()->instance_set_scenario(move_plane_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
4417 RS::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
4418 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(move_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
4419 RS::get_singleton()->instance_set_layer_mask(move_plane_gizmo_instance[i], layer);
4420 RS::get_singleton()->instance_geometry_set_flag(move_plane_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
4421 RS::get_singleton()->instance_geometry_set_flag(move_plane_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
4422
4423 scale_gizmo_instance[i] = RS::get_singleton()->instance_create();
4424 RS::get_singleton()->instance_set_base(scale_gizmo_instance[i], spatial_editor->get_scale_gizmo(i)->get_rid());
4425 RS::get_singleton()->instance_set_scenario(scale_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
4426 RS::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
4427 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
4428 RS::get_singleton()->instance_set_layer_mask(scale_gizmo_instance[i], layer);
4429 RS::get_singleton()->instance_geometry_set_flag(scale_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
4430 RS::get_singleton()->instance_geometry_set_flag(scale_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
4431
4432 scale_plane_gizmo_instance[i] = RS::get_singleton()->instance_create();
4433 RS::get_singleton()->instance_set_base(scale_plane_gizmo_instance[i], spatial_editor->get_scale_plane_gizmo(i)->get_rid());
4434 RS::get_singleton()->instance_set_scenario(scale_plane_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
4435 RS::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
4436 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(scale_plane_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
4437 RS::get_singleton()->instance_set_layer_mask(scale_plane_gizmo_instance[i], layer);
4438 RS::get_singleton()->instance_geometry_set_flag(scale_plane_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
4439 RS::get_singleton()->instance_geometry_set_flag(scale_plane_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
4440
4441 axis_gizmo_instance[i] = RS::get_singleton()->instance_create();
4442 }
4443
4444 for (int i = 0; i < 3; i++) {
4445 RS::get_singleton()->instance_set_base(axis_gizmo_instance[i], spatial_editor->get_axis_gizmo(i)->get_rid());
4446 RS::get_singleton()->instance_set_scenario(axis_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
4447 RS::get_singleton()->instance_set_visible(axis_gizmo_instance[i], true);
4448 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(axis_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
4449 RS::get_singleton()->instance_set_layer_mask(axis_gizmo_instance[i], layer);
4450 RS::get_singleton()->instance_geometry_set_flag(axis_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
4451 RS::get_singleton()->instance_geometry_set_flag(axis_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
4452 }
4453
4454 for (int i = 0; i < 4; i++) {
4455 rotate_gizmo_instance[i] = RS::get_singleton()->instance_create();
4456 RS::get_singleton()->instance_set_base(rotate_gizmo_instance[i], spatial_editor->get_rotate_gizmo(i)->get_rid());
4457 RS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i], get_tree()->get_root()->get_world_3d()->get_scenario());
4458 RS::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
4459 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(rotate_gizmo_instance[i], RS::SHADOW_CASTING_SETTING_OFF);
4460 RS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i], layer);
4461 RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
4462 RS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
4463 }
4464 }
4465
4466 void Node3DEditorViewport::_finish_gizmo_instances() {
4467 ERR_FAIL_NULL(RenderingServer::get_singleton());
4468 for (int i = 0; i < 3; i++) {
4469 RS::get_singleton()->free_rid(move_gizmo_instance[i]);
4470 RS::get_singleton()->free_rid(move_plane_gizmo_instance[i]);
4471 RS::get_singleton()->free_rid(rotate_gizmo_instance[i]);
4472 RS::get_singleton()->free_rid(scale_gizmo_instance[i]);
4473 RS::get_singleton()->free_rid(scale_plane_gizmo_instance[i]);
4474 RS::get_singleton()->free_rid(axis_gizmo_instance[i]);
4475 }
4476 // Rotation white outline
4477 RS::get_singleton()->free_rid(rotate_gizmo_instance[3]);
4478 }
4479
4480 void Node3DEditorViewport::_toggle_camera_preview(bool p_activate) {
4481 ERR_FAIL_COND(p_activate && !preview);
4482 ERR_FAIL_COND(!p_activate && !previewing);
4483
4484 previewing_camera = p_activate;
4485 _update_navigation_controls_visibility();
4486
4487 if (!p_activate) {
4488 previewing->disconnect(SceneStringName(tree_exiting), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
4489 previewing->disconnect(CoreStringName(property_list_changed), callable_mp(this, &Node3DEditorViewport::_preview_camera_property_changed));
4490 previewing = nullptr;
4491 RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
4492 if (!preview) {
4493 preview_camera->hide();
4494 }
4495 surface->queue_redraw();
4496
4497 } else {
4498 previewing = preview;
4499 previewing->connect(SceneStringName(tree_exiting), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
4500 previewing->connect(CoreStringName(property_list_changed), callable_mp(this, &Node3DEditorViewport::_preview_camera_property_changed));
4501 RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), preview->get_camera()); //replace
4502 surface->queue_redraw();
4503 }
4504 }
4505
4506 void Node3DEditorViewport::_toggle_cinema_preview(bool p_activate) {
4507 previewing_cinema = p_activate;
4508 _update_navigation_controls_visibility();
4509
4510 if (!previewing_cinema) {
4511 if (previewing != nullptr) {
4512 previewing->disconnect(SceneStringName(tree_exited), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
4513 previewing->disconnect(CoreStringName(property_list_changed), callable_mp(this, &Node3DEditorViewport::_preview_camera_property_changed));
4514 }
4515
4516 previewing = nullptr;
4517 RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), camera->get_camera()); //restore
4518 preview_camera->set_pressed(false);
4519 if (!preview) {
4520 preview_camera->hide();
4521 } else {
4522 preview_camera->show();
4523 }
4524 view_display_menu->show();
4525 surface->queue_redraw();
4526 }
4527 }
4528
4529 void Node3DEditorViewport::_selection_result_pressed(int p_result) {
4530 if (selection_results_menu.size() <= p_result) {
4531 return;
4532 }
4533
4534 clicked = selection_results_menu[p_result]->get_instance_id();
4535
4536 if (clicked.is_valid()) {
4537 _select_clicked(true);
4538 }
4539
4540 selection_results_menu.clear();
4541 }
4542
4543 void Node3DEditorViewport::_selection_menu_hide() {
4544 selection_results.clear();
4545 selection_menu->clear();
4546 selection_menu->reset_size();
4547 }
4548
4549 void Node3DEditorViewport::set_can_preview(Camera3D *p_preview) {
4550 preview = p_preview;
4551
4552 if (!preview_camera->is_pressed() && !previewing_cinema) {
4553 preview_camera->set_visible(p_preview);
4554 }
4555 }
4556
4557 void Node3DEditorViewport::update_transform_gizmo_view() {
4558 if (!is_visible_in_tree()) {
4559 return;
4560 }
4561
4562 Transform3D xform = spatial_editor->get_gizmo_transform();
4563
4564 Transform3D camera_xform = camera->get_transform();
4565
4566 if (xform.origin.is_equal_approx(camera_xform.origin)) {
4567 for (int i = 0; i < 3; i++) {
4568 RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
4569 RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
4570 RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
4571 RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
4572 RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
4573 RenderingServer::get_singleton()->instance_set_visible(axis_gizmo_instance[i], false);
4574 }
4575 RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
4576 return;
4577 }
4578
4579 const Vector3 camz = -camera_xform.get_basis().get_column(2).normalized();
4580 const Vector3 camy = -camera_xform.get_basis().get_column(1).normalized();
4581 const Plane p = Plane(camz, camera_xform.origin);
4582 const real_t gizmo_d = MAX(Math::abs(p.distance_to(xform.origin)), CMP_EPSILON);
4583 const real_t d0 = camera->unproject_position(camera_xform.origin + camz * gizmo_d).y;
4584 const real_t d1 = camera->unproject_position(camera_xform.origin + camz * gizmo_d + camy).y;
4585 const real_t dd = MAX(Math::abs(d0 - d1), CMP_EPSILON);
4586
4587 const real_t gizmo_size = EDITOR_GET("editors/3d/manipulator_gizmo_size");
4588 // At low viewport heights, multiply the gizmo scale based on the viewport height.
4589 // This prevents the gizmo from growing very large and going outside the viewport.
4590 const int viewport_base_height = 400 * MAX(1, EDSCALE);
4591 gizmo_scale =
4592 (gizmo_size / Math::abs(dd)) * MAX(1, EDSCALE) *
4593 MIN(viewport_base_height, subviewport_container->get_size().height) / viewport_base_height;
4594 Vector3 scale = Vector3(1, 1, 1) * gizmo_scale;
4595
4596 // if the determinant is zero, we should disable the gizmo from being rendered
4597 // this prevents supplying bad values to the renderer and then having to filter it out again
4598 if (xform.basis.determinant() == 0) {
4599 for (int i = 0; i < 3; i++) {
4600 RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], false);
4601 RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], false);
4602 RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], false);
4603 RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], false);
4604 RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], false);
4605 }
4606 RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], false);
4607 return;
4608 }
4609
4610 bool local_coords = spatial_editor->are_local_coords_enabled();
4611 bool arc_visible = _is_rotation_arc_visible();
4612 int show_gizmo_flags = EDITOR_GET("editors/3d/show_gizmo_during_rotation");
4613
4614 bool keep_gizmo_visible = arc_visible && ((local_coords && (show_gizmo_flags & Node3DEditor::TRANSFORM_MODE_LOCAL)) || (!local_coords && (show_gizmo_flags & Node3DEditor::TRANSFORM_MODE_GLOBAL)));
4615 bool hide_gizmo_during_rotation = arc_visible && !keep_gizmo_visible;
4616
4617 int arc_replaces_ring = -1;
4618 if (keep_gizmo_visible) {
4619 switch (_edit.plane) {
4620 case TRANSFORM_X_AXIS:
4621 arc_replaces_ring = 0;
4622 break;
4623 case TRANSFORM_Y_AXIS:
4624 arc_replaces_ring = 1;
4625 break;
4626 case TRANSFORM_Z_AXIS:
4627 arc_replaces_ring = 2;
4628 break;
4629 case TRANSFORM_VIEW:
4630 arc_replaces_ring = 3;
4631 break;
4632 default:
4633 break;
4634 }
4635 }
4636
4637 bool show_gizmo = spatial_editor->is_gizmo_visible() && !_edit.instant && transform_gizmo_visible && !collision_reposition && !hide_gizmo_during_rotation;
4638 bool show_rotate_gizmo = show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_TRANSFORM || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_ROTATE);
4639
4640 for (int i = 0; i < 3; i++) {
4641 Transform3D axis_angle;
4642 if (xform.basis.get_column(i).normalized().dot(xform.basis.get_column((i + 1) % 3).normalized()) < 1.0) {
4643 axis_angle = axis_angle.looking_at(xform.basis.get_column(i).normalized(), xform.basis.get_column((i + 1) % 3).normalized());
4644 }
4645 axis_angle.basis.scale(scale);
4646 axis_angle.origin = xform.origin;
4647 RenderingServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], axis_angle);
4648 RenderingServer::get_singleton()->instance_set_visible(move_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_TRANSFORM || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE));
4649 RenderingServer::get_singleton()->instance_set_transform(move_plane_gizmo_instance[i], axis_angle);
4650 RenderingServer::get_singleton()->instance_set_visible(move_plane_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_TRANSFORM || spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_MOVE));
4651 RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], axis_angle);
4652 RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[i], show_rotate_gizmo && i != arc_replaces_ring);
4653 RenderingServer::get_singleton()->instance_set_transform(scale_gizmo_instance[i], axis_angle);
4654 RenderingServer::get_singleton()->instance_set_visible(scale_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
4655 RenderingServer::get_singleton()->instance_set_transform(scale_plane_gizmo_instance[i], axis_angle);
4656 RenderingServer::get_singleton()->instance_set_visible(scale_plane_gizmo_instance[i], show_gizmo && (spatial_editor->get_tool_mode() == Node3DEditor::TOOL_MODE_SCALE));
4657 RenderingServer::get_singleton()->instance_set_transform(axis_gizmo_instance[i], xform);
4658 }
4659
4660 Transform3D view_rotation_xform = xform;
4661 view_rotation_xform.orthonormalize();
4662 bool shrink_view_ring = arc_replaces_ring >= 0 && arc_replaces_ring < 3;
4663 Vector3 view_ring_scale = shrink_view_ring ? scale * (GIZMO_CIRCLE_SIZE / GIZMO_VIEW_ROTATION_SIZE) : scale;
4664 view_rotation_xform.basis.scale(view_ring_scale);
4665 RenderingServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[3], view_rotation_xform);
4666 RenderingServer::get_singleton()->instance_set_visible(rotate_gizmo_instance[3], show_rotate_gizmo && arc_replaces_ring != 3);
4667
4668 bool show_axes = spatial_editor->is_gizmo_visible() && _edit.mode != TRANSFORM_NONE;
4669 RenderingServer *rs = RenderingServer::get_singleton();
4670 rs->instance_set_visible(axis_gizmo_instance[0], show_axes && (_edit.plane == TRANSFORM_X_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_XZ));
4671 rs->instance_set_visible(axis_gizmo_instance[1], show_axes && (_edit.plane == TRANSFORM_Y_AXIS || _edit.plane == TRANSFORM_XY || _edit.plane == TRANSFORM_YZ));
4672 rs->instance_set_visible(axis_gizmo_instance[2], show_axes && (_edit.plane == TRANSFORM_Z_AXIS || _edit.plane == TRANSFORM_XZ || _edit.plane == TRANSFORM_YZ));
4673 }
4674
4675 void Node3DEditorViewport::set_state(const Dictionary &p_state) {
4676 if (p_state.has("position")) {
4677 cursor.pos = p_state["position"];
4678 }
4679 if (p_state.has("x_rotation")) {
4680 cursor.x_rot = p_state["x_rotation"];
4681 cursor.unsnapped_x_rot = cursor.x_rot;
4682 }
4683 if (p_state.has("y_rotation")) {
4684 cursor.y_rot = p_state["y_rotation"];
4685 cursor.unsnapped_y_rot = cursor.y_rot;
4686 }
4687 if (p_state.has("distance")) {
4688 cursor.distance = p_state["distance"];
4689 }
4690 if (p_state.has("orthogonal")) {
4691 bool orth = p_state["orthogonal"];
4692 _menu_option(orth ? VIEW_ORTHOGONAL : VIEW_PERSPECTIVE);
4693 }
4694 if (p_state.has("view_type")) {
4695 view_type = ViewType(p_state["view_type"].operator int());
4696 _update_name();
4697 }
4698 if (p_state.has("auto_orthogonal")) {
4699 auto_orthogonal = p_state["auto_orthogonal"];
4700 _update_name();
4701 }
4702 if (p_state.has("auto_orthogonal_enabled")) {
4703 bool enabled = p_state["auto_orthogonal_enabled"];
4704 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), enabled);
4705 }
4706 if (p_state.has("display_mode")) {
4707 int display = p_state["display_mode"];
4708
4709 int idx = view_display_menu->get_popup()->get_item_index(display);
4710 if (idx != -1 && !view_display_menu->get_popup()->is_item_checked(idx)) {
4711 _menu_option(display);
4712 } else {
4713 idx = display_submenu->get_item_index(display);
4714 if (idx != -1 && !display_submenu->is_item_checked(idx)) {
4715 _menu_option(display);
4716 }
4717 }
4718 }
4719 if (p_state.has("lock_rotation")) {
4720 _set_lock_view_rotation(p_state["lock_rotation"]);
4721 }
4722 if (p_state.has("use_environment")) {
4723 bool env = p_state["use_environment"];
4724
4725 if (env != camera->get_environment().is_valid()) {
4726 _menu_option(VIEW_ENVIRONMENT);
4727 }
4728 }
4729 if (p_state.has("listener")) {
4730 bool listener = p_state["listener"];
4731
4732 int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
4733 viewport->set_as_audio_listener_3d(listener);
4734 view_display_menu->get_popup()->set_item_checked(idx, listener);
4735 }
4736 if (p_state.has("doppler")) {
4737 bool doppler = p_state["doppler"];
4738
4739 int idx = view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER);
4740 camera->set_doppler_tracking(doppler ? Camera3D::DOPPLER_TRACKING_IDLE_STEP : Camera3D::DOPPLER_TRACKING_DISABLED);
4741 view_display_menu->get_popup()->set_item_checked(idx, doppler);
4742 }
4743 if (p_state.has("gizmos")) {
4744 bool gizmos = p_state["gizmos"];
4745
4746 int idx = view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS);
4747 if (view_display_menu->get_popup()->is_item_checked(idx) != gizmos) {
4748 _menu_option(VIEW_GIZMOS);
4749 }
4750 }
4751 if (p_state.has("transform_gizmo")) {
4752 bool transform_gizmo = p_state["transform_gizmo"];
4753
4754 int idx = view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO);
4755 if (view_display_menu->get_popup()->is_item_checked(idx) != transform_gizmo) {
4756 _menu_option(VIEW_TRANSFORM_GIZMO);
4757 }
4758 }
4759 if (p_state.has("grid")) {
4760 bool grid = p_state["grid"];
4761
4762 int idx = view_display_menu->get_popup()->get_item_index(VIEW_GRID);
4763 if (view_display_menu->get_popup()->is_item_checked(idx) != grid) {
4764 _menu_option(VIEW_GRID);
4765 }
4766 }
4767 if (p_state.has("information")) {
4768 bool information = p_state["information"];
4769
4770 int idx = view_display_menu->get_popup()->get_item_index(VIEW_INFORMATION);
4771 if (view_display_menu->get_popup()->is_item_checked(idx) != information) {
4772 _menu_option(VIEW_INFORMATION);
4773 }
4774 }
4775 if (p_state.has("frame_time")) {
4776 bool fps = p_state["frame_time"];
4777
4778 int idx = view_display_menu->get_popup()->get_item_index(VIEW_FRAME_TIME);
4779 if (view_display_menu->get_popup()->is_item_checked(idx) != fps) {
4780 _menu_option(VIEW_FRAME_TIME);
4781 }
4782 }
4783 if (p_state.has("half_res")) {
4784 bool half_res = p_state["half_res"];
4785
4786 int idx = view_display_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION);
4787 view_display_menu->get_popup()->set_item_checked(idx, half_res);
4788 _update_shrink();
4789 }
4790 if (p_state.has("cinematic_preview")) {
4791 previewing_cinema = p_state["cinematic_preview"];
4792
4793 int idx = view_display_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW);
4794 view_display_menu->get_popup()->set_item_checked(idx, previewing_cinema);
4795
4796 cinema_label->set_visible(previewing_cinema);
4797 if (previewing_cinema) {
4798 _update_centered_labels();
4799 surface->queue_redraw();
4800 }
4801 }
4802
4803 if (preview_camera->is_connected(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview))) {
4804 preview_camera->disconnect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
4805 }
4806 if (p_state.has("previewing")) {
4807 Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
4808 if (Object::cast_to<Camera3D>(pv)) {
4809 previewing = Object::cast_to<Camera3D>(pv);
4810 previewing->connect(SceneStringName(tree_exiting), callable_mp(this, &Node3DEditorViewport::_preview_exited_scene));
4811 previewing->connect(CoreStringName(property_list_changed), callable_mp(this, &Node3DEditorViewport::_preview_camera_property_changed));
4812 RS::get_singleton()->viewport_attach_camera(viewport->get_viewport_rid(), previewing->get_camera()); //replace
4813 surface->queue_redraw();
4814 previewing_camera = true;
4815 _update_navigation_controls_visibility();
4816 preview_camera->set_pressed(true);
4817 preview_camera->show();
4818 }
4819 }
4820 preview_camera->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
4821 }
4822
4823 Dictionary Node3DEditorViewport::get_state() const {
4824 Dictionary d;
4825 d["position"] = cursor.pos;
4826 d["x_rotation"] = cursor.x_rot;
4827 d["y_rotation"] = cursor.y_rot;
4828 d["distance"] = cursor.distance;
4829 d["use_environment"] = camera->get_environment().is_valid();
4830 d["orthogonal"] = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
4831 d["view_type"] = view_type;
4832 d["auto_orthogonal"] = auto_orthogonal;
4833 d["auto_orthogonal_enabled"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL));
4834
4835 // Find selected display mode.
4836 int display_mode = VIEW_DISPLAY_NORMAL;
4837 for (int i = VIEW_DISPLAY_NORMAL; i < VIEW_DISPLAY_ADVANCED; i++) {
4838 if (view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(i))) {
4839 display_mode = i;
4840 break;
4841 }
4842 }
4843 for (int i = VIEW_DISPLAY_ADVANCED + 1; i < VIEW_DISPLAY_MAX; i++) {
4844 if (display_submenu->is_item_checked(display_submenu->get_item_index(i))) {
4845 display_mode = i;
4846 break;
4847 }
4848 }
4849 d["display_mode"] = display_mode;
4850
4851 d["listener"] = viewport->is_audio_listener_3d();
4852 d["doppler"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_DOPPLER));
4853 d["gizmos"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS));
4854 d["transform_gizmo"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO));
4855 d["grid"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_GRID));
4856 d["information"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_INFORMATION));
4857 d["frame_time"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_FRAME_TIME));
4858 d["half_res"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_HALF_RESOLUTION));
4859 d["cinematic_preview"] = view_display_menu->get_popup()->is_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_CINEMATIC_PREVIEW));
4860 if (previewing) {
4861 d["previewing"] = EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
4862 }
4863 d["lock_rotation"] = lock_rotation;
4864
4865 return d;
4866 }
4867
4868 void Node3DEditorViewport::_bind_methods() {
4869 ADD_SIGNAL(MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")));
4870 ADD_SIGNAL(MethodInfo("clicked"));
4871 }
4872
4873 void Node3DEditorViewport::reset() {
4874 orthogonal = false;
4875 auto_orthogonal = false;
4876 lock_rotation = false;
4877 message_time = 0;
4878 message = "";
4879 last_message = "";
4880 view_type = VIEW_TYPE_USER;
4881
4882 cursor = Cursor();
4883 _update_name();
4884 }
4885
4886 void Node3DEditorViewport::focus_selection() {
4887 Vector3 center;
4888 int count = 0;
4889
4890 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
4891
4892 for (Node *node : selection) {
4893 Node3D *node_3d = Object::cast_to<Node3D>(node);
4894 if (!node_3d) {
4895 continue;
4896 }
4897
4898 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(node_3d);
4899 if (!se) {
4900 continue;
4901 }
4902
4903 if (se->gizmo.is_valid()) {
4904 for (const KeyValue<int, Transform3D> &GE : se->subgizmos) {
4905 const Vector3 pos = node_3d->get_global_gizmo_transform().xform(se->gizmo->get_subgizmo_transform(GE.key).origin);
4906 if (pos.is_finite()) {
4907 center += pos;
4908 count++;
4909 }
4910 }
4911 } else {
4912 const Vector3 pos = node_3d->get_global_gizmo_transform().origin;
4913 if (pos.is_finite()) {
4914 center += pos;
4915 count++;
4916 }
4917 }
4918 }
4919
4920 if (count > 1) {
4921 center /= count;
4922 }
4923
4924 cursor.pos = center;
4925 }
4926
4927 void Node3DEditorViewport::assign_pending_data_pointers(Node3D *p_preview_node, AABB *p_preview_bounds, AcceptDialog *p_accept) {
4928 preview_node = p_preview_node;
4929 preview_bounds = p_preview_bounds;
4930 accept = p_accept;
4931 }
4932
4933 void _insert_rid_recursive(Node *node, HashSet<RID> &rids) {
4934 CollisionObject3D *co = Object::cast_to<CollisionObject3D>(node);
4935
4936 if (co) {
4937 rids.insert(co->get_rid());
4938 } else if (node->is_class("CSGShape3D")) { // HACK: We should avoid referencing module logic.
4939 rids.insert(node->call("_get_root_collision_instance"));
4940 }
4941
4942 for (int i = 0; i < node->get_child_count(); i++) {
4943 Node *child = node->get_child(i);
4944 _insert_rid_recursive(child, rids);
4945 }
4946 }
4947
4948 Vector3 Node3DEditorViewport::_get_instance_position(const Point2 &p_pos, Node3D *p_node) const {
4949 const float MAX_DISTANCE = 50.0;
4950 const float FALLBACK_DISTANCE = 5.0;
4951
4952 Vector3 world_ray = get_ray(p_pos);
4953 Vector3 world_pos = get_ray_pos(p_pos);
4954
4955 PhysicsDirectSpaceState3D *ss = get_tree()->get_root()->get_world_3d()->get_direct_space_state();
4956
4957 HashSet<RID> rids;
4958
4959 if (preview_node && preview_node->get_child_count() > 0) {
4960 _insert_rid_recursive(preview_node, rids);
4961 } else if (!preview_node->is_inside_tree() && !ruler->is_inside_tree()) {
4962 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
4963
4964 Node3D *first_selected_node = Object::cast_to<Node3D>(selection.front()->get());
4965
4966 if (first_selected_node) {
4967 _insert_rid_recursive(first_selected_node, rids);
4968 }
4969 }
4970
4971 PhysicsDirectSpaceState3D::RayParameters ray_params;
4972 ray_params.exclude = rids;
4973 ray_params.from = world_pos;
4974 ray_params.to = world_pos + world_ray * camera->get_far();
4975
4976 PhysicsDirectSpaceState3D::RayResult result;
4977 if (ss->intersect_ray(ray_params, result) && (preview_node->get_child_count() > 0 || !preview_node->is_inside_tree())) {
4978 // Calculate an offset for the `p_node` such that the its bounding box is on top of and touching the contact surface's plane.
4979
4980 // Use the Gram-Schmidt process to get an orthonormal Basis aligned with the surface normal.
4981 const Vector3 bb_basis_x = result.normal;
4982 Vector3 bb_basis_y = Vector3(0, 1, 0);
4983 bb_basis_y = bb_basis_y - bb_basis_y.project(bb_basis_x);
4984 if (bb_basis_y.is_zero_approx()) {
4985 bb_basis_y = Vector3(0, 0, 1);
4986 bb_basis_y = bb_basis_y - bb_basis_y.project(bb_basis_x);
4987 }
4988 bb_basis_y = bb_basis_y.normalized();
4989 const Vector3 bb_basis_z = bb_basis_x.cross(bb_basis_y);
4990 const Basis bb_basis = Basis(bb_basis_x, bb_basis_y, bb_basis_z);
4991
4992 // This normal-aligned Basis allows us to create an AABB that can fit on the surface plane as snugly as possible.
4993 const Transform3D bb_transform = Transform3D(bb_basis, p_node->get_global_transform().origin);
4994 const AABB p_node_bb = _calculate_spatial_bounds(p_node, true, &bb_transform);
4995 // The x-axis's alignment with the surface normal also makes it trivial to get the distance from `p_node`'s origin at (0, 0, 0) to the correct AABB face.
4996 const float offset_distance = -p_node_bb.position.x;
4997
4998 // `result_offset` is in global space.
4999 const Vector3 result_offset = result.position + result.normal * offset_distance;
5000
5001 return result_offset;
5002 }
5003
5004 const bool is_orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
5005
5006 // The XZ plane.
5007 Vector3 intersection;
5008 Plane plane(Vector3(0, 1, 0));
5009 if (plane.intersects_ray(world_pos, world_ray, &intersection)) {
5010 if (is_orthogonal || world_pos.distance_to(intersection) <= MAX_DISTANCE) {
5011 return intersection;
5012 }
5013 }
5014
5015 // Plane facing the camera using fallback distance.
5016 if (is_orthogonal) {
5017 plane = Plane(world_ray, cursor.pos - world_ray * (cursor.distance - FALLBACK_DISTANCE));
5018 } else {
5019 plane = Plane(world_ray, world_pos + world_ray * FALLBACK_DISTANCE);
5020 }
5021 if (plane.intersects_ray(world_pos, world_ray, &intersection)) {
5022 return intersection;
5023 }
5024
5025 // Not likely, but just in case...
5026 return world_pos + world_ray * FALLBACK_DISTANCE;
5027 }
5028
5029 AABB Node3DEditorViewport::_calculate_spatial_bounds(const Node3D *p_parent, bool p_omit_top_level, const Transform3D *p_bounds_orientation) {
5030 if (!p_parent) {
5031 return AABB(Vector3(-0.2, -0.2, -0.2), Vector3(0.4, 0.4, 0.4));
5032 }
5033 const Transform3D parent_transform = p_parent->get_global_transform();
5034 if (!parent_transform.is_finite()) {
5035 return AABB();
5036 }
5037 AABB bounds;
5038
5039 Transform3D bounds_orientation;
5040 Transform3D xform_to_top_level_parent_space;
5041 if (p_bounds_orientation) {
5042 bounds_orientation = *p_bounds_orientation;
5043 xform_to_top_level_parent_space = bounds_orientation.affine_inverse() * parent_transform;
5044 } else {
5045 bounds_orientation = parent_transform;
5046 }
5047
5048 const VisualInstance3D *visual_instance = Object::cast_to<VisualInstance3D>(p_parent);
5049 if (visual_instance) {
5050 bounds = visual_instance->get_aabb();
5051 } else {
5052 bounds = AABB();
5053 }
5054 bounds = xform_to_top_level_parent_space.xform(bounds);
5055
5056 for (int i = 0; i < p_parent->get_child_count(); i++) {
5057 const Node3D *child = Object::cast_to<Node3D>(p_parent->get_child(i));
5058 if (child && !(p_omit_top_level && child->is_set_as_top_level())) {
5059 const AABB child_bounds = _calculate_spatial_bounds(child, p_omit_top_level, &bounds_orientation);
5060 bounds.merge_with(child_bounds);
5061 }
5062 }
5063
5064 return bounds;
5065 }
5066
5067 Node *Node3DEditorViewport::_sanitize_preview_node(Node *p_node) const {
5068 Node3D *node_3d = Object::cast_to<Node3D>(p_node);
5069 if (node_3d == nullptr) {
5070 Node3D *replacement_node = memnew(Node3D);
5071 replacement_node->set_name(p_node->get_name());
5072 p_node->replace_by(replacement_node);
5073 memdelete(p_node);
5074 p_node = replacement_node;
5075 } else {
5076 VisualInstance3D *visual_instance = Object::cast_to<VisualInstance3D>(node_3d);
5077 if (visual_instance == nullptr) {
5078 Node3D *replacement_node = memnew(Node3D);
5079 replacement_node->set_name(node_3d->get_name());
5080 replacement_node->set_visible(node_3d->is_visible());
5081 replacement_node->set_transform(node_3d->get_transform());
5082 replacement_node->set_rotation_edit_mode(node_3d->get_rotation_edit_mode());
5083 replacement_node->set_rotation_order(node_3d->get_rotation_order());
5084 replacement_node->set_as_top_level(node_3d->is_set_as_top_level());
5085 p_node->replace_by(replacement_node);
5086 memdelete(p_node);
5087 p_node = replacement_node;
5088 }
5089 }
5090
5091 for (int i = 0; i < p_node->get_child_count(); i++) {
5092 _sanitize_preview_node(p_node->get_child(i));
5093 }
5094
5095 return p_node;
5096 }
5097
5098 void Node3DEditorViewport::_create_preview_node(const Vector<String> &files) const {
5099 bool add_preview = false;
5100 for (const String &path : files) {
5101 Ref<Resource> res = ResourceLoader::load(path);
5102 ERR_CONTINUE(res.is_null());
5103
5104 Ref<PackedScene> scene = res;
5105 if (scene.is_valid()) {
5106 Node *instance = scene->instantiate();
5107 if (instance) {
5108 instance = _sanitize_preview_node(instance);
5109 preview_node->add_child(instance);
5110 Node3D *node_3d = Object::cast_to<Node3D>(instance);
5111 if (node_3d) {
5112 node_3d->set_as_top_level(false);
5113 }
5114 }
5115 add_preview = true;
5116 }
5117
5118 Ref<Mesh> mesh = res;
5119 if (mesh.is_valid()) {
5120 MeshInstance3D *mesh_instance = memnew(MeshInstance3D);
5121 mesh_instance->set_mesh(mesh);
5122 preview_node->add_child(mesh_instance);
5123 add_preview = true;
5124 }
5125
5126 Ref<AudioStream> audio = res;
5127 if (audio.is_valid()) {
5128 Sprite3D *sprite = memnew(Sprite3D);
5129 sprite->set_texture(get_editor_theme_icon(SNAME("Gizmo3DSamplePlayer")));
5130 sprite->set_billboard_mode(StandardMaterial3D::BILLBOARD_ENABLED);
5131 sprite->set_pixel_size(0.005);
5132 preview_node->add_child(sprite);
5133 add_preview = true;
5134 }
5135 }
5136 if (add_preview) {
5137 EditorNode::get_singleton()->get_scene_root()->add_child(preview_node);
5138 }
5139
5140 *preview_bounds = _calculate_spatial_bounds(preview_node);
5141 }
5142
5143 void Node3DEditorViewport::_remove_preview_node() {
5144 set_message("");
5145 if (preview_node->get_parent()) {
5146 for (int i = preview_node->get_child_count() - 1; i >= 0; i--) {
5147 Node *node = preview_node->get_child(i);
5148 node->queue_free();
5149 preview_node->remove_child(node);
5150 }
5151 EditorNode::get_singleton()->get_scene_root()->remove_child(preview_node);
5152 }
5153 }
5154
5155 bool Node3DEditorViewport::_apply_preview_material(ObjectID p_target, const Point2 &p_point) const {
5156 _reset_preview_material();
5157
5158 if (p_target.is_null()) {
5159 return false;
5160 }
5161
5162 spatial_editor->set_preview_material_target(p_target);
5163
5164 Object *target_inst = ObjectDB::get_instance(p_target);
5165
5166 bool is_ctrl = Input::get_singleton()->is_key_pressed(Key::CTRL);
5167
5168 MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(target_inst);
5169 if (is_ctrl && mesh_instance) {
5170 Ref<Mesh> mesh = mesh_instance->get_mesh();
5171 int surface_count = mesh->get_surface_count();
5172
5173 Vector3 world_ray = get_ray(p_point);
5174 Vector3 world_pos = get_ray_pos(p_point);
5175
5176 int closest_surface = -1;
5177 float closest_dist = 1e20;
5178
5179 Transform3D gt = mesh_instance->get_global_transform();
5180
5181 Transform3D ai = gt.affine_inverse();
5182 Vector3 xform_ray = ai.basis.xform(world_ray).normalized();
5183 Vector3 xform_pos = ai.xform(world_pos);
5184
5185 for (int surface_idx = 0; surface_idx < surface_count; surface_idx++) {
5186 Ref<TriangleMesh> surface_mesh = mesh->generate_surface_triangle_mesh(surface_idx);
5187
5188 Vector3 rpos, rnorm;
5189 if (surface_mesh->intersect_ray(xform_pos, xform_ray, rpos, rnorm)) {
5190 Vector3 hitpos = gt.xform(rpos);
5191
5192 const real_t dist = world_pos.distance_to(hitpos);
5193
5194 if (dist < 0) {
5195 continue;
5196 }
5197
5198 if (dist < closest_dist) {
5199 closest_surface = surface_idx;
5200 closest_dist = dist;
5201 }
5202 }
5203 }
5204
5205 if (closest_surface == -1) {
5206 return false;
5207 }
5208
5209 spatial_editor->set_preview_material_surface(closest_surface);
5210 spatial_editor->set_preview_reset_material(mesh_instance->get_surface_override_material(closest_surface));
5211 mesh_instance->set_surface_override_material(closest_surface, spatial_editor->get_preview_material());
5212
5213 return true;
5214 }
5215
5216 GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(target_inst);
5217 if (geometry_instance) {
5218 spatial_editor->set_preview_material_surface(-1);
5219 spatial_editor->set_preview_reset_material(geometry_instance->get_material_override());
5220 geometry_instance->set_material_override(spatial_editor->get_preview_material());
5221 return true;
5222 }
5223
5224 return false;
5225 }
5226
5227 void Node3DEditorViewport::_reset_preview_material() const {
5228 ObjectID last_target = spatial_editor->get_preview_material_target();
5229 if (last_target.is_null()) {
5230 return;
5231 }
5232 Object *last_target_inst = ObjectDB::get_instance(last_target);
5233
5234 MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(last_target_inst);
5235 GeometryInstance3D *geometry_instance = Object::cast_to<GeometryInstance3D>(last_target_inst);
5236 if (mesh_instance && spatial_editor->get_preview_material_surface() != -1) {
5237 mesh_instance->set_surface_override_material(spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
5238 } else if (geometry_instance) {
5239 geometry_instance->set_material_override(spatial_editor->get_preview_reset_material());
5240 }
5241 }
5242
5243 void Node3DEditorViewport::_remove_preview_material() {
5244 preview_material_label->hide();
5245 preview_material_label_desc->hide();
5246
5247 spatial_editor->set_preview_material(Ref<Material>());
5248 spatial_editor->set_preview_reset_material(Ref<Material>());
5249 spatial_editor->set_preview_material_target(ObjectID());
5250 spatial_editor->set_preview_material_surface(-1);
5251 }
5252
5253 bool Node3DEditorViewport::_cyclical_dependency_exists(const String &p_target_scene_path, Node *p_desired_node) const {
5254 if (p_desired_node->get_scene_file_path() == p_target_scene_path) {
5255 return true;
5256 }
5257
5258 int childCount = p_desired_node->get_child_count();
5259 for (int i = 0; i < childCount; i++) {
5260 Node *child = p_desired_node->get_child(i);
5261 if (_cyclical_dependency_exists(p_target_scene_path, child)) {
5262 return true;
5263 }
5264 }
5265 return false;
5266 }
5267
5268 bool Node3DEditorViewport::_create_instance(Node *p_parent, const String &p_path, const Point2 &p_point) {
5269 Ref<Resource> res = ResourceLoader::load(p_path);
5270 ERR_FAIL_COND_V(res.is_null(), false);
5271
5272 Ref<PackedScene> scene = res;
5273 Ref<Mesh> mesh = res;
5274
5275 Node *instantiated_scene = nullptr;
5276
5277 if (mesh.is_valid() || scene.is_valid()) {
5278 if (mesh.is_valid()) {
5279 MeshInstance3D *mesh_instance = memnew(MeshInstance3D);
5280 mesh_instance->set_mesh(mesh);
5281
5282 // Adjust casing according to project setting. The file name is expected to be in snake_case, but will work for others.
5283 const String &node_name = Node::adjust_name_casing(p_path.get_file().get_basename());
5284 if (!node_name.is_empty()) {
5285 mesh_instance->set_name(node_name);
5286 }
5287
5288 instantiated_scene = mesh_instance;
5289 } else {
5290 if (scene.is_null()) { // invalid scene
5291 return false;
5292 } else {
5293 instantiated_scene = scene->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
5294 }
5295 }
5296 }
5297
5298 if (instantiated_scene == nullptr) {
5299 return false;
5300 }
5301
5302 if (!EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path().is_empty()) { // Cyclic instantiation.
5303 if (_cyclical_dependency_exists(EditorNode::get_singleton()->get_edited_scene()->get_scene_file_path(), instantiated_scene)) {
5304 memdelete(instantiated_scene);
5305 return false;
5306 }
5307 }
5308
5309 if (scene.is_valid()) {
5310 instantiated_scene->set_scene_file_path(ProjectSettings::get_singleton()->localize_path(p_path));
5311 }
5312
5313 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
5314 undo_redo->add_do_method(p_parent, "add_child", instantiated_scene, true);
5315 undo_redo->add_do_method(instantiated_scene, "set_owner", EditorNode::get_singleton()->get_edited_scene());
5316 undo_redo->add_do_reference(instantiated_scene);
5317 undo_redo->add_undo_method(p_parent, "remove_child", instantiated_scene);
5318 undo_redo->add_do_method(editor_selection, "add_node", instantiated_scene);
5319
5320 String new_name = p_parent->validate_child_name(instantiated_scene);
5321 EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
5322 undo_redo->add_do_method(ed, "live_debug_instantiate_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent), p_path, new_name);
5323 undo_redo->add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent)) + "/" + new_name));
5324
5325 Node3D *node3d = Object::cast_to<Node3D>(instantiated_scene);
5326 if (node3d) {
5327 Transform3D parent_tf;
5328 Node3D *parent_node3d = Object::cast_to<Node3D>(p_parent);
5329 if (parent_node3d) {
5330 parent_tf = parent_node3d->get_global_gizmo_transform();
5331 }
5332
5333 Transform3D new_tf = node3d->get_transform();
5334 if (node3d->is_set_as_top_level()) {
5335 new_tf.origin += preview_node_pos;
5336 } else {
5337 new_tf.origin = parent_tf.affine_inverse().xform(preview_node_pos + node3d->get_position());
5338 new_tf.basis = parent_tf.affine_inverse().basis * new_tf.basis;
5339 }
5340
5341 undo_redo->add_do_method(instantiated_scene, "set_transform", new_tf);
5342 }
5343
5344 return true;
5345 }
5346
5347 bool Node3DEditorViewport::_create_audio_node(Node *p_parent, const String &p_path, const Point2 &p_point) {
5348 Ref<AudioStream> audio = ResourceLoader::load(p_path);
5349 ERR_FAIL_COND_V(audio.is_null(), false);
5350
5351 AudioStreamPlayer3D *audio_player = memnew(AudioStreamPlayer3D);
5352 audio_player->set_stream(audio);
5353
5354 // Adjust casing according to project setting. The file name is expected to be in snake_case, but will work for others.
5355 const String &node_name = Node::adjust_name_casing(p_path.get_file().get_basename());
5356 if (!node_name.is_empty()) {
5357 audio_player->set_name(node_name);
5358 }
5359
5360 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
5361 undo_redo->add_do_method(p_parent, "add_child", audio_player, true);
5362 undo_redo->add_do_method(audio_player, "set_owner", EditorNode::get_singleton()->get_edited_scene());
5363 undo_redo->add_do_reference(audio_player);
5364 undo_redo->add_undo_method(p_parent, "remove_child", audio_player);
5365 undo_redo->add_do_method(editor_selection, "add_node", audio_player);
5366
5367 const String new_name = p_parent->validate_child_name(audio_player);
5368 EditorDebuggerNode *ed = EditorDebuggerNode::get_singleton();
5369 undo_redo->add_do_method(ed, "live_debug_create_node", EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent), audio_player->get_class(), new_name);
5370 undo_redo->add_undo_method(ed, "live_debug_remove_node", NodePath(String(EditorNode::get_singleton()->get_edited_scene()->get_path_to(p_parent)) + "/" + new_name));
5371
5372 Transform3D parent_tf;
5373 Node3D *parent_node3d = Object::cast_to<Node3D>(p_parent);
5374 if (parent_node3d) {
5375 parent_tf = parent_node3d->get_global_gizmo_transform();
5376 }
5377
5378 Transform3D new_tf = audio_player->get_transform();
5379 new_tf.origin = parent_tf.affine_inverse().xform(preview_node_pos + audio_player->get_position());
5380 new_tf.basis = parent_tf.affine_inverse().basis * new_tf.basis;
5381
5382 undo_redo->add_do_method(audio_player, "set_transform", new_tf);
5383
5384 return true;
5385 }
5386
5387 void Node3DEditorViewport::_perform_drop_data() {
5388 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
5389 if (spatial_editor->get_preview_material_target().is_valid()) {
5390 GeometryInstance3D *geometry_instance = ObjectDB::get_instance<GeometryInstance3D>(spatial_editor->get_preview_material_target());
5391 MeshInstance3D *mesh_instance = ObjectDB::get_instance<MeshInstance3D>(spatial_editor->get_preview_material_target());
5392 if (mesh_instance && spatial_editor->get_preview_material_surface() != -1) {
5393 undo_redo->create_action(vformat(TTR("Set Surface %d Override Material"), spatial_editor->get_preview_material_surface()));
5394 undo_redo->add_do_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_material());
5395 undo_redo->add_undo_method(geometry_instance, "set_surface_override_material", spatial_editor->get_preview_material_surface(), spatial_editor->get_preview_reset_material());
5396 undo_redo->commit_action();
5397 } else if (geometry_instance) {
5398 undo_redo->create_action(TTR("Set Material Override"));
5399 undo_redo->add_do_method(geometry_instance, "set_material_override", spatial_editor->get_preview_material());
5400 undo_redo->add_undo_method(geometry_instance, "set_material_override", spatial_editor->get_preview_reset_material());
5401 undo_redo->commit_action();
5402 }
5403
5404 _remove_preview_material();
5405 return;
5406 }
5407
5408 _remove_preview_node();
5409
5410 PackedStringArray error_files;
5411
5412 undo_redo->create_action(TTR("Create Node"), UndoRedo::MERGE_DISABLE, target_node);
5413 undo_redo->add_do_method(editor_selection, "clear");
5414
5415 for (int i = 0; i < selected_files.size(); i++) {
5416 String path = selected_files[i];
5417 Ref<Resource> res = ResourceLoader::load(path);
5418 if (res.is_null()) {
5419 continue;
5420 }
5421
5422 Ref<PackedScene> scene = res;
5423 Ref<Mesh> mesh = res;
5424 if (mesh.is_valid() || scene.is_valid()) {
5425 if (!_create_instance(target_node, path, drop_pos)) {
5426 error_files.push_back(path.get_file());
5427 }
5428 }
5429
5430 Ref<AudioStream> audio = res;
5431 if (audio.is_valid()) {
5432 if (!_create_audio_node(target_node, path, drop_pos)) {
5433 error_files.push_back(path.get_file());
5434 }
5435 }
5436 }
5437
5438 undo_redo->commit_action();
5439
5440 if (error_files.size() > 0) {
5441 accept->set_text(vformat(TTR("Error instantiating scene from %s."), String(", ").join(error_files)));
5442 accept->popup_centered();
5443 }
5444 }
5445
5446 bool Node3DEditorViewport::can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
5447 if (p_point == Vector2(Math::INF, Math::INF)) {
5448 return false;
5449 }
5450 preview_node_viewport_pos = p_point;
5451
5452 bool can_instantiate = false;
5453 bool is_cyclical_dep = false;
5454 String error_file;
5455
5456 if (!preview_node->is_inside_tree() && spatial_editor->get_preview_material().is_null()) {
5457 Dictionary d = p_data;
5458 if (d.has("type") && (String(d["type"]) == "files")) {
5459 Vector<String> files = d["files"];
5460
5461 // Track whether a type other than PackedScene is valid to stop checking them and only
5462 // continue to check if the rest of the scenes are valid (don't have cyclic dependencies).
5463 bool is_other_valid = false;
5464 // Check if at least one of the dragged files is a mesh, material, texture or scene.
5465 for (int i = 0; i < files.size(); i++) {
5466 const String &res_type = ResourceLoader::get_resource_type(files[i]);
5467 bool is_scene = ClassDB::is_parent_class(res_type, "PackedScene");
5468 bool is_mesh = ClassDB::is_parent_class(res_type, "Mesh");
5469 bool is_material = ClassDB::is_parent_class(res_type, "Material");
5470 bool is_texture = ClassDB::is_parent_class(res_type, "Texture");
5471 bool is_audio = ClassDB::is_parent_class(res_type, "AudioStream");
5472
5473 if (is_mesh || is_scene || is_material || is_texture || is_audio) {
5474 Ref<Resource> res = ResourceLoader::load(files[i]);
5475 if (res.is_null()) {
5476 continue;
5477 }
5478 Ref<PackedScene> scn = res;
5479 Ref<Mesh> mesh = res;
5480 Ref<Material> mat = res;
5481 Ref<Texture2D> tex = res;
5482 Ref<AudioStream> audio = res;
5483 if (scn.is_valid()) {
5484 Node *instantiated_scene = scn->instantiate(PackedScene::GEN_EDIT_STATE_INSTANCE);
5485 if (!instantiated_scene) {
5486 continue;
5487 }
5488 Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
5489 if (edited_scene && !edited_scene->get_scene_file_path().is_empty() && _cyclical_dependency_exists(edited_scene->get_scene_file_path(), instantiated_scene)) {
5490 memdelete(instantiated_scene);
5491 can_instantiate = false;
5492 is_cyclical_dep = true;
5493 error_file = files[i].get_file();
5494 break;
5495 }
5496 memdelete(instantiated_scene);
5497 } else if (!is_other_valid && mat.is_valid()) {
5498 Ref<BaseMaterial3D> base_mat = res;
5499 Ref<ShaderMaterial> shader_mat = res;
5500
5501 if (base_mat.is_null() && shader_mat.is_null()) {
5502 continue;
5503 }
5504
5505 spatial_editor->set_preview_material(mat);
5506 is_other_valid = true;
5507 continue;
5508 } else if (!is_other_valid && mesh.is_valid()) {
5509 // Let the mesh pass.
5510 is_other_valid = true;
5511 } else if (!is_other_valid && tex.is_valid()) {
5512 Ref<StandardMaterial3D> new_mat = memnew(StandardMaterial3D);
5513 new_mat->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, tex);
5514
5515 spatial_editor->set_preview_material(new_mat);
5516 is_other_valid = true;
5517 continue;
5518 } else if (!is_other_valid && audio.is_valid()) {
5519 is_other_valid = true;
5520 } else {
5521 continue;
5522 }
5523 can_instantiate = true;
5524 }
5525 }
5526 if (can_instantiate) {
5527 _create_preview_node(files);
5528 preview_node->hide();
5529 }
5530 }
5531 } else {
5532 if (preview_node->is_inside_tree()) {
5533 can_instantiate = true;
5534 }
5535 }
5536
5537 if (is_cyclical_dep) {
5538 set_message(vformat(TTR("Can't instantiate: %s."), vformat(TTR("Circular dependency found at %s"), error_file)));
5539 return false;
5540 }
5541
5542 if (can_instantiate) {
5543 update_preview_node = true;
5544 return true;
5545 }
5546
5547 if (spatial_editor->get_preview_material().is_valid()) {
5548 preview_material_label->show();
5549 preview_material_label_desc->show();
5550
5551 ObjectID new_preview_material_target = _select_ray(p_point);
5552 return _apply_preview_material(new_preview_material_target, p_point);
5553 }
5554
5555 return false;
5556 }
5557
5558 void Node3DEditorViewport::drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
5559 if (!can_drop_data_fw(p_point, p_data, p_from)) {
5560 return;
5561 }
5562
5563 bool is_shift = Input::get_singleton()->is_key_pressed(Key::SHIFT);
5564 bool is_alt = Input::get_singleton()->is_key_pressed(Key::ALT);
5565
5566 selected_files.clear();
5567 Dictionary d = p_data;
5568 if (d.has("type") && String(d["type"]) == "files") {
5569 selected_files = d["files"];
5570 }
5571
5572 const List<Node *> &selected_nodes = EditorNode::get_singleton()->get_editor_selection()->get_top_selected_node_list();
5573 Node *root_node = EditorNode::get_singleton()->get_edited_scene();
5574 if (selected_nodes.size() > 0) {
5575 Node *selected_node = selected_nodes.front()->get();
5576 if (is_alt) {
5577 target_node = root_node;
5578 } else if (is_shift) {
5579 target_node = selected_node;
5580 } else { // Default behavior.
5581 target_node = (selected_node != root_node) ? selected_node->get_parent() : root_node;
5582 }
5583 } else {
5584 if (root_node) {
5585 target_node = root_node;
5586 } else {
5587 // Create a root node so we can add child nodes to it.
5588 SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
5589 target_node = get_tree()->get_edited_scene_root();
5590 }
5591 }
5592
5593 drop_pos = p_point;
5594
5595 _perform_drop_data();
5596 }
5597
5598 void Node3DEditorViewport::begin_transform(TransformMode p_mode, bool instant) {
5599 if (get_selected_count() > 0) {
5600 _edit.mode = p_mode;
5601 _compute_edit(_edit.mouse_pos);
5602 _edit.instant = instant;
5603 _edit.snap = spatial_editor->is_snap_enabled();
5604 _edit.initial_click_vector = Vector3();
5605 _edit.previous_rotation_vector = Vector3();
5606 _edit.accumulated_rotation_angle = 0.0;
5607 _edit.display_rotation_angle = 0.0;
5608 _edit.gizmo_initiated = false;
5609 update_transform_gizmo_view();
5610 set_process_input(instant);
5611 }
5612 }
5613
5614 // Apply the current transform operation.
5615 void Node3DEditorViewport::commit_transform() {
5616 ERR_FAIL_COND(_edit.mode == TRANSFORM_NONE);
5617 static const char *_transform_name[4] = {
5618 TTRC("None"),
5619 TTRC("Rotate"),
5620 // TRANSLATORS: This refers to the movement that changes the position of an object.
5621 TTRC("Translate"),
5622 TTRC("Scale"),
5623 };
5624 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
5625 undo_redo->create_action(_transform_name[_edit.mode]);
5626
5627 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
5628
5629 for (Node *E : selection) {
5630 Node3D *sp = Object::cast_to<Node3D>(E);
5631 if (!sp) {
5632 continue;
5633 }
5634
5635 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
5636 if (!se) {
5637 continue;
5638 }
5639
5640 undo_redo->add_do_method(sp, "set_transform", sp->get_local_gizmo_transform());
5641 undo_redo->add_undo_method(sp, "set_transform", se->original_local);
5642 }
5643 undo_redo->commit_action();
5644
5645 collision_reposition = false;
5646 finish_transform();
5647 set_message("");
5648 }
5649
5650 void Node3DEditorViewport::apply_transform(Vector3 p_motion, double p_snap) {
5651 // View-plane translate/scale always uses global coords; rotation and axis operations respect local/global preference.
5652 bool local_coords = spatial_editor->are_local_coords_enabled() &&
5653 !(_edit.plane == TRANSFORM_VIEW && _edit.mode != TRANSFORM_ROTATE);
5654
5655 bool is_global_view_plane = (_edit.plane == TRANSFORM_VIEW) &&
5656 ((_edit.mode != TRANSFORM_ROTATE) || !spatial_editor->are_local_coords_enabled());
5657
5658 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
5659 for (Node *E : selection) {
5660 Node3D *sp = Object::cast_to<Node3D>(E);
5661 if (!sp) {
5662 continue;
5663 }
5664
5665 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
5666 if (!se) {
5667 continue;
5668 }
5669
5670 if (sp->has_meta("_edit_lock_") && !spatial_editor->is_gizmo_visible()) {
5671 continue;
5672 }
5673
5674 if (se->gizmo.is_valid()) {
5675 for (KeyValue<int, Transform3D> &GE : se->subgizmos) {
5676 Transform3D xform = GE.value;
5677 Transform3D new_xform = _compute_transform(_edit.mode, se->original * xform, xform, p_motion, p_snap, local_coords, _edit.plane != TRANSFORM_VIEW, is_global_view_plane); // Force orthogonal with subgizmo.
5678 if (!local_coords) {
5679 new_xform = se->original.affine_inverse() * new_xform;
5680 }
5681 se->gizmo->set_subgizmo_transform(GE.key, new_xform);
5682 }
5683 } else {
5684 Transform3D new_xform = _compute_transform(_edit.mode, se->original, se->original_local, p_motion, p_snap, local_coords, sp->get_rotation_edit_mode() != Node3D::ROTATION_EDIT_MODE_BASIS && _edit.plane != TRANSFORM_VIEW, is_global_view_plane);
5685 _transform_gizmo_apply(se->sp, new_xform, local_coords);
5686 }
5687 }
5688
5689 spatial_editor->update_transform_gizmo();
5690 surface->queue_redraw();
5691 }
5692
5693 // Update the current transform operation in response to an input.
5694 void Node3DEditorViewport::update_transform(bool p_shift) {
5695 Vector3 ray_pos = get_ray_pos(_edit.mouse_pos);
5696 Vector3 ray = get_ray(_edit.mouse_pos);
5697 double snap = EDITOR_GET("interface/inspector/default_float_step");
5698 int snap_step_decimals = Math::range_step_decimals(snap);
5699
5700 // View-plane translate/scale always uses global coords; rotation and axis operations respect local/global preference.
5701 bool local_coords = spatial_editor->are_local_coords_enabled() &&
5702 !(_edit.plane == TRANSFORM_VIEW && _edit.mode != TRANSFORM_ROTATE);
5703
5704 switch (_edit.mode) {
5705 case TRANSFORM_SCALE: {
5706 Vector3 motion_mask;
5707 Plane plane;
5708 bool plane_mv = false;
5709
5710 switch (_edit.plane) {
5711 case TRANSFORM_VIEW:
5712 motion_mask = Vector3(0, 0, 0);
5713 plane = Plane(_get_camera_normal(), _edit.center);
5714 break;
5715 case TRANSFORM_X_AXIS:
5716 motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
5717 plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
5718 break;
5719 case TRANSFORM_Y_AXIS:
5720 motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
5721 plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
5722 break;
5723 case TRANSFORM_Z_AXIS:
5724 motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized();
5725 plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
5726 break;
5727 case TRANSFORM_YZ:
5728 motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
5729 plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(0).normalized(), _edit.center);
5730 plane_mv = true;
5731 break;
5732 case TRANSFORM_XZ:
5733 motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
5734 plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(1).normalized(), _edit.center);
5735 plane_mv = true;
5736 break;
5737 case TRANSFORM_XY:
5738 motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized() + spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
5739 plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(2).normalized(), _edit.center);
5740 plane_mv = true;
5741 break;
5742 }
5743
5744 Vector3 intersection;
5745 if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
5746 break;
5747 }
5748
5749 Vector3 click;
5750 if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
5751 break;
5752 }
5753
5754 Vector3 motion = intersection - click;
5755 if (_edit.plane != TRANSFORM_VIEW) {
5756 if (!plane_mv) {
5757 motion = motion_mask.dot(motion) * motion_mask;
5758
5759 } else {
5760 // Alternative planar scaling mode
5761 if (p_shift) {
5762 motion = motion_mask.dot(motion) * motion_mask;
5763 }
5764 }
5765
5766 } else {
5767 const real_t center_click_dist = click.distance_to(_edit.center);
5768 const real_t center_inters_dist = intersection.distance_to(_edit.center);
5769 if (center_click_dist == 0) {
5770 break;
5771 }
5772
5773 const real_t scale = center_inters_dist - center_click_dist;
5774 motion = Vector3(scale, scale, scale);
5775 }
5776
5777 motion /= click.distance_to(_edit.center);
5778
5779 if (_edit.snap || spatial_editor->is_snap_enabled()) {
5780 snap = spatial_editor->get_scale_snap() / 100;
5781 }
5782 Vector3 motion_snapped = motion;
5783 motion_snapped.snapf(snap);
5784 // This might not be necessary anymore after issue #288 is solved (in 4.0?).
5785 // TRANSLATORS: Refers to changing the scale of a node in the 3D editor.
5786 set_message(TTR("Scaling:") + " (" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
5787 String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
5788 if (local_coords) {
5789 // TODO: needed?
5790 motion = _edit.original.basis.inverse().xform(motion);
5791 }
5792
5793 apply_transform(motion, snap);
5794 } break;
5795
5796 case TRANSFORM_TRANSLATE: {
5797 Vector3 motion_mask;
5798 Plane plane;
5799 bool plane_mv = false;
5800
5801 switch (_edit.plane) {
5802 case TRANSFORM_VIEW:
5803 plane = Plane(_get_camera_normal(), _edit.center);
5804 break;
5805 case TRANSFORM_X_AXIS:
5806 motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(0).normalized();
5807 plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
5808 break;
5809 case TRANSFORM_Y_AXIS:
5810 motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(1).normalized();
5811 plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
5812 break;
5813 case TRANSFORM_Z_AXIS:
5814 motion_mask = spatial_editor->get_gizmo_transform().basis.get_column(2).normalized();
5815 plane = Plane(motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized(), _edit.center);
5816 break;
5817 case TRANSFORM_YZ:
5818 plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(0).normalized(), _edit.center);
5819 plane_mv = true;
5820 break;
5821 case TRANSFORM_XZ:
5822 plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(1).normalized(), _edit.center);
5823 plane_mv = true;
5824 break;
5825 case TRANSFORM_XY:
5826 plane = Plane(spatial_editor->get_gizmo_transform().basis.get_column(2).normalized(), _edit.center);
5827 plane_mv = true;
5828 break;
5829 }
5830
5831 Vector3 intersection;
5832 if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
5833 break;
5834 }
5835
5836 Vector3 click;
5837 if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
5838 break;
5839 }
5840
5841 Vector3 motion = intersection - click;
5842 if (_edit.plane != TRANSFORM_VIEW) {
5843 if (!plane_mv) {
5844 motion = motion_mask.dot(motion) * motion_mask;
5845 }
5846 }
5847
5848 if (_edit.snap || spatial_editor->is_snap_enabled()) {
5849 snap = spatial_editor->get_translate_snap();
5850 }
5851 Vector3 motion_snapped = motion;
5852 motion_snapped.snapf(snap);
5853 // TRANSLATORS: Refers to changing the position of a node in the 3D editor.
5854 set_message(TTR("Translating:") + " (" + String::num(motion_snapped.x, snap_step_decimals) + ", " +
5855 String::num(motion_snapped.y, snap_step_decimals) + ", " + String::num(motion_snapped.z, snap_step_decimals) + ")");
5856 if (local_coords) {
5857 motion = spatial_editor->get_gizmo_transform().basis.inverse().xform(motion);
5858 }
5859
5860 apply_transform(motion, snap);
5861 } break;
5862
5863 case TRANSFORM_ROTATE: {
5864 Plane plane;
5865 if (camera->get_projection() == Camera3D::PROJECTION_PERSPECTIVE) {
5866 Vector3 cam_to_obj = _edit.center - _get_camera_position();
5867 if (!cam_to_obj.is_zero_approx()) {
5868 plane = Plane(cam_to_obj.normalized(), _edit.center);
5869 } else {
5870 plane = Plane(_get_camera_normal(), _edit.center);
5871 }
5872 } else {
5873 plane = Plane(_get_camera_normal(), _edit.center);
5874 }
5875
5876 Vector3 local_axis;
5877 Vector3 global_axis;
5878 switch (_edit.plane) {
5879 case TRANSFORM_VIEW:
5880 local_axis = _edit.view_axis_local;
5881 global_axis = _get_camera_normal();
5882 break;
5883 case TRANSFORM_X_AXIS:
5884 local_axis = Vector3(1, 0, 0);
5885 break;
5886 case TRANSFORM_Y_AXIS:
5887 local_axis = Vector3(0, 1, 0);
5888 break;
5889 case TRANSFORM_Z_AXIS:
5890 local_axis = Vector3(0, 0, 1);
5891 break;
5892 case TRANSFORM_YZ:
5893 case TRANSFORM_XZ:
5894 case TRANSFORM_XY:
5895 break;
5896 }
5897
5898 if (_edit.plane != TRANSFORM_VIEW) {
5899 global_axis = spatial_editor->get_gizmo_transform().basis.xform(local_axis).normalized();
5900 }
5901
5902 Vector3 intersection;
5903 if (!plane.intersects_ray(ray_pos, ray, &intersection)) {
5904 break;
5905 }
5906
5907 Vector3 click;
5908 if (!plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click)) {
5909 break;
5910 }
5911
5912 Vector3 current_rotation_vector = (intersection - _edit.center).normalized();
5913
5914 if (_edit.initial_click_vector == Vector3()) {
5915 Plane rotation_plane(global_axis, _edit.center);
5916 Vector3 click_on_rotation_plane;
5917 if (rotation_plane.intersects_ray(_edit.click_ray_pos, _edit.click_ray, &click_on_rotation_plane)) {
5918 _edit.initial_click_vector = (click_on_rotation_plane - _edit.center).normalized();
5919 } else {
5920 _edit.initial_click_vector = (click - _edit.center).normalized();
5921 }
5922 _edit.previous_rotation_vector = current_rotation_vector;
5923 _edit.accumulated_rotation_angle = 0.0;
5924 _edit.display_rotation_angle = 0.0;
5925 }
5926
5927 static const float orthogonal_threshold = Math::cos(Math::deg_to_rad(85.0f));
5928 bool axis_is_orthogonal = Math::abs(plane.normal.dot(global_axis)) < orthogonal_threshold;
5929
5930 double angle = 0.0f;
5931 if (axis_is_orthogonal) {
5932 _edit.show_rotation_line = false;
5933 Vector3 projection_axis = plane.normal.cross(global_axis);
5934 Vector3 delta = intersection - click;
5935 float projection = delta.dot(projection_axis);
5936 angle = (projection * (Math::PI / 2.0f)) / (gizmo_scale * GIZMO_CIRCLE_SIZE);
5937 } else {
5938 _edit.show_rotation_line = true;
5939 Vector3 click_axis = (click - _edit.center).normalized();
5940 angle = click_axis.signed_angle_to(current_rotation_vector, global_axis);
5941 }
5942
5943 if (_edit.previous_rotation_vector != Vector3()) {
5944 double delta_angle = _edit.previous_rotation_vector.signed_angle_to(current_rotation_vector, global_axis);
5945 _edit.accumulated_rotation_angle += delta_angle;
5946 }
5947 _edit.previous_rotation_vector = current_rotation_vector;
5948
5949 bool snapping = _edit.snap || spatial_editor->is_snap_enabled();
5950 if (snapping) {
5951 snap = spatial_editor->get_rotate_snap();
5952 _edit.display_rotation_angle = Math::deg_to_rad(Math::snapped(Math::rad_to_deg(_edit.accumulated_rotation_angle), snap));
5953 } else {
5954 _edit.display_rotation_angle = _edit.accumulated_rotation_angle;
5955 }
5956 angle = Math::snapped(Math::rad_to_deg(angle), snap);
5957 set_message(vformat(TTR("Rotating %s degrees."), String::num(angle, snap_step_decimals)));
5958 angle = Math::deg_to_rad(angle);
5959
5960 Vector3 compute_axis = local_coords ? local_axis : global_axis;
5961 apply_transform(compute_axis, angle);
5962 } break;
5963 default: {
5964 }
5965 }
5966 }
5967
5968 void Node3DEditorViewport::update_transform_numeric() {
5969 Vector3 motion;
5970 switch (_edit.plane) {
5971 case TRANSFORM_VIEW: {
5972 switch (_edit.mode) {
5973 case TRANSFORM_TRANSLATE:
5974 motion = Vector3(1, 0, 0);
5975 break;
5976 case TRANSFORM_ROTATE:
5977 motion = _edit.view_axis_local;
5978 break;
5979 case TRANSFORM_SCALE:
5980 motion = Vector3(1, 1, 1);
5981 break;
5982 case TRANSFORM_NONE:
5983 ERR_FAIL_MSG("_edit.mode cannot be TRANSFORM_NONE in update_transform_numeric.");
5984 }
5985 break;
5986 }
5987 case TRANSFORM_X_AXIS:
5988 motion = Vector3(1, 0, 0);
5989 break;
5990 case TRANSFORM_Y_AXIS:
5991 motion = Vector3(0, 1, 0);
5992 break;
5993 case TRANSFORM_Z_AXIS:
5994 motion = Vector3(0, 0, 1);
5995 break;
5996 case TRANSFORM_XY:
5997 motion = Vector3(1, 1, 0);
5998 break;
5999 case TRANSFORM_XZ:
6000 motion = Vector3(1, 0, 1);
6001 break;
6002 case TRANSFORM_YZ:
6003 motion = Vector3(0, 1, 1);
6004 break;
6005 }
6006
6007 double value = _edit.numeric_input * (_edit.numeric_negate ? -1 : 1);
6008 double extra = 0.0;
6009 switch (_edit.mode) {
6010 case TRANSFORM_TRANSLATE:
6011 motion *= value;
6012 set_message(vformat(TTR("Translating %s."), motion));
6013 break;
6014 case TRANSFORM_ROTATE:
6015 extra = Math::deg_to_rad(value);
6016 set_message(vformat(TTR("Rotating %f degrees."), value));
6017 break;
6018 case TRANSFORM_SCALE:
6019 // To halve the size of an object in Blender, you scale it by 0.5.
6020 // Doing the same in Godot is considered scaling it by -0.5.
6021 motion *= (value - 1.0);
6022 set_message(vformat(TTR("Scaling %s."), motion));
6023 break;
6024 case TRANSFORM_NONE:
6025 ERR_FAIL_MSG("_edit.mode cannot be TRANSFORM_NONE in update_transform_numeric.");
6026 }
6027
6028 apply_transform(motion, extra);
6029 }
6030
6031 // Perform cleanup after a transform operation is committed or canceled.
6032 void Node3DEditorViewport::finish_transform() {
6033 _edit.mode = TRANSFORM_NONE;
6034 _edit.instant = false;
6035 _edit.numeric_input = 0;
6036 _edit.numeric_next_decimal = 0;
6037 _edit.numeric_negate = false;
6038 _edit.initial_click_vector = Vector3();
6039 _edit.previous_rotation_vector = Vector3();
6040 _edit.accumulated_rotation_angle = 0.0;
6041 _edit.display_rotation_angle = 0.0;
6042 _edit.gizmo_initiated = false;
6043 spatial_editor->set_local_coords_enabled(_edit.original_local);
6044 spatial_editor->update_transform_gizmo();
6045 surface->queue_redraw();
6046 set_process_input(false);
6047 clicked = ObjectID();
6048 }
6049
6050 // Register a shortcut and also add it as an input action with the same events.
6051 void Node3DEditorViewport::register_shortcut_action(const String &p_path, const String &p_name, Key p_keycode, bool p_physical) {
6052 Ref<Shortcut> sc = ED_SHORTCUT(p_path, p_name, p_keycode, p_physical);
6053 shortcut_changed_callback(sc, p_path);
6054 // Connect to the change event on the shortcut so the input binding can be updated.
6055 sc->connect_changed(callable_mp(this, &Node3DEditorViewport::shortcut_changed_callback).bind(sc, p_path));
6056 }
6057
6058 // Update the action in the InputMap to the provided shortcut events.
6059 void Node3DEditorViewport::shortcut_changed_callback(const Ref<Shortcut> p_shortcut, const String &p_shortcut_path) {
6060 InputMap *im = InputMap::get_singleton();
6061 if (im->has_action(p_shortcut_path)) {
6062 im->action_erase_events(p_shortcut_path);
6063 } else {
6064 im->add_action(p_shortcut_path);
6065 }
6066
6067 for (int i = 0; i < p_shortcut->get_events().size(); i++) {
6068 im->action_add_event(p_shortcut_path, p_shortcut->get_events()[i]);
6069 }
6070 }
6071
6072 void Node3DEditorViewport::_set_lock_view_rotation(bool p_lock_rotation) {
6073 lock_rotation = p_lock_rotation;
6074 int idx = view_display_menu->get_popup()->get_item_index(VIEW_LOCK_ROTATION);
6075 view_display_menu->get_popup()->set_item_checked(idx, p_lock_rotation);
6076 if (p_lock_rotation) {
6077 locked_label->show();
6078 } else {
6079 locked_label->hide();
6080 }
6081 }
6082
6083 void Node3DEditorViewport::_add_advanced_debug_draw_mode_item(PopupMenu *p_popup, const String &p_name, int p_value, SupportedRenderingMethods p_rendering_methods, const String &p_tooltip) {
6084 display_submenu->add_radio_check_item(p_name, p_value);
6085 Array item_data = { p_rendering_methods, p_tooltip };
6086 display_submenu->set_item_metadata(-1, item_data); // Tooltip is assigned in NOTIFICATION_TRANSLATION_CHANGED.
6087 }
6088
6089 void Node3DEditorViewport::_load_viewport_inputs() {
6090 // Registering with Key::NONE intentionally creates an empty Array.
6091 register_shortcut_action("spatial_editor/viewport_orbit_modifier_1", TTRC("Viewport Orbit Modifier 1"), Key::NONE);
6092 register_shortcut_action("spatial_editor/viewport_orbit_modifier_2", TTRC("Viewport Orbit Modifier 2"), Key::NONE);
6093 register_shortcut_action("spatial_editor/viewport_orbit_snap_modifier_1", TTRC("Viewport Orbit Snap Modifier 1"), Key::ALT);
6094 register_shortcut_action("spatial_editor/viewport_orbit_snap_modifier_2", TTRC("Viewport Orbit Snap Modifier 2"), Key::NONE);
6095 register_shortcut_action("spatial_editor/viewport_pan_modifier_1", TTRC("Viewport Pan Modifier 1"), Key::SHIFT);
6096 register_shortcut_action("spatial_editor/viewport_pan_modifier_2", TTRC("Viewport Pan Modifier 2"), Key::NONE);
6097 register_shortcut_action("spatial_editor/viewport_zoom_modifier_1", TTRC("Viewport Zoom Modifier 1"), Key::CTRL);
6098 register_shortcut_action("spatial_editor/viewport_zoom_modifier_2", TTRC("Viewport Zoom Modifier 2"), Key::NONE);
6099
6100 register_shortcut_action("spatial_editor/freelook_left", TTRC("Freelook Left"), Key::A, true);
6101 register_shortcut_action("spatial_editor/freelook_right", TTRC("Freelook Right"), Key::D, true);
6102 register_shortcut_action("spatial_editor/freelook_forward", TTRC("Freelook Forward"), Key::W, true);
6103 register_shortcut_action("spatial_editor/freelook_backwards", TTRC("Freelook Backwards"), Key::S, true);
6104 register_shortcut_action("spatial_editor/freelook_up", TTRC("Freelook Up"), Key::E, true);
6105 register_shortcut_action("spatial_editor/freelook_down", TTRC("Freelook Down"), Key::Q, true);
6106 register_shortcut_action("spatial_editor/freelook_speed_modifier", TTRC("Freelook Speed Modifier"), Key::SHIFT);
6107 register_shortcut_action("spatial_editor/freelook_slow_modifier", TTRC("Freelook Slow Modifier"), Key::ALT);
6108 }
6109
6110 Node3DEditorViewport::Node3DEditorViewport(Node3DEditor *p_spatial_editor, int p_index) {
6111 cpu_time_history_index = 0;
6112 gpu_time_history_index = 0;
6113
6114 _edit.mode = TRANSFORM_NONE;
6115 _edit.plane = TRANSFORM_VIEW;
6116 _edit.snap = true;
6117 _edit.show_rotation_line = true;
6118 _edit.instant = false;
6119 _edit.gizmo_handle = -1;
6120 _edit.gizmo_handle_secondary = false;
6121
6122 index = p_index;
6123 editor_selection = EditorNode::get_singleton()->get_editor_selection();
6124
6125 orthogonal = false;
6126 auto_orthogonal = false;
6127 lock_rotation = false;
6128 message_time = 0;
6129 zoom_indicator_delay = 0.0;
6130
6131 spatial_editor = p_spatial_editor;
6132 SubViewportContainer *c = memnew(SubViewportContainer);
6133 subviewport_container = c;
6134 c->set_stretch(true);
6135 add_child(c);
6136 c->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
6137 viewport = memnew(SubViewport);
6138 viewport->set_disable_input(true);
6139
6140 c->add_child(viewport);
6141 surface = memnew(Control);
6142 SET_DRAG_FORWARDING_CD(surface, Node3DEditorViewport);
6143 add_child(surface);
6144 surface->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
6145 surface->set_clip_contents(true);
6146 camera = memnew(Camera3D);
6147 camera->set_disable_gizmos(true);
6148 camera->set_cull_mask(((1 << 20) - 1) | (1 << (GIZMO_BASE_LAYER + p_index)) | (1 << GIZMO_EDIT_LAYER) | (1 << GIZMO_GRID_LAYER) | (1 << MISC_TOOL_LAYER));
6149 viewport->add_child(camera);
6150 camera->make_current();
6151 surface->set_focus_mode(FOCUS_ALL);
6152
6153 VBoxContainer *vbox = memnew(VBoxContainer);
6154 surface->add_child(vbox);
6155 vbox->set_offset(SIDE_LEFT, 10 * EDSCALE);
6156 vbox->set_offset(SIDE_TOP, 10 * EDSCALE);
6157
6158 HBoxContainer *hbox = memnew(HBoxContainer);
6159 vbox->add_child(hbox);
6160
6161 view_display_menu = memnew(MenuButton);
6162 view_display_menu->set_flat(false);
6163 view_display_menu->set_h_size_flags(0);
6164 view_display_menu->set_shortcut_context(this);
6165 view_display_menu->set_accessibility_name(TTRC("View"));
6166 view_display_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
6167 view_display_menu->get_popup()->set_auto_translate_mode(AUTO_TRANSLATE_MODE_ALWAYS);
6168 hbox->add_child(view_display_menu);
6169
6170 view_display_menu->get_popup()->set_hide_on_checkable_item_selection(false);
6171
6172 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/top_view"), VIEW_TOP);
6173 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/bottom_view"), VIEW_BOTTOM);
6174 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/left_view"), VIEW_LEFT);
6175 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/right_view"), VIEW_RIGHT);
6176 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/front_view"), VIEW_FRONT);
6177 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/rear_view"), VIEW_REAR);
6178 view_display_menu->get_popup()->add_separator();
6179 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/switch_perspective_orthogonal"), VIEW_SWITCH_PERSPECTIVE_ORTHOGONAL);
6180 view_display_menu->get_popup()->add_radio_check_item(TTRC("Perspective"), VIEW_PERSPECTIVE);
6181 view_display_menu->get_popup()->add_radio_check_item(TTRC("Orthogonal"), VIEW_ORTHOGONAL);
6182 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true);
6183 view_display_menu->get_popup()->add_check_item(TTRC("Auto Orthogonal Enabled"), VIEW_AUTO_ORTHOGONAL);
6184 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUTO_ORTHOGONAL), true);
6185 view_display_menu->get_popup()->add_separator();
6186 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_lock_rotation", TTRC("Lock View Rotation")), VIEW_LOCK_ROTATION);
6187 view_display_menu->get_popup()->add_separator();
6188 // TRANSLATORS: "Normal" as in "normal life", not "normal vector".
6189 view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_normal", TTRC("Display Normal")), VIEW_DISPLAY_NORMAL);
6190 view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_wireframe", TTRC("Display Wireframe")), VIEW_DISPLAY_WIREFRAME);
6191 view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_overdraw", TTRC("Display Overdraw")), VIEW_DISPLAY_OVERDRAW);
6192 view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_lighting", TTRC("Display Lighting")), VIEW_DISPLAY_LIGHTING);
6193 view_display_menu->get_popup()->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/view_display_unshaded", TTRC("Display Unshaded")), VIEW_DISPLAY_UNSHADED);
6194 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_DISPLAY_NORMAL), true);
6195
6196 display_submenu = memnew(PopupMenu);
6197 display_submenu->set_hide_on_checkable_item_selection(false);
6198 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Directional Shadow Splits"), VIEW_DISPLAY_DEBUG_PSSM_SPLITS, SupportedRenderingMethods::FORWARD_PLUS_MOBILE,
6199 TTRC("Displays directional shadow splits in different colors to make adjusting split thresholds easier. \nRed: 1st split (closest to the camera), Green: 2nd split, Blue: 3rd split, Yellow: 4th split (furthest from the camera)"));
6200 display_submenu->add_separator();
6201 // TRANSLATORS: "Normal" as in "normal vector", not "normal life".
6202 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Normal Buffer"), VIEW_DISPLAY_NORMAL_BUFFER, SupportedRenderingMethods::FORWARD_PLUS);
6203 display_submenu->add_separator();
6204 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Shadow Atlas"), VIEW_DISPLAY_DEBUG_SHADOW_ATLAS, SupportedRenderingMethods::ALL,
6205 TTRC("Displays the shadow atlas used for positional (omni/spot) shadow mapping.\nRequires a visible OmniLight3D or SpotLight3D node with shadows enabled to have a visible effect."));
6206 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Directional Shadow Map"), VIEW_DISPLAY_DEBUG_DIRECTIONAL_SHADOW_ATLAS, SupportedRenderingMethods::ALL,
6207 TTRC("Displays the shadow map used for directional shadow mapping.\nRequires a visible DirectionalLight3D node with shadows enabled to have a visible effect."));
6208 display_submenu->add_separator();
6209 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Decal Atlas"), VIEW_DISPLAY_DEBUG_DECAL_ATLAS, SupportedRenderingMethods::FORWARD_PLUS_MOBILE);
6210 display_submenu->add_separator();
6211 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("VoxelGI Lighting"), VIEW_DISPLAY_DEBUG_VOXEL_GI_LIGHTING, SupportedRenderingMethods::FORWARD_PLUS,
6212 TTRC("Requires a visible VoxelGI node that has been baked to have a visible effect."));
6213 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("VoxelGI Albedo"), VIEW_DISPLAY_DEBUG_VOXEL_GI_ALBEDO, SupportedRenderingMethods::FORWARD_PLUS,
6214 TTRC("Requires a visible VoxelGI node that has been baked to have a visible effect."));
6215 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("VoxelGI Emission"), VIEW_DISPLAY_DEBUG_VOXEL_GI_EMISSION, SupportedRenderingMethods::FORWARD_PLUS,
6216 TTRC("Requires a visible VoxelGI node that has been baked to have a visible effect."));
6217 display_submenu->add_separator();
6218 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("SDFGI Cascades"), VIEW_DISPLAY_DEBUG_SDFGI, SupportedRenderingMethods::FORWARD_PLUS,
6219 TTRC("Requires SDFGI to be enabled in Environment to have a visible effect."));
6220 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("SDFGI Probes"), VIEW_DISPLAY_DEBUG_SDFGI_PROBES, SupportedRenderingMethods::FORWARD_PLUS,
6221 TTRC("Left-click a SDFGI probe to display its occlusion information (white = not occluded, red = fully occluded).\nRequires SDFGI to be enabled in Environment to have a visible effect."));
6222 display_submenu->add_separator();
6223 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Scene Luminance"), VIEW_DISPLAY_DEBUG_SCENE_LUMINANCE, SupportedRenderingMethods::FORWARD_PLUS_MOBILE,
6224 TTRC("Displays the scene luminance computed from the 3D buffer. This is used for Auto Exposure calculation.\nRequires Auto Exposure to be enabled in CameraAttributes to have a visible effect."));
6225 display_submenu->add_separator();
6226 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("SSAO"), VIEW_DISPLAY_DEBUG_SSAO, SupportedRenderingMethods::FORWARD_PLUS,
6227 TTRC("Displays the screen-space ambient occlusion buffer. Requires SSAO to be enabled in Environment to have a visible effect."));
6228 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("SSIL"), VIEW_DISPLAY_DEBUG_SSIL, SupportedRenderingMethods::FORWARD_PLUS,
6229 TTRC("Displays the screen-space indirect lighting buffer. Requires SSIL to be enabled in Environment to have a visible effect."));
6230 display_submenu->add_separator();
6231 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("VoxelGI/SDFGI Buffer"), VIEW_DISPLAY_DEBUG_GI_BUFFER, SupportedRenderingMethods::FORWARD_PLUS,
6232 TTRC("Requires SDFGI or VoxelGI to be enabled to have a visible effect."));
6233 display_submenu->add_separator();
6234 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Disable Mesh LOD"), VIEW_DISPLAY_DEBUG_DISABLE_LOD, SupportedRenderingMethods::ALL,
6235 TTRC("Renders all meshes with their highest level of detail regardless of their distance from the camera."));
6236 display_submenu->add_separator();
6237 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("OmniLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_OMNI_LIGHTS, SupportedRenderingMethods::FORWARD_PLUS,
6238 TTRC("Highlights tiles of pixels that are affected by at least one OmniLight3D."));
6239 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("SpotLight3D Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_SPOT_LIGHTS, SupportedRenderingMethods::FORWARD_PLUS,
6240 TTRC("Highlights tiles of pixels that are affected by at least one SpotLight3D."));
6241 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Decal Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_DECALS, SupportedRenderingMethods::FORWARD_PLUS,
6242 TTRC("Highlights tiles of pixels that are affected by at least one Decal."));
6243 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("ReflectionProbe Cluster"), VIEW_DISPLAY_DEBUG_CLUSTER_REFLECTION_PROBES, SupportedRenderingMethods::FORWARD_PLUS,
6244 TTRC("Highlights tiles of pixels that are affected by at least one ReflectionProbe."));
6245 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Occlusion Culling Buffer"), VIEW_DISPLAY_DEBUG_OCCLUDERS, SupportedRenderingMethods::FORWARD_PLUS_MOBILE,
6246 TTRC("Represents occluders with black pixels. Requires occlusion culling to be enabled to have a visible effect."));
6247 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Motion Vectors"), VIEW_DISPLAY_MOTION_VECTORS, SupportedRenderingMethods::FORWARD_PLUS,
6248 TTRC("Represents motion vectors with colored lines in the direction of motion. Gray dots represent areas with no per-pixel motion."));
6249 _add_advanced_debug_draw_mode_item(display_submenu, TTRC("Internal Buffer"), VIEW_DISPLAY_INTERNAL_BUFFER, SupportedRenderingMethods::FORWARD_PLUS_MOBILE,
6250 TTRC("Shows the scene rendered in linear colorspace before any tonemapping or post-processing."));
6251 view_display_menu->get_popup()->add_submenu_node_item(TTRC("Display Advanced..."), display_submenu, VIEW_DISPLAY_ADVANCED);
6252
6253 view_display_menu->get_popup()->add_separator();
6254 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_environment", TTRC("View Environment")), VIEW_ENVIRONMENT);
6255 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_gizmos", TTRC("View Gizmos")), VIEW_GIZMOS);
6256 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_transform_gizmo", TTRC("View Transform Gizmo")), VIEW_TRANSFORM_GIZMO);
6257 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid_lines", TTRC("View Grid")), VIEW_GRID);
6258 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_information", TTRC("View Information")), VIEW_INFORMATION);
6259 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_fps", TTRC("View Frame Time")), VIEW_FRAME_TIME);
6260 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT), true);
6261 view_display_menu->get_popup()->add_separator();
6262 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_half_resolution", TTRC("Half Resolution")), VIEW_HALF_RESOLUTION);
6263 view_display_menu->get_popup()->add_separator();
6264 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_listener", TTRC("Audio Listener")), VIEW_AUDIO_LISTENER);
6265 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_audio_doppler", TTRC("Enable Doppler")), VIEW_AUDIO_DOPPLER);
6266 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_GIZMOS), true);
6267 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_TRANSFORM_GIZMO), true);
6268 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_GRID), true);
6269
6270 view_display_menu->get_popup()->add_separator();
6271 view_display_menu->get_popup()->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_cinematic_preview", TTRC("Cinematic Preview")), VIEW_CINEMATIC_PREVIEW);
6272
6273 view_display_menu->get_popup()->add_separator();
6274 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_origin"), VIEW_CENTER_TO_ORIGIN);
6275 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/focus_selection"), VIEW_CENTER_TO_SELECTION);
6276 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_transform_with_view"), VIEW_ALIGN_TRANSFORM_WITH_VIEW);
6277 view_display_menu->get_popup()->add_shortcut(ED_GET_SHORTCUT("spatial_editor/align_rotation_with_view"), VIEW_ALIGN_ROTATION_WITH_VIEW);
6278 view_display_menu->get_popup()->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditorViewport::_menu_option));
6279 display_submenu->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditorViewport::_menu_option));
6280 view_display_menu->set_disable_shortcuts(true);
6281
6282 _load_viewport_inputs();
6283 InputMap::get_singleton()->connect("project_settings_loaded", callable_mp(this, &Node3DEditorViewport::_load_viewport_inputs));
6284
6285 ED_SHORTCUT("spatial_editor/lock_transform_x", TTRC("Lock Transformation to X axis"), Key::X);
6286 ED_SHORTCUT("spatial_editor/lock_transform_y", TTRC("Lock Transformation to Y axis"), Key::Y);
6287 ED_SHORTCUT("spatial_editor/lock_transform_z", TTRC("Lock Transformation to Z axis"), Key::Z);
6288 ED_SHORTCUT("spatial_editor/lock_transform_yz", TTRC("Lock Transformation to YZ plane"), KeyModifierMask::SHIFT | Key::X);
6289 ED_SHORTCUT("spatial_editor/lock_transform_xz", TTRC("Lock Transformation to XZ plane"), KeyModifierMask::SHIFT | Key::Y);
6290 ED_SHORTCUT("spatial_editor/lock_transform_xy", TTRC("Lock Transformation to XY plane"), KeyModifierMask::SHIFT | Key::Z);
6291 ED_SHORTCUT("spatial_editor/cancel_transform", TTRC("Cancel Transformation"), Key::ESCAPE);
6292 ED_SHORTCUT("spatial_editor/instant_translate", TTRC("Begin Translate Transformation"));
6293 ED_SHORTCUT("spatial_editor/instant_rotate", TTRC("Begin Rotate Transformation"));
6294 ED_SHORTCUT("spatial_editor/instant_scale", TTRC("Begin Scale Transformation"));
6295 ED_SHORTCUT("spatial_editor/collision_reposition", TTRC("Reposition Using Collisions"), KeyModifierMask::SHIFT | Key::G);
6296 ED_SHORTCUT("spatial_editor/reset_transform_position", TTRC("Reset Position"), KeyModifierMask::ALT + Key::W);
6297 ED_SHORTCUT("spatial_editor/reset_transform_rotation", TTRC("Reset Rotation"), KeyModifierMask::ALT + Key::E);
6298 ED_SHORTCUT("spatial_editor/reset_transform_scale", TTRC("Reset Scale"), KeyModifierMask::ALT + Key::R);
6299
6300 translation_preview_button = memnew(EditorTranslationPreviewButton);
6301 hbox->add_child(translation_preview_button);
6302
6303 preview_camera = memnew(CheckBox);
6304 preview_camera->set_text(TTRC("Preview"));
6305 // Using Control even on macOS to avoid conflict with Quick Open shortcut.
6306 preview_camera->set_shortcut(ED_SHORTCUT("spatial_editor/toggle_camera_preview", TTRC("Toggle Camera Preview"), KeyModifierMask::CTRL | Key::P));
6307 vbox->add_child(preview_camera);
6308 preview_camera->set_h_size_flags(0);
6309 preview_camera->set_theme_type_variation("CheckBoxNoIconTint");
6310 preview_camera->hide();
6311 preview_camera->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditorViewport::_toggle_camera_preview));
6312 previewing = nullptr;
6313 gizmo_scale = 1.0;
6314
6315 preview_node = nullptr;
6316
6317 bottom_center_vbox = memnew(VBoxContainer);
6318 bottom_center_vbox->set_anchors_preset(LayoutPreset::PRESET_CENTER);
6319 bottom_center_vbox->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -20 * EDSCALE);
6320 bottom_center_vbox->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE);
6321 bottom_center_vbox->set_h_grow_direction(GROW_DIRECTION_BOTH);
6322 bottom_center_vbox->set_v_grow_direction(GROW_DIRECTION_BEGIN);
6323 surface->add_child(bottom_center_vbox);
6324
6325 info_panel = memnew(PanelContainer);
6326 info_panel->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -90 * EDSCALE);
6327 info_panel->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -90 * EDSCALE);
6328 info_panel->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, -10 * EDSCALE);
6329 info_panel->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -10 * EDSCALE);
6330 info_panel->set_h_grow_direction(GROW_DIRECTION_BEGIN);
6331 info_panel->set_v_grow_direction(GROW_DIRECTION_BEGIN);
6332 info_panel->set_mouse_filter(MOUSE_FILTER_IGNORE);
6333 surface->add_child(info_panel);
6334 info_panel->hide();
6335
6336 info_label = memnew(Label);
6337 info_label->set_focus_mode(FOCUS_ACCESSIBILITY);
6338 info_panel->add_child(info_label);
6339
6340 cinema_label = memnew(Label);
6341 cinema_label->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, 10 * EDSCALE);
6342 cinema_label->set_h_grow_direction(GROW_DIRECTION_END);
6343 cinema_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
6344 cinema_label->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
6345 surface->add_child(cinema_label);
6346 cinema_label->set_text(TTRC("Cinematic Preview"));
6347 cinema_label->hide();
6348 previewing_cinema = false;
6349
6350 locked_label = memnew(Label);
6351 locked_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
6352 locked_label->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
6353 locked_label->set_h_size_flags(SIZE_SHRINK_CENTER);
6354 bottom_center_vbox->add_child(locked_label);
6355 locked_label->set_text(TTRC("View Rotation Locked"));
6356 locked_label->hide();
6357
6358 zoom_limit_label = memnew(Label);
6359 zoom_limit_label->set_text(TTRC(U"To zoom further, change the camera's clipping planes (View → Settings...)"));
6360 zoom_limit_label->set_name("ZoomLimitMessageLabel");
6361 zoom_limit_label->add_theme_color_override(SceneStringName(font_color), Color(1, 1, 1, 1));
6362 zoom_limit_label->hide();
6363 bottom_center_vbox->add_child(zoom_limit_label);
6364
6365 preview_material_label = memnew(Label);
6366 preview_material_label->set_anchors_and_offsets_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
6367 preview_material_label->set_offset(Side::SIDE_TOP, -70 * EDSCALE);
6368 preview_material_label->set_text(TTRC("Overriding material..."));
6369 preview_material_label->add_theme_color_override(SceneStringName(font_color), Color(1, 1, 1, 1));
6370 preview_material_label->hide();
6371 surface->add_child(preview_material_label);
6372
6373 preview_material_label_desc = memnew(Label);
6374 preview_material_label_desc->set_focus_mode(FOCUS_ACCESSIBILITY);
6375 preview_material_label_desc->set_anchors_and_offsets_preset(LayoutPreset::PRESET_BOTTOM_LEFT);
6376 preview_material_label_desc->set_offset(Side::SIDE_TOP, -50 * EDSCALE);
6377 preview_material_label_desc->add_theme_color_override(SceneStringName(font_color), Color(0.8, 0.8, 0.8, 1));
6378 preview_material_label_desc->add_theme_constant_override("line_spacing", 0);
6379 preview_material_label_desc->hide();
6380 surface->add_child(preview_material_label_desc);
6381
6382 frame_time_gradient = memnew(Gradient);
6383 // The color is set when the theme changes.
6384 frame_time_gradient->add_point(0.5, Color());
6385
6386 top_right_vbox = memnew(VBoxContainer);
6387 top_right_vbox->add_theme_constant_override("separation", 10.0 * EDSCALE);
6388 top_right_vbox->set_anchors_and_offsets_preset(PRESET_TOP_RIGHT, PRESET_MODE_MINSIZE, 10.0 * EDSCALE);
6389 top_right_vbox->set_h_grow_direction(GROW_DIRECTION_BEGIN);
6390
6391 const int navigation_control_size = 150;
6392
6393 position_control = memnew(ViewportNavigationControl);
6394 position_control->set_navigation_mode(Node3DEditorViewport::NAVIGATION_MOVE);
6395 position_control->set_custom_minimum_size(Size2(navigation_control_size, navigation_control_size) * EDSCALE);
6396 position_control->set_h_size_flags(SIZE_SHRINK_END);
6397 position_control->set_anchor_and_offset(SIDE_LEFT, ANCHOR_BEGIN, 0);
6398 position_control->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -navigation_control_size * EDSCALE);
6399 position_control->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_BEGIN, navigation_control_size * EDSCALE);
6400 position_control->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
6401 position_control->set_viewport(this);
6402 surface->add_child(position_control);
6403
6404 look_control = memnew(ViewportNavigationControl);
6405 look_control->set_navigation_mode(Node3DEditorViewport::NAVIGATION_LOOK);
6406 look_control->set_custom_minimum_size(Size2(navigation_control_size, navigation_control_size) * EDSCALE);
6407 look_control->set_h_size_flags(SIZE_SHRINK_END);
6408 look_control->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -navigation_control_size * EDSCALE);
6409 look_control->set_anchor_and_offset(SIDE_TOP, ANCHOR_END, -navigation_control_size * EDSCALE);
6410 look_control->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
6411 look_control->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, 0);
6412 look_control->set_viewport(this);
6413 surface->add_child(look_control);
6414
6415 rotation_control = memnew(ViewportRotationControl);
6416 rotation_control->set_custom_minimum_size(Size2(80, 80) * EDSCALE);
6417 rotation_control->set_h_size_flags(SIZE_SHRINK_END);
6418 rotation_control->set_viewport(this);
6419 rotation_control->set_focus_mode(FOCUS_CLICK);
6420 top_right_vbox->add_child(rotation_control);
6421
6422 frame_time_panel = memnew(PanelContainer);
6423 frame_time_panel->set_mouse_filter(MOUSE_FILTER_IGNORE);
6424 top_right_vbox->add_child(frame_time_panel);
6425 frame_time_panel->hide();
6426
6427 frame_time_vbox = memnew(VBoxContainer);
6428 frame_time_panel->add_child(frame_time_vbox);
6429
6430 // Individual Labels are used to allow coloring each label with its own color.
6431 cpu_time_label = memnew(Label);
6432 frame_time_vbox->add_child(cpu_time_label);
6433
6434 gpu_time_label = memnew(Label);
6435 frame_time_vbox->add_child(gpu_time_label);
6436
6437 fps_label = memnew(Label);
6438 frame_time_vbox->add_child(fps_label);
6439
6440 surface->add_child(top_right_vbox);
6441
6442 accept = nullptr;
6443
6444 freelook_active = false;
6445 freelook_speed = EDITOR_GET("editors/3d/freelook/freelook_base_speed");
6446
6447 selection_menu = memnew(PopupMenu);
6448 add_child(selection_menu);
6449 selection_menu->set_min_size(Size2(100, 0) * EDSCALE);
6450 selection_menu->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditorViewport::_selection_result_pressed));
6451 selection_menu->connect("popup_hide", callable_mp(this, &Node3DEditorViewport::_selection_menu_hide));
6452
6453 if (p_index == 0) {
6454 view_display_menu->get_popup()->set_item_checked(view_display_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER), true);
6455 viewport->set_as_audio_listener_3d(true);
6456 }
6457
6458 ruler = memnew(Node);
6459
6460 ruler_start_point = memnew(Node3D);
6461 ruler_start_point->set_visible(false);
6462
6463 ruler_end_point = memnew(Node3D);
6464 ruler_end_point->set_visible(false);
6465
6466 ruler_material.instantiate();
6467 ruler_material->set_albedo(Color(1.0, 0.9, 0.0, 1.0));
6468 ruler_material->set_flag(BaseMaterial3D::FLAG_DISABLE_FOG, true);
6469 ruler_material->set_shading_mode(BaseMaterial3D::SHADING_MODE_UNSHADED);
6470 ruler_material->set_depth_draw_mode(BaseMaterial3D::DEPTH_DRAW_DISABLED);
6471
6472 ruler_material_xray.instantiate();
6473 ruler_material_xray->set_albedo(Color(1.0, 0.9, 0.0, 0.15));
6474 ruler_material_xray->set_flag(BaseMaterial3D::FLAG_DISABLE_FOG, true);
6475 ruler_material_xray->set_shading_mode(BaseMaterial3D::SHADING_MODE_UNSHADED);
6476 ruler_material_xray->set_flag(BaseMaterial3D::FLAG_DISABLE_DEPTH_TEST, true);
6477 ruler_material_xray->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA);
6478 ruler_material_xray->set_render_priority(BaseMaterial3D::RENDER_PRIORITY_MAX);
6479
6480 geometry.instantiate();
6481
6482 ruler_line = memnew(MeshInstance3D);
6483 ruler_line->set_mesh(geometry);
6484 ruler_line->set_material_override(ruler_material);
6485
6486 ruler_line_xray = memnew(MeshInstance3D);
6487 ruler_line_xray->set_mesh(geometry);
6488 ruler_line_xray->set_material_override(ruler_material_xray);
6489
6490 ruler_label = memnew(Label);
6491 ruler_label->set_visible(false);
6492
6493 ruler->add_child(ruler_start_point);
6494 ruler->add_child(ruler_end_point);
6495 ruler->add_child(ruler_line);
6496 ruler->add_child(ruler_line_xray);
6497
6498 viewport->add_child(ruler_label);
6499
6500 view_type = VIEW_TYPE_USER;
6501 _update_name();
6502 }
6503
6504 Node3DEditorViewport::~Node3DEditorViewport() {
6505 memdelete(ruler);
6506 memdelete(frame_time_gradient);
6507 }
6508
6509 //////////////////////////////////////////////////////////////
6510
6511 void Node3DEditorViewportContainer::gui_input(const Ref<InputEvent> &p_event) {
6512 ERR_FAIL_COND(p_event.is_null());
6513
6514 if (_redirect_freelook_input(p_event)) {
6515 return;
6516 }
6517
6518 Ref<InputEventMouseButton> mb = p_event;
6519
6520 if (mb.is_valid() && mb->get_button_index() == MouseButton::LEFT) {
6521 if (mb->is_pressed()) {
6522 Vector2 size = get_size();
6523
6524 int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
6525 int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
6526
6527 int mid_w = size.width * ratio_h;
6528 int mid_h = size.height * ratio_v;
6529
6530 dragging_h = mb->get_position().x > (mid_w - h_sep / 2) && mb->get_position().x < (mid_w + h_sep / 2);
6531 dragging_v = mb->get_position().y > (mid_h - v_sep / 2) && mb->get_position().y < (mid_h + v_sep / 2);
6532
6533 drag_begin_pos = mb->get_position();
6534 drag_begin_ratio.x = ratio_h;
6535 drag_begin_ratio.y = ratio_v;
6536
6537 switch (view) {
6538 case VIEW_USE_1_VIEWPORT: {
6539 dragging_h = false;
6540 dragging_v = false;
6541
6542 } break;
6543 case VIEW_USE_2_VIEWPORTS: {
6544 dragging_h = false;
6545
6546 } break;
6547 case VIEW_USE_2_VIEWPORTS_ALT: {
6548 dragging_v = false;
6549
6550 } break;
6551 case VIEW_USE_3_VIEWPORTS:
6552 case VIEW_USE_3_VIEWPORTS_ALT:
6553 case VIEW_USE_4_VIEWPORTS: {
6554 // Do nothing.
6555
6556 } break;
6557 }
6558 } else {
6559 dragging_h = false;
6560 dragging_v = false;
6561 }
6562 }
6563
6564 Ref<InputEventMouseMotion> mm = p_event;
6565
6566 if (mm.is_valid()) {
6567 if (view == VIEW_USE_3_VIEWPORTS || view == VIEW_USE_3_VIEWPORTS_ALT || view == VIEW_USE_4_VIEWPORTS) {
6568 Vector2 size = get_size();
6569
6570 int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
6571 int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
6572
6573 int mid_w = size.width * ratio_h;
6574 int mid_h = size.height * ratio_v;
6575
6576 bool was_hovering_h = hovering_h;
6577 bool was_hovering_v = hovering_v;
6578 hovering_h = mm->get_position().x > (mid_w - h_sep / 2) && mm->get_position().x < (mid_w + h_sep / 2);
6579 hovering_v = mm->get_position().y > (mid_h - v_sep / 2) && mm->get_position().y < (mid_h + v_sep / 2);
6580
6581 if (was_hovering_h != hovering_h || was_hovering_v != hovering_v) {
6582 queue_redraw();
6583 }
6584 }
6585
6586 if (dragging_h) {
6587 real_t new_ratio = drag_begin_ratio.x + (mm->get_position().x - drag_begin_pos.x) / get_size().width;
6588 new_ratio = CLAMP(new_ratio, 40 / get_size().width, (get_size().width - 40) / get_size().width);
6589 ratio_h = new_ratio;
6590 queue_sort();
6591 queue_redraw();
6592 }
6593 if (dragging_v) {
6594 real_t new_ratio = drag_begin_ratio.y + (mm->get_position().y - drag_begin_pos.y) / get_size().height;
6595 new_ratio = CLAMP(new_ratio, 40 / get_size().height, (get_size().height - 40) / get_size().height);
6596 ratio_v = new_ratio;
6597 queue_sort();
6598 queue_redraw();
6599 }
6600 }
6601 }
6602
6603 void Node3DEditorViewportContainer::_notification(int p_what) {
6604 switch (p_what) {
6605 case NOTIFICATION_MOUSE_ENTER:
6606 case NOTIFICATION_MOUSE_EXIT: {
6607 mouseover = (p_what == NOTIFICATION_MOUSE_ENTER);
6608 queue_redraw();
6609 } break;
6610
6611 case NOTIFICATION_DRAW: {
6612 if (mouseover && Input::get_singleton()->get_mouse_mode() != Input::MOUSE_MODE_CAPTURED) {
6613 Ref<Texture2D> h_grabber = get_theme_icon(SNAME("grabber"), SNAME("HSplitContainer"));
6614 Ref<Texture2D> v_grabber = get_theme_icon(SNAME("grabber"), SNAME("VSplitContainer"));
6615
6616 Ref<Texture2D> hdiag_grabber = get_editor_theme_icon(SNAME("GuiViewportHdiagsplitter"));
6617 Ref<Texture2D> vdiag_grabber = get_editor_theme_icon(SNAME("GuiViewportVdiagsplitter"));
6618 Ref<Texture2D> vh_grabber = get_editor_theme_icon(SNAME("GuiViewportVhsplitter"));
6619
6620 Vector2 size = get_size();
6621
6622 int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
6623
6624 int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
6625
6626 int mid_w = size.width * ratio_h;
6627 int mid_h = size.height * ratio_v;
6628
6629 int size_left = mid_w - h_sep / 2;
6630 int size_bottom = size.height - mid_h - v_sep / 2;
6631
6632 switch (view) {
6633 case VIEW_USE_1_VIEWPORT: {
6634 // Nothing to show.
6635
6636 } break;
6637 case VIEW_USE_2_VIEWPORTS: {
6638 draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
6639 set_default_cursor_shape(CURSOR_VSPLIT);
6640
6641 } break;
6642 case VIEW_USE_2_VIEWPORTS_ALT: {
6643 draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
6644 set_default_cursor_shape(CURSOR_HSPLIT);
6645
6646 } break;
6647 case VIEW_USE_3_VIEWPORTS: {
6648 if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
6649 draw_texture(hdiag_grabber, Vector2(mid_w - hdiag_grabber->get_width() / 2, mid_h - v_grabber->get_height() / 4));
6650 set_default_cursor_shape(CURSOR_DRAG);
6651 } else if ((hovering_v && !dragging_h) || dragging_v) {
6652 draw_texture(v_grabber, Vector2((size.width - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
6653 set_default_cursor_shape(CURSOR_VSPLIT);
6654 } else if (hovering_h || dragging_h) {
6655 draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, mid_h + v_grabber->get_height() / 2 + (size_bottom - h_grabber->get_height()) / 2));
6656 set_default_cursor_shape(CURSOR_HSPLIT);
6657 }
6658
6659 } break;
6660 case VIEW_USE_3_VIEWPORTS_ALT: {
6661 if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
6662 draw_texture(vdiag_grabber, Vector2(mid_w - vdiag_grabber->get_width() + v_grabber->get_height() / 4, mid_h - vdiag_grabber->get_height() / 2));
6663 set_default_cursor_shape(CURSOR_DRAG);
6664 } else if ((hovering_v && !dragging_h) || dragging_v) {
6665 draw_texture(v_grabber, Vector2((size_left - v_grabber->get_width()) / 2, mid_h - v_grabber->get_height() / 2));
6666 set_default_cursor_shape(CURSOR_VSPLIT);
6667 } else if (hovering_h || dragging_h) {
6668 draw_texture(h_grabber, Vector2(mid_w - h_grabber->get_width() / 2, (size.height - h_grabber->get_height()) / 2));
6669 set_default_cursor_shape(CURSOR_HSPLIT);
6670 }
6671
6672 } break;
6673 case VIEW_USE_4_VIEWPORTS: {
6674 Vector2 half(mid_w, mid_h);
6675 if ((hovering_v && hovering_h && !dragging_v && !dragging_h) || (dragging_v && dragging_h)) {
6676 draw_texture(vh_grabber, half - vh_grabber->get_size() / 2.0);
6677 set_default_cursor_shape(CURSOR_DRAG);
6678 } else if ((hovering_v && !dragging_h) || dragging_v) {
6679 draw_texture(v_grabber, half - v_grabber->get_size() / 2.0);
6680 set_default_cursor_shape(CURSOR_VSPLIT);
6681 } else if (hovering_h || dragging_h) {
6682 draw_texture(h_grabber, half - h_grabber->get_size() / 2.0);
6683 set_default_cursor_shape(CURSOR_HSPLIT);
6684 }
6685
6686 } break;
6687 }
6688 }
6689 } break;
6690
6691 case NOTIFICATION_SORT_CHILDREN: {
6692 Node3DEditorViewport *viewports[4];
6693 int vc = 0;
6694 for (int i = 0; i < get_child_count(); i++) {
6695 viewports[vc] = Object::cast_to<Node3DEditorViewport>(get_child(i));
6696 if (viewports[vc]) {
6697 vc++;
6698 }
6699 }
6700
6701 ERR_FAIL_COND(vc != 4);
6702
6703 Size2 size = get_size();
6704
6705 if (size.x < 10 || size.y < 10) {
6706 for (int i = 0; i < 4; i++) {
6707 viewports[i]->hide();
6708 }
6709 return;
6710 }
6711 int h_sep = get_theme_constant(SNAME("separation"), SNAME("HSplitContainer"));
6712
6713 int v_sep = get_theme_constant(SNAME("separation"), SNAME("VSplitContainer"));
6714
6715 int mid_w = size.width * ratio_h;
6716 int mid_h = size.height * ratio_v;
6717
6718 int size_left = mid_w - h_sep / 2;
6719 int size_right = size.width - mid_w - h_sep / 2;
6720
6721 int size_top = mid_h - v_sep / 2;
6722 int size_bottom = size.height - mid_h - v_sep / 2;
6723
6724 switch (view) {
6725 case VIEW_USE_1_VIEWPORT: {
6726 viewports[0]->show();
6727 for (int i = 1; i < 4; i++) {
6728 viewports[i]->hide();
6729 }
6730
6731 fit_child_in_rect(viewports[0], Rect2(Vector2(), size));
6732
6733 } break;
6734 case VIEW_USE_2_VIEWPORTS: {
6735 for (int i = 0; i < 4; i++) {
6736 if (i == 1 || i == 3) {
6737 viewports[i]->hide();
6738 } else {
6739 viewports[i]->show();
6740 }
6741 }
6742
6743 fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
6744 fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size.width, size_bottom)));
6745
6746 } break;
6747 case VIEW_USE_2_VIEWPORTS_ALT: {
6748 for (int i = 0; i < 4; i++) {
6749 if (i == 1 || i == 3) {
6750 viewports[i]->hide();
6751 } else {
6752 viewports[i]->show();
6753 }
6754 }
6755 fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size.height)));
6756 fit_child_in_rect(viewports[2], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
6757
6758 } break;
6759 case VIEW_USE_3_VIEWPORTS: {
6760 for (int i = 0; i < 4; i++) {
6761 if (i == 1) {
6762 viewports[i]->hide();
6763 } else {
6764 viewports[i]->show();
6765 }
6766 }
6767
6768 fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size.width, size_top)));
6769 fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
6770 fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
6771
6772 } break;
6773 case VIEW_USE_3_VIEWPORTS_ALT: {
6774 for (int i = 0; i < 4; i++) {
6775 if (i == 1) {
6776 viewports[i]->hide();
6777 } else {
6778 viewports[i]->show();
6779 }
6780 }
6781
6782 fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
6783 fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
6784 fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size.height)));
6785
6786 } break;
6787 case VIEW_USE_4_VIEWPORTS: {
6788 for (int i = 0; i < 4; i++) {
6789 viewports[i]->show();
6790 }
6791
6792 fit_child_in_rect(viewports[0], Rect2(Vector2(), Vector2(size_left, size_top)));
6793 fit_child_in_rect(viewports[1], Rect2(Vector2(mid_w + h_sep / 2, 0), Vector2(size_right, size_top)));
6794 fit_child_in_rect(viewports[2], Rect2(Vector2(0, mid_h + v_sep / 2), Vector2(size_left, size_bottom)));
6795 fit_child_in_rect(viewports[3], Rect2(Vector2(mid_w + h_sep / 2, mid_h + v_sep / 2), Vector2(size_right, size_bottom)));
6796
6797 } break;
6798 }
6799 } break;
6800 }
6801 }
6802
6803 void Node3DEditorViewportContainer::set_view(View p_view) {
6804 view = p_view;
6805 queue_sort();
6806 }
6807
6808 Node3DEditorViewportContainer::View Node3DEditorViewportContainer::get_view() {
6809 return view;
6810 }
6811
6812 Node3DEditorViewportContainer::Node3DEditorViewportContainer() {
6813 set_clip_contents(true);
6814 view = VIEW_USE_1_VIEWPORT;
6815 mouseover = false;
6816 ratio_h = 0.5;
6817 ratio_v = 0.5;
6818 hovering_v = false;
6819 hovering_h = false;
6820 dragging_v = false;
6821 dragging_h = false;
6822 }
6823
6824 ///////////////////////////////////////////////////////////////////
6825
6826 Node3DEditor *Node3DEditor::singleton = nullptr;
6827
6828 Node3DEditorSelectedItem::~Node3DEditorSelectedItem() {
6829 ERR_FAIL_NULL(RenderingServer::get_singleton());
6830 if (sbox_instance.is_valid()) {
6831 RenderingServer::get_singleton()->free_rid(sbox_instance);
6832 }
6833 if (sbox_instance_offset.is_valid()) {
6834 RenderingServer::get_singleton()->free_rid(sbox_instance_offset);
6835 }
6836 if (sbox_instance_xray.is_valid()) {
6837 RenderingServer::get_singleton()->free_rid(sbox_instance_xray);
6838 }
6839 if (sbox_instance_xray_offset.is_valid()) {
6840 RenderingServer::get_singleton()->free_rid(sbox_instance_xray_offset);
6841 }
6842 }
6843
6844 void Node3DEditor::select_gizmo_highlight_axis(int p_axis) {
6845 for (int i = 0; i < 3; i++) {
6846 move_gizmo[i]->surface_set_material(0, i == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
6847 move_plane_gizmo[i]->surface_set_material(0, (i + 6) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
6848 scale_gizmo[i]->surface_set_material(0, (i + 9) == p_axis ? gizmo_color_hl[i] : gizmo_color[i]);
6849 scale_plane_gizmo[i]->surface_set_material(0, (i + 12) == p_axis ? plane_gizmo_color_hl[i] : plane_gizmo_color[i]);
6850 }
6851
6852 for (int i = 0; i < 4; i++) {
6853 bool highlight;
6854 if (i == 3) {
6855 highlight = (p_axis == 15);
6856 } else {
6857 highlight = (i + 3) == p_axis;
6858 }
6859 rotate_gizmo[i]->surface_set_material(0, highlight ? rotate_gizmo_color_hl[i] : rotate_gizmo_color[i]);
6860 }
6861 }
6862
6863 void Node3DEditor::update_transform_gizmo() {
6864 int count = 0;
6865 bool local_gizmo_coords = are_local_coords_enabled();
6866
6867 Vector3 gizmo_center;
6868 Basis gizmo_basis;
6869
6870 Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
6871
6872 if (se && se->gizmo.is_valid()) {
6873 for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
6874 Transform3D xf = se->sp->get_global_transform() * se->gizmo->get_subgizmo_transform(E.key);
6875 if (!xf.is_finite()) {
6876 continue;
6877 }
6878 gizmo_center += xf.origin;
6879 if ((unsigned int)count == se->subgizmos.size() - 1 && local_gizmo_coords) {
6880 gizmo_basis = xf.basis;
6881 }
6882 count++;
6883 }
6884 } else {
6885 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
6886 for (Node *E : selection) {
6887 Node3D *sp = Object::cast_to<Node3D>(E);
6888 if (!sp) {
6889 continue;
6890 }
6891
6892 if (sp->has_meta("_edit_lock_")) {
6893 continue;
6894 }
6895
6896 Node3DEditorSelectedItem *sel_item = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
6897 if (!sel_item) {
6898 continue;
6899 }
6900
6901 Transform3D xf = sel_item->sp->get_global_transform();
6902 if (!xf.is_finite()) {
6903 continue;
6904 }
6905 gizmo_center += xf.origin;
6906 if (count == selection.size() - 1 && local_gizmo_coords) {
6907 gizmo_basis = xf.basis;
6908 }
6909 count++;
6910 }
6911 }
6912
6913 gizmo.visible = count > 0;
6914 gizmo.transform.origin = (count > 0) ? gizmo_center / count : Vector3();
6915 gizmo.transform.basis = gizmo_basis;
6916
6917 for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
6918 viewports[i]->update_transform_gizmo_view();
6919 }
6920 }
6921
6922 void _update_all_gizmos(Node *p_node) {
6923 for (int i = p_node->get_child_count() - 1; 0 <= i; --i) {
6924 Node3D *spatial_node = Object::cast_to<Node3D>(p_node->get_child(i));
6925 if (spatial_node) {
6926 spatial_node->update_gizmos();
6927 }
6928
6929 _update_all_gizmos(p_node->get_child(i));
6930 }
6931 }
6932
6933 void Node3DEditor::update_all_gizmos(Node *p_node) {
6934 if (!p_node && is_inside_tree()) {
6935 p_node = get_tree()->get_edited_scene_root();
6936 }
6937
6938 if (!p_node) {
6939 // No edited scene, so nothing to update.
6940 return;
6941 }
6942 _update_all_gizmos(p_node);
6943 }
6944
6945 Object *Node3DEditor::_get_editor_data(Object *p_what) {
6946 Node3D *sp = Object::cast_to<Node3D>(p_what);
6947 if (!sp) {
6948 return nullptr;
6949 }
6950
6951 Node3DEditorSelectedItem *si = memnew(Node3DEditorSelectedItem);
6952
6953 si->sp = sp;
6954 si->sbox_instance = RenderingServer::get_singleton()->instance_create2(
6955 selection_box->get_rid(),
6956 sp->get_world_3d()->get_scenario());
6957 si->sbox_instance_offset = RenderingServer::get_singleton()->instance_create2(
6958 selection_box->get_rid(),
6959 sp->get_world_3d()->get_scenario());
6960 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
6961 si->sbox_instance,
6962 RS::SHADOW_CASTING_SETTING_OFF);
6963 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
6964 si->sbox_instance_offset,
6965 RS::SHADOW_CASTING_SETTING_OFF);
6966 // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
6967 // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
6968 RS::get_singleton()->instance_set_layer_mask(si->sbox_instance, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
6969 RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
6970 RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
6971 RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
6972 RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
6973 RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_offset, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
6974 si->sbox_instance_xray = RenderingServer::get_singleton()->instance_create2(
6975 selection_box_xray->get_rid(),
6976 sp->get_world_3d()->get_scenario());
6977 si->sbox_instance_xray_offset = RenderingServer::get_singleton()->instance_create2(
6978 selection_box_xray->get_rid(),
6979 sp->get_world_3d()->get_scenario());
6980 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
6981 si->sbox_instance_xray,
6982 RS::SHADOW_CASTING_SETTING_OFF);
6983 RS::get_singleton()->instance_geometry_set_cast_shadows_setting(
6984 si->sbox_instance_xray_offset,
6985 RS::SHADOW_CASTING_SETTING_OFF);
6986 // Use the Edit layer to hide the selection box when View Gizmos is disabled, since it is a bit distracting.
6987 // It's still possible to approximately guess what is selected by looking at the manipulation gizmo position.
6988 RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
6989 RS::get_singleton()->instance_set_layer_mask(si->sbox_instance_xray_offset, 1 << Node3DEditorViewport::GIZMO_EDIT_LAYER);
6990 RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
6991 RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
6992 RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray_offset, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
6993 RS::get_singleton()->instance_geometry_set_flag(si->sbox_instance_xray_offset, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
6994
6995 return si;
6996 }
6997
6998 void Node3DEditor::_generate_selection_boxes() {
6999 // Use two AABBs to create the illusion of a slightly thicker line.
7000 AABB aabb(Vector3(), Vector3(1, 1, 1));
7001
7002 // Create a x-ray (visible through solid surfaces) and standard version of the selection box.
7003 // Both will be drawn at the same position, but with different opacity.
7004 // This lets the user see where the selection is while still having a sense of depth.
7005 Ref<SurfaceTool> st = memnew(SurfaceTool);
7006 Ref<SurfaceTool> st_xray = memnew(SurfaceTool);
7007 Ref<SurfaceTool> active_st = memnew(SurfaceTool);
7008 Ref<SurfaceTool> active_st_xray = memnew(SurfaceTool);
7009
7010 st->begin(Mesh::PRIMITIVE_LINES);
7011 st_xray->begin(Mesh::PRIMITIVE_LINES);
7012 active_st->begin(Mesh::PRIMITIVE_LINES);
7013 active_st_xray->begin(Mesh::PRIMITIVE_LINES);
7014 for (int i = 0; i < 12; i++) {
7015 Vector3 a, b;
7016 aabb.get_edge(i, a, b);
7017
7018 st->add_vertex(a);
7019 st->add_vertex(b);
7020 active_st->add_vertex(a);
7021 active_st->add_vertex(b);
7022 st_xray->add_vertex(a);
7023 st_xray->add_vertex(b);
7024 active_st_xray->add_vertex(a);
7025 active_st_xray->add_vertex(b);
7026 }
7027
7028 const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color");
7029 const Color active_selection_box_color = EDITOR_GET("editors/3d/active_selection_box_color");
7030
7031 selection_box_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
7032 selection_box_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
7033 selection_box_mat->set_albedo(selection_box_color);
7034 selection_box_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
7035 st->set_material(selection_box_mat);
7036 selection_box = st->commit();
7037
7038 selection_box_mat_xray->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
7039 selection_box_mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
7040 selection_box_mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_DEPTH_TEST, true);
7041 selection_box_mat_xray->set_albedo(selection_box_color * Color(1, 1, 1, 0.15));
7042 selection_box_mat_xray->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
7043 st_xray->set_material(selection_box_mat_xray);
7044 selection_box_xray = st_xray->commit();
7045
7046 active_selection_box_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
7047 active_selection_box_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
7048 active_selection_box_mat->set_albedo(active_selection_box_color);
7049 active_selection_box_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
7050 active_st->set_material(active_selection_box_mat);
7051 active_selection_box = active_st->commit();
7052
7053 active_selection_box_mat_xray->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
7054 active_selection_box_mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
7055 active_selection_box_mat_xray->set_flag(StandardMaterial3D::FLAG_DISABLE_DEPTH_TEST, true);
7056 active_selection_box_mat_xray->set_albedo(active_selection_box_color * Color(1, 1, 1, 0.15));
7057 active_selection_box_mat_xray->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
7058 active_st_xray->set_material(active_selection_box_mat_xray);
7059 active_selection_box_xray = active_st_xray->commit();
7060 }
7061
7062 Dictionary Node3DEditor::get_state() const {
7063 Dictionary d;
7064
7065 d["snap_enabled"] = snap_enabled;
7066 d["translate_snap"] = snap_translate_value;
7067 d["rotate_snap"] = snap_rotate_value;
7068 d["scale_snap"] = snap_scale_value;
7069
7070 d["local_coords"] = tool_option_button[TOOL_OPT_LOCAL_COORDS]->is_pressed();
7071
7072 int vc = 0;
7073 if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
7074 vc = 1;
7075 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
7076 vc = 2;
7077 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
7078 vc = 3;
7079 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
7080 vc = 4;
7081 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
7082 vc = 5;
7083 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
7084 vc = 6;
7085 }
7086
7087 d["viewport_mode"] = vc;
7088 Array vpdata;
7089 for (int i = 0; i < 4; i++) {
7090 vpdata.push_back(viewports[i]->get_state());
7091 }
7092
7093 d["viewports"] = vpdata;
7094
7095 d["show_grid"] = view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_GRID));
7096 d["show_origin"] = view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN));
7097 d["fov"] = get_fov();
7098 d["znear"] = get_znear();
7099 d["zfar"] = get_zfar();
7100
7101 Dictionary gizmos_status;
7102 for (int i = 0; i < gizmo_plugins_by_name.size(); i++) {
7103 if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
7104 continue;
7105 }
7106 int state = gizmos_menu->get_item_state(gizmos_menu->get_item_index(i));
7107 String name = gizmo_plugins_by_name[i]->get_gizmo_name();
7108 gizmos_status[name] = state;
7109 }
7110
7111 d["gizmos_status"] = gizmos_status;
7112 {
7113 Dictionary pd;
7114
7115 pd["sun_rotation"] = sun_rotation;
7116
7117 pd["environ_sky_color"] = environ_sky_color->get_pick_color();
7118 pd["environ_ground_color"] = environ_ground_color->get_pick_color();
7119 pd["environ_energy"] = environ_energy->get_value();
7120 pd["environ_glow_enabled"] = environ_glow_button->is_pressed();
7121 pd["environ_tonemap_enabled"] = environ_tonemap_button->is_pressed();
7122 pd["environ_ao_enabled"] = environ_ao_button->is_pressed();
7123 pd["environ_gi_enabled"] = environ_gi_button->is_pressed();
7124 pd["sun_shadow_max_distance"] = sun_shadow_max_distance->get_value();
7125
7126 pd["sun_color"] = sun_color->get_pick_color();
7127 pd["sun_energy"] = sun_energy->get_value();
7128
7129 pd["sun_enabled"] = sun_button->is_pressed();
7130 pd["environ_enabled"] = environ_button->is_pressed();
7131
7132 d["preview_sun_env"] = pd;
7133 }
7134
7135 return d;
7136 }
7137
7138 void Node3DEditor::set_state(const Dictionary &p_state) {
7139 Dictionary d = p_state;
7140
7141 if (d.has("snap_enabled")) {
7142 snap_enabled = d["snap_enabled"];
7143 tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(d["snap_enabled"]);
7144 }
7145
7146 if (d.has("translate_snap")) {
7147 snap_translate_value = d["translate_snap"];
7148 }
7149
7150 if (d.has("rotate_snap")) {
7151 snap_rotate_value = d["rotate_snap"];
7152 }
7153
7154 if (d.has("scale_snap")) {
7155 snap_scale_value = d["scale_snap"];
7156 }
7157
7158 _snap_update();
7159
7160 if (d.has("local_coords")) {
7161 tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(d["local_coords"]);
7162 update_transform_gizmo();
7163 }
7164
7165 if (d.has("viewport_mode")) {
7166 int vc = d["viewport_mode"];
7167
7168 if (vc == 1) {
7169 _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
7170 } else if (vc == 2) {
7171 _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
7172 } else if (vc == 3) {
7173 _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
7174 } else if (vc == 4) {
7175 _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
7176 } else if (vc == 5) {
7177 _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
7178 } else if (vc == 6) {
7179 _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
7180 }
7181 }
7182
7183 if (d.has("zfar")) {
7184 settings_zfar->set_value(double(d["zfar"]));
7185 }
7186 if (d.has("znear")) {
7187 settings_znear->set_value(double(d["znear"]));
7188 }
7189 if (d.has("fov")) {
7190 settings_fov->set_value(double(d["fov"]));
7191 }
7192
7193 if (d.has("viewports")) {
7194 Array vp = d["viewports"];
7195 uint32_t vp_size = static_cast<uint32_t>(vp.size());
7196 if (vp_size > VIEWPORTS_COUNT) {
7197 WARN_PRINT("Ignoring superfluous viewport settings from spatial editor state.");
7198 vp_size = VIEWPORTS_COUNT;
7199 }
7200
7201 for (uint32_t i = 0; i < vp_size; i++) {
7202 viewports[i]->set_state(vp[i]);
7203 }
7204 }
7205
7206 if (d.has("show_grid")) {
7207 bool use = d["show_grid"];
7208
7209 if (use != view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
7210 _menu_item_pressed(MENU_VIEW_GRID);
7211 }
7212 }
7213
7214 if (d.has("show_origin")) {
7215 bool use = d["show_origin"];
7216
7217 if (use != view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
7218 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use);
7219 RenderingServer::get_singleton()->instance_set_visible(origin_instance, use);
7220 }
7221 }
7222
7223 if (d.has("gizmos_status")) {
7224 Dictionary gizmos_status = d["gizmos_status"];
7225
7226 for (int j = 0; j < gizmo_plugins_by_name.size(); ++j) {
7227 if (!gizmo_plugins_by_name[j]->can_be_hidden()) {
7228 continue;
7229 }
7230 int state = EditorNode3DGizmoPlugin::VISIBLE;
7231 for (const KeyValue<Variant, Variant> &kv : gizmos_status) {
7232 if (gizmo_plugins_by_name.write[j]->get_gizmo_name() == String(kv.key)) {
7233 state = kv.value;
7234 break;
7235 }
7236 }
7237
7238 gizmo_plugins_by_name.write[j]->set_state(state);
7239 }
7240 _update_gizmos_menu();
7241 }
7242
7243 if (d.has("preview_sun_env")) {
7244 sun_environ_updating = true;
7245 Dictionary pd = d["preview_sun_env"];
7246 sun_rotation = pd["sun_rotation"];
7247
7248 environ_sky_color->set_pick_color(pd["environ_sky_color"]);
7249 environ_ground_color->set_pick_color(pd["environ_ground_color"]);
7250 environ_energy->set_value_no_signal(pd["environ_energy"]);
7251 environ_glow_button->set_pressed_no_signal(pd["environ_glow_enabled"]);
7252 environ_tonemap_button->set_pressed_no_signal(pd["environ_tonemap_enabled"]);
7253 environ_ao_button->set_pressed_no_signal(pd["environ_ao_enabled"]);
7254 environ_gi_button->set_pressed_no_signal(pd["environ_gi_enabled"]);
7255 sun_shadow_max_distance->set_value_no_signal(pd["sun_shadow_max_distance"]);
7256
7257 sun_color->set_pick_color(pd["sun_color"]);
7258 sun_energy->set_value_no_signal(pd["sun_energy"]);
7259
7260 sun_button->set_pressed(pd["sun_enabled"]);
7261 environ_button->set_pressed(pd["environ_enabled"]);
7262
7263 sun_environ_updating = false;
7264
7265 _preview_settings_changed();
7266 _update_preview_environment();
7267 } else {
7268 _load_default_preview_settings();
7269 sun_button->set_pressed(true);
7270 environ_button->set_pressed(true);
7271 _preview_settings_changed();
7272 _update_preview_environment();
7273 }
7274 }
7275
7276 void Node3DEditor::edit(Node3D *p_spatial) {
7277 if (p_spatial != selected) {
7278 if (selected) {
7279 Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
7280 for (int i = 0; i < gizmos.size(); i++) {
7281 Ref<EditorNode3DGizmo> seg = gizmos[i];
7282 if (seg.is_null()) {
7283 continue;
7284 }
7285 seg->set_selected(false);
7286 }
7287
7288 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
7289 if (se) {
7290 se->gizmo.unref();
7291 se->subgizmos.clear();
7292 }
7293
7294 selected->update_gizmos();
7295 }
7296
7297 selected = p_spatial;
7298 current_hover_gizmo = Ref<EditorNode3DGizmo>();
7299 current_hover_gizmo_handle = -1;
7300 current_hover_gizmo_handle_secondary = false;
7301
7302 if (selected) {
7303 Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
7304 for (int i = 0; i < gizmos.size(); i++) {
7305 Ref<EditorNode3DGizmo> seg = gizmos[i];
7306 if (seg.is_null()) {
7307 continue;
7308 }
7309 seg->set_selected(true);
7310 }
7311 selected->update_gizmos();
7312 }
7313 }
7314 }
7315
7316 void Node3DEditor::_snap_changed() {
7317 snap_translate_value = snap_translate->get_value();
7318 snap_rotate_value = snap_rotate->get_value();
7319 snap_scale_value = snap_scale->get_value();
7320
7321 EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_translate_value", snap_translate_value);
7322 EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_rotate_value", snap_rotate_value);
7323 EditorSettings::get_singleton()->set_project_metadata("3d_editor", "snap_scale_value", snap_scale_value);
7324 }
7325
7326 void Node3DEditor::_snap_update() {
7327 snap_translate->set_value(snap_translate_value);
7328 snap_rotate->set_value(snap_rotate_value);
7329 snap_scale->set_value(snap_scale_value);
7330 }
7331
7332 void Node3DEditor::_xform_dialog_action() {
7333 Transform3D t;
7334 //translation
7335 Vector3 scale;
7336 Vector3 rotate;
7337 Vector3 translate;
7338
7339 for (int i = 0; i < 3; i++) {
7340 translate[i] = xform_translate[i]->get_text().to_float();
7341 rotate[i] = Math::deg_to_rad(xform_rotate[i]->get_text().to_float());
7342 scale[i] = xform_scale[i]->get_text().to_float();
7343 }
7344
7345 t.basis.scale(scale);
7346 t.basis.rotate(rotate);
7347 t.origin = translate;
7348
7349 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
7350 undo_redo->create_action(TTR("XForm Dialog"));
7351
7352 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
7353
7354 for (Node *E : selection) {
7355 Node3D *sp = Object::cast_to<Node3D>(E);
7356 if (!sp) {
7357 continue;
7358 }
7359
7360 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
7361 if (!se) {
7362 continue;
7363 }
7364
7365 bool post = xform_type->get_selected() > 0;
7366
7367 Transform3D tr = sp->get_global_gizmo_transform();
7368 if (post) {
7369 tr = tr * t;
7370 } else {
7371 tr.basis = t.basis * tr.basis;
7372 tr.origin += t.origin;
7373 }
7374
7375 Node3D *parent = sp->get_parent_node_3d();
7376 Transform3D local_tr = parent ? parent->get_global_transform().affine_inverse() * tr : tr;
7377 undo_redo->add_do_method(sp, "set_transform", local_tr);
7378 undo_redo->add_undo_method(sp, "set_transform", sp->get_transform());
7379 }
7380 undo_redo->commit_action();
7381 }
7382
7383 void Node3DEditor::_menu_item_toggled(bool pressed, int p_option) {
7384 switch (p_option) {
7385 case MENU_TOOL_LOCAL_COORDS: {
7386 tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_pressed(pressed);
7387 update_transform_gizmo();
7388 } break;
7389
7390 case MENU_TOOL_USE_SNAP: {
7391 tool_option_button[TOOL_OPT_USE_SNAP]->set_pressed(pressed);
7392 snap_enabled = pressed;
7393 } break;
7394 }
7395 }
7396
7397 void Node3DEditor::_menu_gizmo_toggled(int p_option) {
7398 const int idx = gizmos_menu->get_item_index(p_option);
7399 gizmos_menu->toggle_item_multistate(idx);
7400
7401 // Change icon
7402 const int state = gizmos_menu->get_item_state(idx);
7403 switch (state) {
7404 case EditorNode3DGizmoPlugin::VISIBLE:
7405 gizmos_menu->set_item_icon(idx, get_editor_theme_icon(SNAME("GuiVisibilityVisible")));
7406 break;
7407 case EditorNode3DGizmoPlugin::ON_TOP:
7408 gizmos_menu->set_item_icon(idx, get_editor_theme_icon(SNAME("GuiVisibilityXray")));
7409 break;
7410 case EditorNode3DGizmoPlugin::HIDDEN:
7411 gizmos_menu->set_item_icon(idx, get_editor_theme_icon(SNAME("GuiVisibilityHidden")));
7412 break;
7413 }
7414
7415 gizmo_plugins_by_name.write[p_option]->set_state(state);
7416
7417 update_all_gizmos();
7418 }
7419
7420 void Node3DEditor::_menu_item_pressed(int p_option) {
7421 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
7422 switch (p_option) {
7423 case MENU_TOOL_TRANSFORM:
7424 case MENU_TOOL_MOVE:
7425 case MENU_TOOL_ROTATE:
7426 case MENU_TOOL_SCALE:
7427 case MENU_TOOL_SELECT:
7428 case MENU_TOOL_LIST_SELECT: {
7429 for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
7430 if (viewports[i]->_edit.mode != Node3DEditorViewport::TRANSFORM_NONE) {
7431 viewports[i]->commit_transform();
7432 }
7433 }
7434
7435 for (int i = 0; i < TOOL_MAX; i++) {
7436 tool_button[i]->set_pressed(i == p_option);
7437 }
7438 tool_mode = (ToolMode)p_option;
7439 update_transform_gizmo();
7440
7441 } break;
7442 case MENU_TRANSFORM_CONFIGURE_SNAP: {
7443 snap_dialog->popup_centered(Size2(200, 180));
7444 } break;
7445 case MENU_TRANSFORM_DIALOG: {
7446 for (int i = 0; i < 3; i++) {
7447 xform_translate[i]->set_text("0");
7448 xform_rotate[i]->set_text("0");
7449 xform_scale[i]->set_text("1");
7450 }
7451
7452 xform_dialog->popup_centered(Size2(320, 240) * EDSCALE);
7453
7454 } break;
7455 case MENU_VIEW_USE_1_VIEWPORT: {
7456 viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_1_VIEWPORT);
7457 if (last_used_viewport > 0) {
7458 last_used_viewport = 0;
7459 }
7460
7461 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true);
7462 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
7463 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
7464 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
7465 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
7466 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
7467
7468 } break;
7469 case MENU_VIEW_USE_2_VIEWPORTS: {
7470 viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_2_VIEWPORTS);
7471 if (last_used_viewport > 1) {
7472 last_used_viewport = 0;
7473 }
7474
7475 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
7476 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true);
7477 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
7478 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
7479 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
7480 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
7481
7482 } break;
7483 case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
7484 viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_2_VIEWPORTS_ALT);
7485 if (last_used_viewport > 1) {
7486 last_used_viewport = 0;
7487 }
7488
7489 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
7490 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
7491 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
7492 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
7493 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true);
7494 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
7495
7496 } break;
7497 case MENU_VIEW_USE_3_VIEWPORTS: {
7498 viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_3_VIEWPORTS);
7499 if (last_used_viewport > 2) {
7500 last_used_viewport = 0;
7501 }
7502
7503 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
7504 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
7505 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true);
7506 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
7507 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
7508 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
7509
7510 } break;
7511 case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
7512 viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_3_VIEWPORTS_ALT);
7513 if (last_used_viewport > 2) {
7514 last_used_viewport = 0;
7515 }
7516
7517 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
7518 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
7519 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
7520 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false);
7521 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
7522 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true);
7523
7524 } break;
7525 case MENU_VIEW_USE_4_VIEWPORTS: {
7526 viewport_base->set_view(Node3DEditorViewportContainer::VIEW_USE_4_VIEWPORTS);
7527
7528 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false);
7529 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false);
7530 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false);
7531 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true);
7532 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false);
7533 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false);
7534
7535 } break;
7536 case MENU_VIEW_ORIGIN: {
7537 bool is_checked = view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(p_option));
7538
7539 origin_enabled = !is_checked;
7540 RenderingServer::get_singleton()->instance_set_visible(origin_instance, origin_enabled);
7541 // Update the grid since its appearance depends on whether the origin is enabled
7542 _finish_grid();
7543 _init_grid();
7544
7545 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(p_option), origin_enabled);
7546 } break;
7547 case MENU_VIEW_GRID: {
7548 bool is_checked = view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(p_option));
7549
7550 grid_enabled = !is_checked;
7551
7552 for (int i = 0; i < 3; ++i) {
7553 if (grid_enable[i]) {
7554 grid_visible[i] = grid_enabled;
7555 }
7556 }
7557 _finish_grid();
7558 _init_grid();
7559
7560 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(p_option), grid_enabled);
7561
7562 } break;
7563 case MENU_VIEW_CAMERA_SETTINGS: {
7564 settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size() + Size2(50, 50));
7565 } break;
7566 case MENU_SNAP_TO_FLOOR: {
7567 snap_selected_nodes_to_floor();
7568 } break;
7569 case MENU_LOCK_SELECTED: {
7570 undo_redo->create_action(TTR("Lock Selected"));
7571
7572 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
7573
7574 for (Node *E : selection) {
7575 Node3D *spatial = Object::cast_to<Node3D>(E);
7576 if (!spatial || !spatial->is_inside_tree()) {
7577 continue;
7578 }
7579
7580 undo_redo->add_do_method(spatial, "set_meta", "_edit_lock_", true);
7581 undo_redo->add_undo_method(spatial, "remove_meta", "_edit_lock_");
7582 undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
7583 undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
7584 }
7585
7586 undo_redo->add_do_method(this, "_refresh_menu_icons");
7587 undo_redo->add_undo_method(this, "_refresh_menu_icons");
7588 undo_redo->commit_action();
7589 } break;
7590 case MENU_UNLOCK_SELECTED: {
7591 undo_redo->create_action(TTR("Unlock Selected"));
7592
7593 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
7594
7595 for (Node *E : selection) {
7596 Node3D *spatial = Object::cast_to<Node3D>(E);
7597 if (!spatial || !spatial->is_inside_tree()) {
7598 continue;
7599 }
7600
7601 undo_redo->add_do_method(spatial, "remove_meta", "_edit_lock_");
7602 undo_redo->add_undo_method(spatial, "set_meta", "_edit_lock_", true);
7603 undo_redo->add_do_method(this, "emit_signal", "item_lock_status_changed");
7604 undo_redo->add_undo_method(this, "emit_signal", "item_lock_status_changed");
7605 }
7606
7607 undo_redo->add_do_method(this, "_refresh_menu_icons");
7608 undo_redo->add_undo_method(this, "_refresh_menu_icons");
7609 undo_redo->commit_action();
7610 } break;
7611 case MENU_GROUP_SELECTED: {
7612 undo_redo->create_action(TTR("Group Selected"));
7613
7614 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
7615
7616 for (Node *E : selection) {
7617 Node3D *spatial = Object::cast_to<Node3D>(E);
7618 if (!spatial || !spatial->is_inside_tree()) {
7619 continue;
7620 }
7621
7622 undo_redo->add_do_method(spatial, "set_meta", "_edit_group_", true);
7623 undo_redo->add_undo_method(spatial, "remove_meta", "_edit_group_");
7624 undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
7625 undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
7626 }
7627
7628 undo_redo->add_do_method(this, "_refresh_menu_icons");
7629 undo_redo->add_undo_method(this, "_refresh_menu_icons");
7630 undo_redo->commit_action();
7631 } break;
7632 case MENU_UNGROUP_SELECTED: {
7633 undo_redo->create_action(TTR("Ungroup Selected"));
7634 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
7635
7636 for (Node *E : selection) {
7637 Node3D *spatial = Object::cast_to<Node3D>(E);
7638 if (!spatial || !spatial->is_inside_tree()) {
7639 continue;
7640 }
7641
7642 undo_redo->add_do_method(spatial, "remove_meta", "_edit_group_");
7643 undo_redo->add_undo_method(spatial, "set_meta", "_edit_group_", true);
7644 undo_redo->add_do_method(this, "emit_signal", "item_group_status_changed");
7645 undo_redo->add_undo_method(this, "emit_signal", "item_group_status_changed");
7646 }
7647
7648 undo_redo->add_do_method(this, "_refresh_menu_icons");
7649 undo_redo->add_undo_method(this, "_refresh_menu_icons");
7650 undo_redo->commit_action();
7651 } break;
7652 case MENU_RULER: {
7653 for (int i = 0; i < TOOL_MAX; i++) {
7654 tool_button[i]->set_pressed(i == p_option);
7655 }
7656 tool_button[TOOL_RULER]->set_pressed(true);
7657 tool_mode = ToolMode::TOOL_RULER;
7658 update_transform_gizmo();
7659 } break;
7660 }
7661 }
7662
7663 void Node3DEditor::_init_indicators() {
7664 {
7665 origin_enabled = true;
7666 grid_enabled = true;
7667
7668 Ref<Shader> origin_shader = memnew(Shader);
7669 origin_shader->set_code(R"(
7670 // 3D editor origin line shader.
7671
7672 shader_type spatial;
7673 render_mode blend_mix, cull_disabled, unshaded, fog_disabled;
7674
7675 void vertex() {
7676 vec3 point_a = MODEL_MATRIX[3].xyz;
7677 // Encoded in scale.
7678 vec3 point_b = vec3(MODEL_MATRIX[0].x, MODEL_MATRIX[1].y, MODEL_MATRIX[2].z);
7679
7680 // Points are already in world space, so no need for MODEL_MATRIX anymore.
7681 vec4 clip_a = PROJECTION_MATRIX * (VIEW_MATRIX * vec4(point_a, 1.0));
7682 vec4 clip_b = PROJECTION_MATRIX * (VIEW_MATRIX * vec4(point_b, 1.0));
7683
7684 vec2 screen_a = VIEWPORT_SIZE * (0.5 * clip_a.xy / clip_a.w + 0.5);
7685 vec2 screen_b = VIEWPORT_SIZE * (0.5 * clip_b.xy / clip_b.w + 0.5);
7686
7687 vec2 x_basis = normalize(screen_b - screen_a);
7688 vec2 y_basis = vec2(-x_basis.y, x_basis.x);
7689
7690 float width = 3.0;
7691 vec2 screen_point_a = screen_a + width * (VERTEX.x * x_basis + VERTEX.y * y_basis);
7692 vec2 screen_point_b = screen_b + width * (VERTEX.x * x_basis + VERTEX.y * y_basis);
7693 vec2 screen_point_final = mix(screen_point_a, screen_point_b, VERTEX.z);
7694
7695 vec4 clip_final = mix(clip_a, clip_b, VERTEX.z);
7696
7697 POSITION = vec4(clip_final.w * ((2.0 * screen_point_final) / VIEWPORT_SIZE - 1.0), clip_final.z, clip_final.w);
7698 UV = VERTEX.yz * clip_final.w;
7699
7700 if (!OUTPUT_IS_SRGB) {
7701 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)));
7702 }
7703 }
7704
7705 void fragment() {
7706 // Multiply by 0.5 since UV is actually UV is [-1, 1].
7707 float line_width = fwidth(UV.x * 0.5);
7708 float line_uv = abs(UV.x * 0.5);
7709 float line = smoothstep(line_width * 1.0, line_width * 0.25, line_uv);
7710
7711 ALBEDO = COLOR.rgb;
7712 ALPHA *= COLOR.a * line;
7713 }
7714 )");
7715
7716 origin_mat.instantiate();
7717 origin_mat->set_shader(origin_shader);
7718
7719 Vector<Vector3> origin_points;
7720 origin_points.resize(6);
7721
7722 origin_points.set(0, Vector3(0.0, -0.5, 0.0));
7723 origin_points.set(1, Vector3(0.0, -0.5, 1.0));
7724 origin_points.set(2, Vector3(0.0, 0.5, 1.0));
7725
7726 origin_points.set(3, Vector3(0.0, -0.5, 0.0));
7727 origin_points.set(4, Vector3(0.0, 0.5, 1.0));
7728 origin_points.set(5, Vector3(0.0, 0.5, 0.0));
7729
7730 Array d;
7731 d.resize(RS::ARRAY_MAX);
7732 d[RenderingServer::ARRAY_VERTEX] = origin_points;
7733
7734 origin_mesh = RenderingServer::get_singleton()->mesh_create();
7735
7736 RenderingServer::get_singleton()->mesh_add_surface_from_arrays(origin_mesh, RenderingServer::PRIMITIVE_TRIANGLES, d);
7737 RenderingServer::get_singleton()->mesh_surface_set_material(origin_mesh, 0, origin_mat->get_rid());
7738
7739 origin_multimesh = RenderingServer::get_singleton()->multimesh_create();
7740 RenderingServer::get_singleton()->multimesh_set_mesh(origin_multimesh, origin_mesh);
7741 RenderingServer::get_singleton()->multimesh_allocate_data(origin_multimesh, 12, RS::MultimeshTransformFormat::MULTIMESH_TRANSFORM_3D, true, false);
7742 RenderingServer::get_singleton()->multimesh_set_visible_instances(origin_multimesh, -1);
7743
7744 LocalVector<float> distances;
7745 distances.resize(5);
7746 distances[0] = -1000000.0;
7747 distances[1] = -1000.0;
7748 distances[2] = 0.0;
7749 distances[3] = 1000.0;
7750 distances[4] = 1000000.0;
7751
7752 for (int i = 0; i < 3; i++) {
7753 Color origin_color;
7754 switch (i) {
7755 case 0:
7756 origin_color = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
7757 break;
7758 case 1:
7759 origin_color = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
7760 break;
7761 case 2:
7762 origin_color = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
7763 break;
7764 default:
7765 origin_color = Color();
7766 break;
7767 }
7768
7769 Vector3 axis;
7770 axis[i] = 1;
7771
7772 for (int j = 0; j < 4; j++) {
7773 Transform3D t = Transform3D();
7774 if (distances[j] > 0.0) {
7775 t = t.scaled(axis * distances[j + 1]);
7776 t = t.translated(axis * distances[j]);
7777 } else {
7778 t = t.scaled(axis * distances[j]);
7779 t = t.translated(axis * distances[j + 1]);
7780 }
7781 RenderingServer::get_singleton()->multimesh_instance_set_transform(origin_multimesh, i * 4 + j, t);
7782 RenderingServer::get_singleton()->multimesh_instance_set_color(origin_multimesh, i * 4 + j, origin_color);
7783 }
7784 }
7785
7786 origin_instance = RenderingServer::get_singleton()->instance_create2(origin_multimesh, get_tree()->get_root()->get_world_3d()->get_scenario());
7787 RS::get_singleton()->instance_set_layer_mask(origin_instance, 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
7788 RS::get_singleton()->instance_geometry_set_flag(origin_instance, RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
7789 RS::get_singleton()->instance_geometry_set_flag(origin_instance, RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
7790
7791 RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(origin_instance, RS::SHADOW_CASTING_SETTING_OFF);
7792
7793 Ref<Shader> grid_shader = memnew(Shader);
7794 grid_shader->set_code(R"(
7795 // 3D editor grid shader.
7796
7797 shader_type spatial;
7798
7799 render_mode unshaded, fog_disabled;
7800
7801 uniform bool orthogonal;
7802 uniform float grid_size;
7803
7804 void vertex() {
7805 // From FLAG_SRGB_VERTEX_COLOR.
7806 if (!OUTPUT_IS_SRGB) {
7807 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)));
7808 }
7809 }
7810
7811 void fragment() {
7812 ALBEDO = COLOR.rgb;
7813 vec3 dir = orthogonal ? -vec3(0, 0, 1) : VIEW;
7814 float angle_fade = abs(dot(dir, NORMAL));
7815 angle_fade = smoothstep(0.05, 0.2, angle_fade);
7816
7817 vec3 world_pos = (INV_VIEW_MATRIX * vec4(VERTEX, 1.0)).xyz;
7818 vec3 world_normal = (INV_VIEW_MATRIX * vec4(NORMAL, 0.0)).xyz;
7819 vec3 camera_world_pos = INV_VIEW_MATRIX[3].xyz;
7820 vec3 camera_world_pos_on_plane = camera_world_pos * (1.0 - world_normal);
7821 float dist_fade = 1.0 - (distance(world_pos, camera_world_pos_on_plane) / grid_size);
7822 dist_fade = smoothstep(0.02, 0.3, dist_fade);
7823
7824 ALPHA = COLOR.a * dist_fade * angle_fade;
7825 }
7826 )");
7827
7828 for (int i = 0; i < 3; i++) {
7829 grid_mat[i].instantiate();
7830 grid_mat[i]->set_shader(grid_shader);
7831 }
7832
7833 grid_enable[0] = EDITOR_GET("editors/3d/grid_xy_plane");
7834 grid_enable[1] = EDITOR_GET("editors/3d/grid_yz_plane");
7835 grid_enable[2] = EDITOR_GET("editors/3d/grid_xz_plane");
7836 grid_visible[0] = grid_enable[0];
7837 grid_visible[1] = grid_enable[1];
7838 grid_visible[2] = grid_enable[2];
7839
7840 _init_grid();
7841 }
7842
7843 {
7844 //move gizmo
7845
7846 // Inverted zxy.
7847 Vector3 ivec = Vector3(0, 0, -1);
7848 Vector3 nivec = Vector3(-1, -1, 0);
7849 Vector3 ivec2 = Vector3(-1, 0, 0);
7850 Vector3 ivec3 = Vector3(0, -1, 0);
7851
7852 for (int i = 0; i < 4; i++) {
7853 Color col;
7854 switch (i) {
7855 case 0:
7856 col = get_theme_color(SNAME("axis_x_color"), EditorStringName(Editor));
7857 break;
7858 case 1:
7859 col = get_theme_color(SNAME("axis_y_color"), EditorStringName(Editor));
7860 break;
7861 case 2:
7862 col = get_theme_color(SNAME("axis_z_color"), EditorStringName(Editor));
7863 break;
7864 case 3:
7865 col = Color(0.75, 0.75, 0.75, 1.0);
7866 break;
7867 default:
7868 col = Color();
7869 break;
7870 }
7871
7872 if (i < 3) {
7873 col.a = EDITOR_GET("editors/3d/manipulator_gizmo_opacity");
7874 }
7875
7876 if (i < 3) {
7877 move_gizmo[i].instantiate();
7878 move_plane_gizmo[i].instantiate();
7879 scale_gizmo[i].instantiate();
7880 scale_plane_gizmo[i].instantiate();
7881 axis_gizmo[i].instantiate();
7882 }
7883
7884 rotate_gizmo[i].instantiate();
7885
7886 const Color albedo = col.from_hsv(col.get_h(), 0.25, 1.0, 1);
7887
7888 Ref<StandardMaterial3D> mat;
7889 Ref<StandardMaterial3D> mat_hl;
7890
7891 if (i < 3) {
7892 // Only create standard materials for X, Y, Z axes (move/scale gizmos).
7893 mat.instantiate();
7894 mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
7895 mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
7896 mat->set_on_top_of_alpha();
7897 mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
7898 mat->set_albedo(col);
7899 gizmo_color[i] = mat;
7900
7901 mat_hl = mat->duplicate();
7902 mat_hl->set_albedo(albedo);
7903 gizmo_color_hl[i] = mat_hl;
7904 }
7905
7906 // Only create translate gizmo for X, Y, Z axes (not view rotation).
7907 if (i < 3) {
7908 //translate
7909 {
7910 Ref<SurfaceTool> surftool;
7911 surftool.instantiate();
7912 surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
7913
7914 // Arrow profile
7915 const int arrow_points = 5;
7916 Vector3 arrow[5] = {
7917 nivec * 0.0 + ivec * 0.0,
7918 nivec * 0.01 + ivec * 0.0,
7919 nivec * 0.01 + ivec * GIZMO_ARROW_OFFSET,
7920 nivec * 0.065 + ivec * GIZMO_ARROW_OFFSET,
7921 nivec * 0.0 + ivec * (GIZMO_ARROW_OFFSET + GIZMO_ARROW_SIZE),
7922 };
7923
7924 int arrow_sides = 16;
7925
7926 const real_t arrow_sides_step = Math::TAU / arrow_sides;
7927 for (int k = 0; k < arrow_sides; k++) {
7928 Basis ma(ivec, k * arrow_sides_step);
7929 Basis mb(ivec, (k + 1) * arrow_sides_step);
7930
7931 for (int j = 0; j < arrow_points - 1; j++) {
7932 Vector3 points[4] = {
7933 ma.xform(arrow[j]),
7934 mb.xform(arrow[j]),
7935 mb.xform(arrow[j + 1]),
7936 ma.xform(arrow[j + 1]),
7937 };
7938 surftool->add_vertex(points[0]);
7939 surftool->add_vertex(points[1]);
7940 surftool->add_vertex(points[2]);
7941
7942 surftool->add_vertex(points[0]);
7943 surftool->add_vertex(points[2]);
7944 surftool->add_vertex(points[3]);
7945 }
7946 }
7947
7948 surftool->set_material(mat);
7949 surftool->commit(move_gizmo[i]);
7950 }
7951
7952 // Plane Translation
7953 {
7954 Ref<SurfaceTool> surftool;
7955 surftool.instantiate();
7956 surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
7957
7958 Vector3 vec = ivec2 - ivec3;
7959 Vector3 plane[4] = {
7960 vec * GIZMO_PLANE_DST,
7961 vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
7962 vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
7963 vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
7964 };
7965
7966 Basis ma(ivec, Math::PI / 2);
7967
7968 Vector3 points[4] = {
7969 ma.xform(plane[0]),
7970 ma.xform(plane[1]),
7971 ma.xform(plane[2]),
7972 ma.xform(plane[3]),
7973 };
7974 surftool->add_vertex(points[0]);
7975 surftool->add_vertex(points[1]);
7976 surftool->add_vertex(points[2]);
7977
7978 surftool->add_vertex(points[0]);
7979 surftool->add_vertex(points[2]);
7980 surftool->add_vertex(points[3]);
7981
7982 Ref<StandardMaterial3D> plane_mat;
7983 plane_mat.instantiate();
7984 plane_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
7985 plane_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
7986 plane_mat->set_on_top_of_alpha();
7987 plane_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
7988 plane_mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
7989 plane_mat->set_albedo(col);
7990 plane_gizmo_color[i] = plane_mat; // Needed, so we can draw planes from both sides.
7991 surftool->set_material(plane_mat);
7992 surftool->commit(move_plane_gizmo[i]);
7993
7994 Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate();
7995 plane_mat_hl->set_albedo(albedo);
7996 plane_gizmo_color_hl[i] = plane_mat_hl; // Needed, so we can draw planes from both sides.
7997 }
7998 }
7999
8000 // Rotate - for all 4 indices (X, Y, Z, and view rotation).
8001 {
8002 Ref<SurfaceTool> surftool;
8003 surftool.instantiate();
8004 surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
8005
8006 int n = 128; // number of circle segments
8007 int m = 3; // number of thickness segments
8008
8009 real_t step = Math::TAU / n;
8010 for (int j = 0; j < n; ++j) {
8011 Basis basis = Basis(ivec, j * step);
8012
8013 real_t circle_size = (i == 3) ? GIZMO_VIEW_ROTATION_SIZE : GIZMO_CIRCLE_SIZE;
8014 Vector3 vertex = basis.xform(ivec2 * circle_size);
8015
8016 for (int k = 0; k < m; ++k) {
8017 Vector2 ofs = Vector2(Math::cos((Math::TAU * k) / m), Math::sin((Math::TAU * k) / m));
8018 Vector3 normal = ivec * ofs.x + ivec2 * ofs.y;
8019
8020 surftool->set_normal(basis.xform(normal));
8021 surftool->add_vertex(vertex);
8022 }
8023 }
8024
8025 for (int j = 0; j < n; ++j) {
8026 for (int k = 0; k < m; ++k) {
8027 int current_ring = j * m;
8028 int next_ring = ((j + 1) % n) * m;
8029 int current_segment = k;
8030 int next_segment = (k + 1) % m;
8031
8032 surftool->add_index(current_ring + next_segment);
8033 surftool->add_index(current_ring + current_segment);
8034 surftool->add_index(next_ring + current_segment);
8035
8036 surftool->add_index(next_ring + current_segment);
8037 surftool->add_index(next_ring + next_segment);
8038 surftool->add_index(current_ring + next_segment);
8039 }
8040 }
8041
8042 Ref<Shader> rotate_shader = memnew(Shader);
8043
8044 // Use special shader for view rotation (index 3) with camera-relative transformation.
8045 if (i == 3) {
8046 rotate_shader->set_code(R"(
8047
8048 shader_type spatial;
8049
8050 render_mode unshaded, depth_test_disabled, fog_disabled;
8051
8052 uniform vec4 albedo;
8053
8054 mat3 orthonormalize(mat3 m) {
8055 vec3 x = normalize(m[0]);
8056 vec3 y = normalize(m[1] - x * dot(x, m[1]));
8057 vec3 z = m[2] - x * dot(x, m[2]);
8058 z = normalize(z - y * (dot(y, m[2])));
8059 return mat3(x,y,z);
8060 }
8061
8062 void vertex() {
8063 mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX));
8064 mv = inverse(mv);
8065 VERTEX += NORMAL * 0.008;
8066 vec3 camera_dir_local = mv * vec3(0.0, 0.0, 1.0);
8067 vec3 camera_up_local = mv * vec3(0.0, 1.0, 0.0);
8068 mat3 rotation_matrix = mat3(cross(camera_dir_local, camera_up_local), camera_up_local, camera_dir_local);
8069 VERTEX = rotation_matrix * VERTEX;
8070 }
8071
8072 void fragment() {
8073 ALBEDO = albedo.rgb;
8074 ALPHA = albedo.a;
8075 }
8076 )");
8077 } else {
8078 // Standard shader for X, Y, Z rotation gizmos.
8079 rotate_shader->set_code(R"(
8080 // 3D editor rotation manipulator gizmo shader.
8081
8082 shader_type spatial;
8083
8084 render_mode unshaded, depth_test_disabled, fog_disabled;
8085
8086 uniform vec4 albedo;
8087
8088 mat3 orthonormalize(mat3 m) {
8089 vec3 x = normalize(m[0]);
8090 vec3 y = normalize(m[1] - x * dot(x, m[1]));
8091 vec3 z = m[2] - x * dot(x, m[2]);
8092 z = normalize(z - y * (dot(y, m[2])));
8093 return mat3(x, y, z);
8094 }
8095
8096 void vertex() {
8097 mat3 mv = orthonormalize(mat3(MODELVIEW_MATRIX));
8098 vec3 n = mv * VERTEX;
8099 float orientation = dot(vec3(0.0, 0.0, -1.0), n);
8100 if (orientation <= 0.005) {
8101 VERTEX += NORMAL * 0.02;
8102 }
8103 }
8104
8105 void fragment() {
8106 ALBEDO = albedo.rgb;
8107 ALPHA = albedo.a;
8108 }
8109 )");
8110 }
8111
8112 Ref<ShaderMaterial> rotate_mat;
8113 rotate_mat.instantiate();
8114 rotate_mat->set_render_priority(Material::RENDER_PRIORITY_MAX);
8115 rotate_mat->set_shader(rotate_shader);
8116 rotate_mat->set_shader_parameter("albedo", col);
8117 rotate_gizmo_color[i] = rotate_mat;
8118
8119 Array arrays = surftool->commit_to_arrays();
8120 rotate_gizmo[i]->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
8121 rotate_gizmo[i]->surface_set_material(0, rotate_mat);
8122
8123 Ref<ShaderMaterial> rotate_mat_hl = rotate_mat->duplicate();
8124 // For view rotation, use bright white; for axes, use highlight color.
8125 Color highlight_color = (i == 3) ? Color(1.0, 1.0, 1.0, 1.0) : albedo;
8126 rotate_mat_hl->set_shader_parameter("albedo", highlight_color);
8127 rotate_gizmo_color_hl[i] = rotate_mat_hl;
8128 }
8129
8130 // Only create scale gizmo for X, Y, Z axes (not view rotation).
8131 if (i < 3) {
8132 // Scale.
8133 {
8134 Ref<SurfaceTool> surftool;
8135 surftool.instantiate();
8136 surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
8137
8138 // Cube arrow profile.
8139 const int arrow_points = 6;
8140 Vector3 arrow[6] = {
8141 nivec * 0.0 + ivec * 0.0,
8142 nivec * 0.01 + ivec * 0.0,
8143 nivec * 0.01 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
8144 nivec * 0.07 + ivec * 1.0 * GIZMO_SCALE_OFFSET,
8145 nivec * 0.07 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
8146 nivec * 0.0 + ivec * 1.11 * GIZMO_SCALE_OFFSET,
8147 };
8148
8149 int arrow_sides = 4;
8150
8151 const real_t arrow_sides_step = Math::TAU / arrow_sides;
8152 for (int k = 0; k < 4; k++) {
8153 Basis ma(ivec, k * arrow_sides_step);
8154 Basis mb(ivec, (k + 1) * arrow_sides_step);
8155
8156 for (int j = 0; j < arrow_points - 1; j++) {
8157 Vector3 points[4] = {
8158 ma.xform(arrow[j]),
8159 mb.xform(arrow[j]),
8160 mb.xform(arrow[j + 1]),
8161 ma.xform(arrow[j + 1]),
8162 };
8163 surftool->add_vertex(points[0]);
8164 surftool->add_vertex(points[1]);
8165 surftool->add_vertex(points[2]);
8166
8167 surftool->add_vertex(points[0]);
8168 surftool->add_vertex(points[2]);
8169 surftool->add_vertex(points[3]);
8170 }
8171 }
8172
8173 surftool->set_material(mat);
8174 surftool->commit(scale_gizmo[i]);
8175 }
8176
8177 // Plane Scale.
8178 {
8179 Ref<SurfaceTool> surftool;
8180 surftool.instantiate();
8181 surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
8182
8183 Vector3 vec = ivec2 - ivec3;
8184 Vector3 plane[4] = {
8185 vec * GIZMO_PLANE_DST,
8186 vec * GIZMO_PLANE_DST + ivec2 * GIZMO_PLANE_SIZE,
8187 vec * (GIZMO_PLANE_DST + GIZMO_PLANE_SIZE),
8188 vec * GIZMO_PLANE_DST - ivec3 * GIZMO_PLANE_SIZE
8189 };
8190
8191 Basis ma(ivec, Math::PI / 2);
8192
8193 Vector3 points[4] = {
8194 ma.xform(plane[0]),
8195 ma.xform(plane[1]),
8196 ma.xform(plane[2]),
8197 ma.xform(plane[3]),
8198 };
8199 surftool->add_vertex(points[0]);
8200 surftool->add_vertex(points[1]);
8201 surftool->add_vertex(points[2]);
8202
8203 surftool->add_vertex(points[0]);
8204 surftool->add_vertex(points[2]);
8205 surftool->add_vertex(points[3]);
8206
8207 Ref<StandardMaterial3D> plane_mat;
8208 plane_mat.instantiate();
8209 plane_mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
8210 plane_mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
8211 plane_mat->set_on_top_of_alpha();
8212 plane_mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
8213 plane_mat->set_cull_mode(StandardMaterial3D::CULL_DISABLED);
8214 plane_mat->set_albedo(col);
8215 plane_gizmo_color[i] = plane_mat; // needed, so we can draw planes from both sides.
8216 surftool->set_material(plane_mat);
8217 surftool->commit(scale_plane_gizmo[i]);
8218
8219 Ref<StandardMaterial3D> plane_mat_hl = plane_mat->duplicate();
8220 plane_mat_hl->set_albedo(col.from_hsv(col.get_h(), 0.25, 1.0, 1));
8221 plane_gizmo_color_hl[i] = plane_mat_hl; // needed, so we can draw planes from both sides.
8222 }
8223
8224 // Lines to visualize transforms locked to an axis/plane.
8225 {
8226 Ref<SurfaceTool> surftool;
8227 surftool.instantiate();
8228 surftool->begin(Mesh::PRIMITIVE_LINE_STRIP);
8229
8230 Vector3 vec;
8231 vec[i] = 1;
8232
8233 // Line extending through like infinity.
8234 surftool->add_vertex(vec * -1048576);
8235 surftool->add_vertex(Vector3());
8236 surftool->add_vertex(vec * 1048576);
8237 surftool->set_material(mat_hl);
8238 surftool->commit(axis_gizmo[i]);
8239 }
8240 }
8241 }
8242 }
8243
8244 _generate_selection_boxes();
8245 }
8246
8247 void Node3DEditor::_update_gizmos_menu() {
8248 gizmos_menu->clear();
8249
8250 for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
8251 if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
8252 continue;
8253 }
8254 String plugin_name = gizmo_plugins_by_name[i]->get_gizmo_name();
8255 const int plugin_state = gizmo_plugins_by_name[i]->get_state();
8256 gizmos_menu->add_multistate_item(plugin_name, 3, plugin_state, i);
8257 const int idx = gizmos_menu->get_item_index(i);
8258 gizmos_menu->set_item_tooltip(
8259 idx,
8260 TTR("Click to toggle between visibility states.\n\nOpen eye: Gizmo is visible.\nClosed eye: Gizmo is hidden.\nHalf-open eye: Gizmo is also visible through opaque surfaces (\"x-ray\")."));
8261 switch (plugin_state) {
8262 case EditorNode3DGizmoPlugin::VISIBLE:
8263 gizmos_menu->set_item_icon(idx, get_editor_theme_icon(SNAME("GuiVisibilityVisible")));
8264 break;
8265 case EditorNode3DGizmoPlugin::ON_TOP:
8266 gizmos_menu->set_item_icon(idx, get_editor_theme_icon(SNAME("GuiVisibilityXray")));
8267 break;
8268 case EditorNode3DGizmoPlugin::HIDDEN:
8269 gizmos_menu->set_item_icon(idx, get_editor_theme_icon(SNAME("GuiVisibilityHidden")));
8270 break;
8271 }
8272 }
8273 }
8274
8275 void Node3DEditor::_update_gizmos_menu_theme() {
8276 for (int i = 0; i < gizmo_plugins_by_name.size(); ++i) {
8277 if (!gizmo_plugins_by_name[i]->can_be_hidden()) {
8278 continue;
8279 }
8280 const int plugin_state = gizmo_plugins_by_name[i]->get_state();
8281 const int idx = gizmos_menu->get_item_index(i);
8282 switch (plugin_state) {
8283 case EditorNode3DGizmoPlugin::VISIBLE:
8284 gizmos_menu->set_item_icon(idx, get_editor_theme_icon(SNAME("GuiVisibilityVisible")));
8285 break;
8286 case EditorNode3DGizmoPlugin::ON_TOP:
8287 gizmos_menu->set_item_icon(idx, get_editor_theme_icon(SNAME("GuiVisibilityXray")));
8288 break;
8289 case EditorNode3DGizmoPlugin::HIDDEN:
8290 gizmos_menu->set_item_icon(idx, get_editor_theme_icon(SNAME("GuiVisibilityHidden")));
8291 break;
8292 }
8293 }
8294 }
8295
8296 void Node3DEditor::_init_grid() {
8297 if (!grid_enabled) {
8298 return;
8299 }
8300 Camera3D *camera = get_editor_viewport(0)->camera;
8301 Vector3 camera_position = camera->get_position();
8302 if (camera_position == Vector3()) {
8303 return; // Camera3D is invalid, don't draw the grid.
8304 }
8305
8306 bool orthogonal = camera->get_projection() == Camera3D::PROJECTION_ORTHOGONAL;
8307
8308 static LocalVector<Color> grid_colors[3];
8309 static LocalVector<Vector3> grid_points[3];
8310 static LocalVector<Vector3> grid_normals[3];
8311
8312 for (uint32_t n = 0; n < 3; n++) {
8313 grid_colors[n].clear();
8314 grid_points[n].clear();
8315 grid_normals[n].clear();
8316 }
8317
8318 Color primary_grid_color = EDITOR_GET("editors/3d/primary_grid_color");
8319 Color secondary_grid_color = EDITOR_GET("editors/3d/secondary_grid_color");
8320 int grid_size = EDITOR_GET("editors/3d/grid_size");
8321 int primary_grid_steps = EDITOR_GET("editors/3d/primary_grid_steps");
8322
8323 // Which grid planes are enabled? Which should we generate?
8324 grid_enable[0] = grid_visible[0] = orthogonal || EDITOR_GET("editors/3d/grid_xy_plane");
8325 grid_enable[1] = grid_visible[1] = orthogonal || EDITOR_GET("editors/3d/grid_yz_plane");
8326 grid_enable[2] = grid_visible[2] = orthogonal || EDITOR_GET("editors/3d/grid_xz_plane");
8327
8328 // Offsets division_level for bigger or smaller grids.
8329 // Default value is -0.2. -1.0 gives Blender-like behavior, 0.5 gives huge grids.
8330 real_t division_level_bias = EDITOR_GET("editors/3d/grid_division_level_bias");
8331 // Default largest grid size is 8^2 (default value is 2) when primary_grid_steps is 8 (64m apart, so primary grid lines are 512m apart).
8332 int division_level_max = EDITOR_GET("editors/3d/grid_division_level_max");
8333 // Default smallest grid size is 8^0 (default value is 0) when primary_grid_steps is 8.
8334 int division_level_min = EDITOR_GET("editors/3d/grid_division_level_min");
8335 ERR_FAIL_COND_MSG(division_level_max < division_level_min, "The 3D grid's maximum division level cannot be lower than its minimum division level.");
8336
8337 if (primary_grid_steps != 10) { // Log10 of 10 is 1.
8338 // Change of base rule, divide by ln(10).
8339 real_t div = Math::log((real_t)primary_grid_steps) / (real_t)2.302585092994045901094;
8340 // Truncation (towards zero) is intentional.
8341 division_level_max = (int)(division_level_max / div);
8342 division_level_min = (int)(division_level_min / div);
8343 }
8344
8345 for (int a = 0; a < 3; a++) {
8346 if (!grid_enable[a]) {
8347 continue; // If this grid plane is disabled, skip generation.
8348 }
8349 int b = (a + 1) % 3;
8350 int c = (a + 2) % 3;
8351
8352 Vector3 normal;
8353 normal[c] = 1.0;
8354
8355 real_t camera_distance = Math::abs(camera_position[c]);
8356
8357 if (orthogonal) {
8358 camera_distance = camera->get_size() / 2.0;
8359 Vector3 camera_direction = -camera->get_global_transform().get_basis().get_column(2);
8360 Plane grid_plane = Plane(normal);
8361 Vector3 intersection;
8362 if (grid_plane.intersects_ray(camera_position, camera_direction, &intersection)) {
8363 camera_position = intersection;
8364 }
8365 }
8366
8367 real_t division_level = Math::log(Math::abs(camera_distance)) / Math::log((double)primary_grid_steps) + division_level_bias;
8368
8369 real_t clamped_division_level = CLAMP(division_level, division_level_min, division_level_max);
8370 real_t division_level_floored = Math::floor(clamped_division_level);
8371 real_t division_level_decimals = clamped_division_level - division_level_floored;
8372
8373 real_t small_step_size = Math::pow(primary_grid_steps, division_level_floored);
8374 real_t large_step_size = small_step_size * primary_grid_steps;
8375 real_t center_a = large_step_size * (int)(camera_position[a] / large_step_size);
8376 real_t center_b = large_step_size * (int)(camera_position[b] / large_step_size);
8377
8378 real_t bgn_a = center_a - grid_size * small_step_size;
8379 real_t end_a = center_a + grid_size * small_step_size;
8380 real_t bgn_b = center_b - grid_size * small_step_size;
8381 real_t end_b = center_b + grid_size * small_step_size;
8382
8383 real_t fade_size = Math::pow(primary_grid_steps, division_level - 1.0);
8384 real_t min_fade_size = Math::pow(primary_grid_steps, float(division_level_min));
8385 real_t max_fade_size = Math::pow(primary_grid_steps, float(division_level_max));
8386 fade_size = CLAMP(fade_size, min_fade_size, max_fade_size);
8387
8388 real_t grid_fade_size = (grid_size - primary_grid_steps) * fade_size;
8389 grid_mat[c]->set_shader_parameter("grid_size", grid_fade_size);
8390 grid_mat[c]->set_shader_parameter("orthogonal", orthogonal);
8391
8392 LocalVector<Vector3> &ref_grid = grid_points[c];
8393 LocalVector<Vector3> &ref_grid_normals = grid_normals[c];
8394 LocalVector<Color> &ref_grid_colors = grid_colors[c];
8395
8396 // Count our elements same as code below it.
8397 int expected_size = 0;
8398 for (int i = -grid_size; i <= grid_size; i++) {
8399 const real_t position_a = center_a + i * small_step_size;
8400 const real_t position_b = center_b + i * small_step_size;
8401
8402 // Don't draw lines over the origin if it's enabled.
8403 if (!(origin_enabled && Math::is_zero_approx(position_a))) {
8404 expected_size += 2;
8405 }
8406
8407 if (!(origin_enabled && Math::is_zero_approx(position_b))) {
8408 expected_size += 2;
8409 }
8410 }
8411
8412 int idx = 0;
8413 ref_grid.resize(expected_size);
8414 ref_grid_normals.resize(expected_size);
8415 ref_grid_colors.resize(expected_size);
8416
8417 // In each iteration of this loop, draw one line in each direction (so two lines per loop, in each if statement).
8418 for (int i = -grid_size; i <= grid_size; i++) {
8419 Color line_color;
8420 // Is this a primary line? Set the appropriate color.
8421 if (i % primary_grid_steps == 0) {
8422 line_color = primary_grid_color.lerp(secondary_grid_color, division_level_decimals);
8423 } else {
8424 line_color = secondary_grid_color;
8425 line_color.a = line_color.a * (1 - division_level_decimals);
8426 }
8427
8428 real_t position_a = center_a + i * small_step_size;
8429 real_t position_b = center_b + i * small_step_size;
8430
8431 // Don't draw lines over the origin if it's enabled.
8432 if (!(origin_enabled && Math::is_zero_approx(position_a))) {
8433 Vector3 line_bgn;
8434 Vector3 line_end;
8435 line_bgn[a] = position_a;
8436 line_end[a] = position_a;
8437 line_bgn[b] = bgn_b;
8438 line_end[b] = end_b;
8439 ref_grid[idx] = line_bgn;
8440 ref_grid[idx + 1] = line_end;
8441 ref_grid_colors[idx] = line_color;
8442 ref_grid_colors[idx + 1] = line_color;
8443 ref_grid_normals[idx] = normal;
8444 ref_grid_normals[idx + 1] = normal;
8445 idx += 2;
8446 }
8447
8448 if (!(origin_enabled && Math::is_zero_approx(position_b))) {
8449 Vector3 line_bgn;
8450 Vector3 line_end;
8451 line_bgn[b] = position_b;
8452 line_end[b] = position_b;
8453 line_bgn[a] = bgn_a;
8454 line_end[a] = end_a;
8455 ref_grid[idx] = line_bgn;
8456 ref_grid[idx + 1] = line_end;
8457 ref_grid_colors[idx] = line_color;
8458 ref_grid_colors[idx + 1] = line_color;
8459 ref_grid_normals[idx] = normal;
8460 ref_grid_normals[idx + 1] = normal;
8461 idx += 2;
8462 }
8463 }
8464
8465 // Create a mesh from the pushed vector points and colors.
8466 grid[c] = RenderingServer::get_singleton()->mesh_create();
8467 Array d;
8468 d.resize(RS::ARRAY_MAX);
8469 d[RenderingServer::ARRAY_VERTEX] = (Vector<Vector3>)grid_points[c];
8470 d[RenderingServer::ARRAY_COLOR] = (Vector<Color>)grid_colors[c];
8471 d[RenderingServer::ARRAY_NORMAL] = (Vector<Vector3>)grid_normals[c];
8472 RenderingServer::get_singleton()->mesh_add_surface_from_arrays(grid[c], RenderingServer::PRIMITIVE_LINES, d);
8473 RenderingServer::get_singleton()->mesh_surface_set_material(grid[c], 0, grid_mat[c]->get_rid());
8474 grid_instance[c] = RenderingServer::get_singleton()->instance_create2(grid[c], get_tree()->get_root()->get_world_3d()->get_scenario());
8475
8476 // Yes, the end of this line is supposed to be a.
8477 RenderingServer::get_singleton()->instance_set_visible(grid_instance[c], grid_visible[a]);
8478 RenderingServer::get_singleton()->instance_geometry_set_cast_shadows_setting(grid_instance[c], RS::SHADOW_CASTING_SETTING_OFF);
8479 RS::get_singleton()->instance_set_layer_mask(grid_instance[c], 1 << Node3DEditorViewport::GIZMO_GRID_LAYER);
8480 RS::get_singleton()->instance_geometry_set_flag(grid_instance[c], RS::INSTANCE_FLAG_IGNORE_OCCLUSION_CULLING, true);
8481 RS::get_singleton()->instance_geometry_set_flag(grid_instance[c], RS::INSTANCE_FLAG_USE_BAKED_LIGHT, false);
8482 }
8483 }
8484
8485 void Node3DEditor::_finish_indicators() {
8486 RenderingServer::get_singleton()->free_rid(origin_instance);
8487 RenderingServer::get_singleton()->free_rid(origin_multimesh);
8488 RenderingServer::get_singleton()->free_rid(origin_mesh);
8489
8490 _finish_grid();
8491 }
8492
8493 void Node3DEditor::_finish_grid() {
8494 for (int i = 0; i < 3; i++) {
8495 RenderingServer::get_singleton()->free_rid(grid_instance[i]);
8496 RenderingServer::get_singleton()->free_rid(grid[i]);
8497 }
8498 }
8499
8500 void Node3DEditor::update_gizmo_opacity() {
8501 if (!origin_instance.is_valid()) {
8502 return;
8503 }
8504
8505 const float opacity = EDITOR_GET("editors/3d/manipulator_gizmo_opacity");
8506
8507 for (int i = 0; i < 3; i++) {
8508 Color col = gizmo_color[i]->get_albedo();
8509 col.a = opacity;
8510 gizmo_color[i]->set_albedo(col);
8511
8512 col = gizmo_color_hl[i]->get_albedo();
8513 col.a = 1.0;
8514 gizmo_color_hl[i]->set_albedo(col);
8515
8516 col = plane_gizmo_color[i]->get_albedo();
8517 col.a = opacity;
8518 plane_gizmo_color[i]->set_albedo(col);
8519
8520 col = plane_gizmo_color_hl[i]->get_albedo();
8521 col.a = 1.0;
8522 plane_gizmo_color_hl[i]->set_albedo(col);
8523 }
8524 }
8525
8526 void Node3DEditor::update_grid() {
8527 const Camera3D::ProjectionType current_projection = viewports[0]->camera->get_projection();
8528
8529 if (current_projection != grid_camera_last_update_perspective) {
8530 grid_init_draw = false; // redraw
8531 grid_camera_last_update_perspective = current_projection;
8532 }
8533
8534 // Gets a orthogonal or perspective position correctly (for the grid comparison)
8535 const Vector3 camera_position = get_editor_viewport(0)->camera->get_position();
8536
8537 if (!grid_init_draw || grid_camera_last_update_position.distance_squared_to(camera_position) >= 100.0f) {
8538 _finish_grid();
8539 _init_grid();
8540 grid_init_draw = true;
8541 grid_camera_last_update_position = camera_position;
8542 }
8543 }
8544
8545 void Node3DEditor::_selection_changed() {
8546 _refresh_menu_icons();
8547
8548 const HashMap<ObjectID, Object *> &selection = editor_selection->get_selection();
8549
8550 for (const KeyValue<ObjectID, Object *> &E : selection) {
8551 Node3D *sp = ObjectDB::get_instance<Node3D>(E.key);
8552 if (!sp) {
8553 continue;
8554 }
8555
8556 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
8557 if (!se) {
8558 continue;
8559 }
8560
8561 if (sp == editor_selection->get_top_selected_node_list().back()->get()) {
8562 RenderingServer::get_singleton()->instance_set_base(se->sbox_instance, active_selection_box->get_rid());
8563 RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_xray, active_selection_box_xray->get_rid());
8564 RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_offset, active_selection_box->get_rid());
8565 RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_xray_offset, active_selection_box_xray->get_rid());
8566 } else {
8567 RenderingServer::get_singleton()->instance_set_base(se->sbox_instance, selection_box->get_rid());
8568 RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_xray, selection_box_xray->get_rid());
8569 RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_offset, selection_box->get_rid());
8570 RenderingServer::get_singleton()->instance_set_base(se->sbox_instance_xray_offset, selection_box_xray->get_rid());
8571 }
8572 }
8573
8574 if (selected && editor_selection->get_top_selected_node_list().size() != 1) {
8575 Vector<Ref<Node3DGizmo>> gizmos = selected->get_gizmos();
8576 for (int i = 0; i < gizmos.size(); i++) {
8577 Ref<EditorNode3DGizmo> seg = gizmos[i];
8578 if (seg.is_null()) {
8579 continue;
8580 }
8581 seg->set_selected(false);
8582 }
8583
8584 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
8585 if (se) {
8586 se->gizmo.unref();
8587 se->subgizmos.clear();
8588 }
8589 selected->update_gizmos();
8590 selected = nullptr;
8591 }
8592
8593 // Ensure gizmo updates are performed when the selection changes
8594 // outside of the 3D view (see GH-106713).
8595 if (!is_visible()) {
8596 const List<Node *> &top_selected = editor_selection->get_top_selected_node_list();
8597 if (top_selected.size() == 1) {
8598 Node3D *new_selected = Object::cast_to<Node3D>(top_selected.back()->get());
8599 if (new_selected != selected) {
8600 gizmos_dirty = true;
8601 }
8602 }
8603 }
8604
8605 update_transform_gizmo();
8606 }
8607
8608 void Node3DEditor::refresh_dirty_gizmos() {
8609 if (!gizmos_dirty) {
8610 return;
8611 }
8612
8613 const List<Node *> &top_selected = editor_selection->get_top_selected_node_list();
8614 if (top_selected.size() == 1) {
8615 Node3D *new_selected = Object::cast_to<Node3D>(top_selected.back()->get());
8616 if (new_selected != selected) {
8617 edit(new_selected);
8618 }
8619 }
8620 gizmos_dirty = false;
8621 }
8622
8623 void Node3DEditor::_refresh_menu_icons() {
8624 bool all_locked = true;
8625 bool all_grouped = true;
8626 bool has_node3d_item = false;
8627
8628 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
8629
8630 if (selection.is_empty()) {
8631 all_locked = false;
8632 all_grouped = false;
8633 } else {
8634 for (Node *E : selection) {
8635 Node3D *node = Object::cast_to<Node3D>(E);
8636 if (node) {
8637 if (all_locked && !node->has_meta("_edit_lock_")) {
8638 all_locked = false;
8639 }
8640 if (all_grouped && !node->has_meta("_edit_group_")) {
8641 all_grouped = false;
8642 }
8643 has_node3d_item = true;
8644 }
8645 if (!all_locked && !all_grouped) {
8646 break;
8647 }
8648 }
8649 }
8650
8651 all_locked = all_locked && has_node3d_item;
8652 all_grouped = all_grouped && has_node3d_item;
8653
8654 tool_button[TOOL_LOCK_SELECTED]->set_visible(!all_locked);
8655 tool_button[TOOL_LOCK_SELECTED]->set_disabled(!has_node3d_item);
8656 tool_button[TOOL_UNLOCK_SELECTED]->set_visible(all_locked);
8657 tool_button[TOOL_UNLOCK_SELECTED]->set_disabled(!has_node3d_item);
8658
8659 tool_button[TOOL_GROUP_SELECTED]->set_visible(!all_grouped);
8660 tool_button[TOOL_GROUP_SELECTED]->set_disabled(!has_node3d_item);
8661 tool_button[TOOL_UNGROUP_SELECTED]->set_visible(all_grouped);
8662 tool_button[TOOL_UNGROUP_SELECTED]->set_disabled(!has_node3d_item);
8663 }
8664
8665 template <typename T>
8666 HashSet<T *> _get_child_nodes(Node *parent_node) {
8667 HashSet<T *> nodes = HashSet<T *>();
8668 T *node = Node::cast_to<T>(parent_node);
8669 if (node) {
8670 nodes.insert(node);
8671 }
8672
8673 for (int i = 0; i < parent_node->get_child_count(); i++) {
8674 Node *child_node = parent_node->get_child(i);
8675 HashSet<T *> child_nodes = _get_child_nodes<T>(child_node);
8676 for (T *I : child_nodes) {
8677 nodes.insert(I);
8678 }
8679 }
8680
8681 return nodes;
8682 }
8683
8684 HashSet<RID> _get_physics_bodies_rid(Node *node) {
8685 HashSet<RID> rids = HashSet<RID>();
8686 PhysicsBody3D *pb = Node::cast_to<PhysicsBody3D>(node);
8687 if (pb) {
8688 rids.insert(pb->get_rid());
8689 }
8690 HashSet<PhysicsBody3D *> child_nodes = _get_child_nodes<PhysicsBody3D>(node);
8691 for (const PhysicsBody3D *I : child_nodes) {
8692 rids.insert(I->get_rid());
8693 }
8694
8695 return rids;
8696 }
8697
8698 void Node3DEditor::snap_selected_nodes_to_floor() {
8699 do_snap_selected_nodes_to_floor = true;
8700 }
8701
8702 void Node3DEditor::_snap_selected_nodes_to_floor() {
8703 const List<Node *> &selection = editor_selection->get_top_selected_node_list();
8704 Dictionary snap_data;
8705
8706 for (Node *E : selection) {
8707 Node3D *sp = Object::cast_to<Node3D>(E);
8708 if (sp) {
8709 Vector3 from;
8710 Vector3 position_offset;
8711
8712 // Priorities for snapping to floor are CollisionShapes, VisualInstances and then origin
8713 HashSet<VisualInstance3D *> vi = _get_child_nodes<VisualInstance3D>(sp);
8714 HashSet<CollisionShape3D *> cs = _get_child_nodes<CollisionShape3D>(sp);
8715 bool found_valid_shape = false;
8716
8717 if (cs.size()) {
8718 AABB aabb;
8719 HashSet<CollisionShape3D *>::Iterator I = cs.begin();
8720 if ((*I)->get_shape().is_valid()) {
8721 CollisionShape3D *collision_shape = *cs.begin();
8722 aabb = collision_shape->get_global_transform().xform(collision_shape->get_shape()->get_debug_mesh()->get_aabb());
8723 found_valid_shape = true;
8724 }
8725
8726 for (++I; I; ++I) {
8727 CollisionShape3D *col_shape = *I;
8728 if (col_shape->get_shape().is_valid()) {
8729 aabb.merge_with(col_shape->get_global_transform().xform(col_shape->get_shape()->get_debug_mesh()->get_aabb()));
8730 found_valid_shape = true;
8731 }
8732 }
8733 if (found_valid_shape) {
8734 Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
8735 from = aabb.position + size;
8736 position_offset.y = from.y - sp->get_global_transform().origin.y;
8737 }
8738 }
8739 if (!found_valid_shape && vi.size()) {
8740 VisualInstance3D *begin = *vi.begin();
8741 AABB aabb = begin->get_global_transform().xform(begin->get_aabb());
8742 for (const VisualInstance3D *I : vi) {
8743 aabb.merge_with(I->get_global_transform().xform(I->get_aabb()));
8744 }
8745 Vector3 size = aabb.size * Vector3(0.5, 0.0, 0.5);
8746 from = aabb.position + size;
8747 position_offset.y = from.y - sp->get_global_transform().origin.y;
8748 } else if (!found_valid_shape) {
8749 from = sp->get_global_transform().origin;
8750 }
8751
8752 // We add a bit of margin to the from position to avoid it from snapping
8753 // when the spatial is already on a floor and there's another floor under
8754 // it
8755 from = from + Vector3(0.0, 1, 0.0);
8756
8757 Dictionary d;
8758
8759 d["from"] = from;
8760 d["position_offset"] = position_offset;
8761 snap_data[sp] = d;
8762 }
8763 }
8764
8765 PhysicsDirectSpaceState3D *ss = get_tree()->get_root()->get_world_3d()->get_direct_space_state();
8766 PhysicsDirectSpaceState3D::RayResult result;
8767
8768 // The maximum height an object can travel to be snapped
8769 const float max_snap_height = 500.0;
8770
8771 // Will be set to `true` if at least one node from the selection was successfully snapped
8772 bool snapped_to_floor = false;
8773
8774 if (!snap_data.is_empty()) {
8775 // For snapping to be performed, there must be solid geometry under at least one of the selected nodes.
8776 // We need to check this before snapping to register the undo/redo action only if needed.
8777 for (const KeyValue<Variant, Variant> &kv : snap_data) {
8778 Node *node = Object::cast_to<Node>(kv.key);
8779 Node3D *sp = Object::cast_to<Node3D>(node);
8780 Dictionary d = kv.value;
8781 Vector3 from = d["from"];
8782 Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
8783 HashSet<RID> excluded = _get_physics_bodies_rid(sp);
8784
8785 PhysicsDirectSpaceState3D::RayParameters ray_params;
8786 ray_params.from = from;
8787 ray_params.to = to;
8788 ray_params.exclude = excluded;
8789
8790 if (ss->intersect_ray(ray_params, result)) {
8791 snapped_to_floor = true;
8792 }
8793 }
8794
8795 if (snapped_to_floor) {
8796 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
8797 undo_redo->create_action(TTR("Snap Nodes to Floor"));
8798
8799 // Perform snapping if at least one node can be snapped
8800 for (const KeyValue<Variant, Variant> &kv : snap_data) {
8801 Node *node = Object::cast_to<Node>(kv.key);
8802 Node3D *sp = Object::cast_to<Node3D>(node);
8803 Dictionary d = kv.value;
8804 Vector3 from = d["from"];
8805 Vector3 to = from - Vector3(0.0, max_snap_height, 0.0);
8806 HashSet<RID> excluded = _get_physics_bodies_rid(sp);
8807
8808 PhysicsDirectSpaceState3D::RayParameters ray_params;
8809 ray_params.from = from;
8810 ray_params.to = to;
8811 ray_params.exclude = excluded;
8812
8813 if (ss->intersect_ray(ray_params, result)) {
8814 Vector3 position_offset = d["position_offset"];
8815 Transform3D new_transform = sp->get_global_transform();
8816
8817 new_transform.origin.y = result.position.y;
8818 new_transform.origin = new_transform.origin - position_offset;
8819
8820 Node3D *parent = sp->get_parent_node_3d();
8821 Transform3D new_local_xform = parent ? parent->get_global_transform().affine_inverse() * new_transform : new_transform;
8822 undo_redo->add_do_method(sp, "set_transform", new_local_xform);
8823 undo_redo->add_undo_method(sp, "set_transform", sp->get_transform());
8824 }
8825 }
8826
8827 undo_redo->commit_action();
8828 } else {
8829 EditorNode::get_singleton()->show_warning(TTR("Couldn't find a solid floor to snap the selection to."));
8830 }
8831 }
8832 }
8833
8834 void Node3DEditor::shortcut_input(const Ref<InputEvent> &p_event) {
8835 ERR_FAIL_COND(p_event.is_null());
8836
8837 if (!is_visible_in_tree()) {
8838 return;
8839 }
8840
8841 snap_key_enabled = Input::get_singleton()->is_key_pressed(Key::CMD_OR_CTRL);
8842 }
8843
8844 void Node3DEditor::_sun_environ_settings_pressed() {
8845 Vector2 pos = sun_environ_settings->get_screen_position() + sun_environ_settings->get_size();
8846 sun_environ_popup->set_position(pos - Vector2(sun_environ_popup->get_contents_minimum_size().width / 2, 0));
8847 sun_environ_popup->reset_size();
8848 sun_environ_popup->popup();
8849 // Grabbing the focus is required for Shift modifier checking to be functional
8850 // (when the Add sun/environment buttons are pressed).
8851 sun_environ_popup->grab_focus();
8852 }
8853
8854 void Node3DEditor::_add_sun_to_scene(bool p_already_added_environment) {
8855 sun_environ_popup->hide();
8856
8857 if (!p_already_added_environment && world_env_count == 0 && Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
8858 // Prevent infinite feedback loop between the sun and environment methods.
8859 _add_environment_to_scene(true);
8860 }
8861
8862 Node *base = get_tree()->get_edited_scene_root();
8863 if (!base) {
8864 // Create a root node so we can add child nodes to it.
8865 SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
8866 base = get_tree()->get_edited_scene_root();
8867 }
8868 ERR_FAIL_NULL(base);
8869 Node *new_sun = preview_sun->duplicate();
8870
8871 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
8872 undo_redo->create_action(TTR("Add Preview Sun to Scene"));
8873 undo_redo->add_do_method(base, "add_child", new_sun, true);
8874 // Move to the beginning of the scene tree since more "global" nodes
8875 // generally look better when placed at the top.
8876 undo_redo->add_do_method(base, "move_child", new_sun, 0);
8877 undo_redo->add_do_method(new_sun, "set_owner", base);
8878 undo_redo->add_undo_method(base, "remove_child", new_sun);
8879 undo_redo->add_do_reference(new_sun);
8880 undo_redo->commit_action();
8881 }
8882
8883 void Node3DEditor::_add_environment_to_scene(bool p_already_added_sun) {
8884 sun_environ_popup->hide();
8885
8886 if (!p_already_added_sun && directional_light_count == 0 && Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
8887 // Prevent infinite feedback loop between the sun and environment methods.
8888 _add_sun_to_scene(true);
8889 }
8890
8891 Node *base = get_tree()->get_edited_scene_root();
8892 if (!base) {
8893 // Create a root node so we can add child nodes to it.
8894 SceneTreeDock::get_singleton()->add_root_node(memnew(Node3D));
8895 base = get_tree()->get_edited_scene_root();
8896 }
8897 ERR_FAIL_NULL(base);
8898
8899 WorldEnvironment *new_env = memnew(WorldEnvironment);
8900 new_env->set_environment(preview_environment->get_environment()->duplicate(true));
8901 if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
8902 new_env->set_camera_attributes(preview_environment->get_camera_attributes()->duplicate(true));
8903 }
8904
8905 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
8906 undo_redo->create_action(TTR("Add Preview Environment to Scene"));
8907 undo_redo->add_do_method(base, "add_child", new_env, true);
8908 // Move to the beginning of the scene tree since more "global" nodes
8909 // generally look better when placed at the top.
8910 undo_redo->add_do_method(base, "move_child", new_env, 0);
8911 undo_redo->add_do_method(new_env, "set_owner", base);
8912 undo_redo->add_undo_method(base, "remove_child", new_env);
8913 undo_redo->add_do_reference(new_env);
8914 undo_redo->commit_action();
8915 }
8916
8917 void Node3DEditor::_update_theme() {
8918 tool_button[TOOL_MODE_TRANSFORM]->set_button_icon(get_editor_theme_icon(SNAME("ToolTransform")));
8919 tool_button[TOOL_MODE_MOVE]->set_button_icon(get_editor_theme_icon(SNAME("ToolMove")));
8920 tool_button[TOOL_MODE_ROTATE]->set_button_icon(get_editor_theme_icon(SNAME("ToolRotate")));
8921 tool_button[TOOL_MODE_SCALE]->set_button_icon(get_editor_theme_icon(SNAME("ToolScale")));
8922 tool_button[TOOL_MODE_SELECT]->set_button_icon(get_editor_theme_icon(SNAME("ToolSelect")));
8923 tool_button[TOOL_MODE_LIST_SELECT]->set_button_icon(get_editor_theme_icon(SNAME("ListSelect")));
8924 tool_button[TOOL_LOCK_SELECTED]->set_button_icon(get_editor_theme_icon(SNAME("Lock")));
8925 tool_button[TOOL_UNLOCK_SELECTED]->set_button_icon(get_editor_theme_icon(SNAME("Unlock")));
8926 tool_button[TOOL_GROUP_SELECTED]->set_button_icon(get_editor_theme_icon(SNAME("Group")));
8927 tool_button[TOOL_UNGROUP_SELECTED]->set_button_icon(get_editor_theme_icon(SNAME("Ungroup")));
8928 tool_button[TOOL_RULER]->set_button_icon(get_editor_theme_icon(SNAME("Ruler")));
8929
8930 tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_button_icon(get_editor_theme_icon(SNAME("Object")));
8931 tool_option_button[TOOL_OPT_USE_SNAP]->set_button_icon(get_editor_theme_icon(SNAME("Snap")));
8932
8933 view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), get_editor_theme_icon(SNAME("Panels1")));
8934 view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), get_editor_theme_icon(SNAME("Panels2")));
8935 view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), get_editor_theme_icon(SNAME("Panels2Alt")));
8936 view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), get_editor_theme_icon(SNAME("Panels3")));
8937 view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), get_editor_theme_icon(SNAME("Panels3Alt")));
8938 view_layout_menu->get_popup()->set_item_icon(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), get_editor_theme_icon(SNAME("Panels4")));
8939
8940 sun_button->set_button_icon(get_editor_theme_icon(SNAME("PreviewSun")));
8941 environ_button->set_button_icon(get_editor_theme_icon(SNAME("PreviewEnvironment")));
8942 sun_environ_settings->set_button_icon(get_editor_theme_icon(SNAME("GuiTabMenuHl")));
8943
8944 sun_title->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("title_font"), SNAME("Window")));
8945 environ_title->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("title_font"), SNAME("Window")));
8946
8947 sun_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("inspector_property_height"), EditorStringName(Editor))));
8948 environ_sky_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("inspector_property_height"), EditorStringName(Editor))));
8949 environ_ground_color->set_custom_minimum_size(Size2(0, get_theme_constant(SNAME("inspector_property_height"), EditorStringName(Editor))));
8950
8951 context_toolbar_panel->add_theme_style_override(SceneStringName(panel), get_theme_stylebox(SNAME("ContextualToolbar"), EditorStringName(EditorStyles)));
8952 }
8953
8954 void Node3DEditor::_notification(int p_what) {
8955 switch (p_what) {
8956 case NOTIFICATION_TRANSLATION_CHANGED: {
8957 tool_button[TOOL_MODE_TRANSFORM]->set_tooltip_text(vformat(TTR("%s+Drag: Rotate selected node around pivot."), keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL)) + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked.") + "\n" + TTR("(Available in all modes.)"));
8958 tool_button[TOOL_MODE_MOVE]->set_tooltip_text(vformat(TTR("%s+Drag: Use snap."), keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL)) + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
8959 tool_button[TOOL_MODE_ROTATE]->set_tooltip_text(vformat(TTR("%s+Drag: Use snap."), keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL)) + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
8960 tool_button[TOOL_MODE_SCALE]->set_tooltip_text(vformat(TTR("%s+Drag: Use snap."), keycode_get_string((Key)KeyModifierMask::CMD_OR_CTRL)) + "\n" + TTR("Alt+RMB: Show list of all nodes at position clicked, including locked."));
8961 tool_button[TOOL_MODE_SELECT]->set_tooltip_text(TTR("Alt+RMB: Show list of all nodes at position clicked, including locked.") + "\n" + TTR("(Available in all modes.)"));
8962 _update_gizmos_menu();
8963 } break;
8964
8965 case NOTIFICATION_READY: {
8966 _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
8967
8968 _refresh_menu_icons();
8969
8970 get_tree()->connect("node_removed", callable_mp(this, &Node3DEditor::_node_removed));
8971 get_tree()->connect("node_added", callable_mp(this, &Node3DEditor::_node_added));
8972 SceneTreeDock::get_singleton()->get_tree_editor()->connect("node_changed", callable_mp(this, &Node3DEditor::_refresh_menu_icons));
8973 editor_selection->connect("selection_changed", callable_mp(this, &Node3DEditor::_selection_changed));
8974
8975 _update_preview_environment();
8976
8977 sun_state->set_custom_minimum_size(sun_vb->get_combined_minimum_size());
8978 environ_state->set_custom_minimum_size(environ_vb->get_combined_minimum_size());
8979
8980 ProjectSettings::get_singleton()->connect("settings_changed", callable_mp(this, &Node3DEditor::update_all_gizmos).bind(Variant()));
8981 } break;
8982
8983 case NOTIFICATION_ACCESSIBILITY_UPDATE: {
8984 RID ae = get_accessibility_element();
8985 ERR_FAIL_COND(ae.is_null());
8986
8987 //TODO
8988 DisplayServer::get_singleton()->accessibility_update_set_role(ae, DisplayServer::AccessibilityRole::ROLE_STATIC_TEXT);
8989 DisplayServer::get_singleton()->accessibility_update_set_value(ae, TTR(vformat("The %s is not accessible at this time.", "3D editor")));
8990 } break;
8991
8992 case NOTIFICATION_ENTER_TREE: {
8993 _update_theme();
8994 _register_all_gizmos();
8995 _init_indicators();
8996 update_all_gizmos();
8997 } break;
8998
8999 case NOTIFICATION_EXIT_TREE: {
9000 _finish_indicators();
9001 } break;
9002
9003 case NOTIFICATION_THEME_CHANGED: {
9004 _update_theme();
9005 _update_gizmos_menu_theme();
9006 sun_title->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("title_font"), SNAME("Window")));
9007 environ_title->add_theme_font_override(SceneStringName(font), get_theme_font(SNAME("title_font"), SNAME("Window")));
9008 } break;
9009
9010 case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
9011 if (EditorSettings::get_singleton()->check_changed_settings_in_group("editors/3d")) {
9012 const Color selection_box_color = EDITOR_GET("editors/3d/selection_box_color");
9013 const Color active_selection_box_color = EDITOR_GET("editors/3d/active_selection_box_color");
9014
9015 if (selection_box_color != selection_box_mat->get_albedo()) {
9016 selection_box_mat->set_albedo(selection_box_color);
9017 selection_box_mat_xray->set_albedo(selection_box_color * Color(1, 1, 1, 0.15));
9018 }
9019
9020 if (active_selection_box_color != active_selection_box_mat->get_albedo()) {
9021 active_selection_box_mat->set_albedo(active_selection_box_color);
9022 active_selection_box_mat_xray->set_albedo(active_selection_box_color * Color(1, 1, 1, 0.15));
9023 }
9024
9025 // Update grid color by rebuilding grid.
9026 _finish_grid();
9027 _init_grid();
9028
9029 for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
9030 viewports[i]->update_transform_gizmo_view();
9031 }
9032 update_gizmo_opacity();
9033 }
9034 } break;
9035
9036 case NOTIFICATION_PHYSICS_PROCESS: {
9037 if (do_snap_selected_nodes_to_floor) {
9038 _snap_selected_nodes_to_floor();
9039 do_snap_selected_nodes_to_floor = false;
9040 }
9041 }
9042 }
9043 }
9044
9045 bool Node3DEditor::is_subgizmo_selected(int p_id) {
9046 Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
9047 if (se) {
9048 return se->subgizmos.has(p_id);
9049 }
9050 return false;
9051 }
9052
9053 bool Node3DEditor::is_current_selected_gizmo(const EditorNode3DGizmo *p_gizmo) {
9054 Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
9055 if (se) {
9056 return se->gizmo == p_gizmo;
9057 }
9058 return false;
9059 }
9060
9061 Vector<int> Node3DEditor::get_subgizmo_selection() {
9062 Node3DEditorSelectedItem *se = selected ? editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected) : nullptr;
9063
9064 Vector<int> ret;
9065 if (se) {
9066 for (const KeyValue<int, Transform3D> &E : se->subgizmos) {
9067 ret.push_back(E.key);
9068 }
9069 }
9070 return ret;
9071 }
9072
9073 void Node3DEditor::clear_subgizmo_selection(Object *p_obj) {
9074 _clear_subgizmo_selection(p_obj);
9075 }
9076
9077 void Node3DEditor::add_control_to_menu_panel(Control *p_control) {
9078 ERR_FAIL_NULL(p_control);
9079 ERR_FAIL_COND(p_control->get_parent());
9080
9081 VSeparator *sep = memnew(VSeparator);
9082 context_toolbar_hbox->add_child(sep);
9083 context_toolbar_hbox->add_child(p_control);
9084 context_toolbar_separators[p_control] = sep;
9085
9086 p_control->connect(SceneStringName(visibility_changed), callable_mp(this, &Node3DEditor::_update_context_toolbar));
9087
9088 _update_context_toolbar();
9089 }
9090
9091 void Node3DEditor::remove_control_from_menu_panel(Control *p_control) {
9092 ERR_FAIL_NULL(p_control);
9093 ERR_FAIL_COND(p_control->get_parent() != context_toolbar_hbox);
9094
9095 p_control->disconnect(SceneStringName(visibility_changed), callable_mp(this, &Node3DEditor::_update_context_toolbar));
9096
9097 VSeparator *sep = context_toolbar_separators[p_control];
9098 context_toolbar_hbox->remove_child(sep);
9099 context_toolbar_hbox->remove_child(p_control);
9100 context_toolbar_separators.erase(p_control);
9101 memdelete(sep);
9102
9103 _update_context_toolbar();
9104 }
9105
9106 void Node3DEditor::_update_context_toolbar() {
9107 bool has_visible = false;
9108 bool first_visible = false;
9109
9110 for (int i = 0; i < context_toolbar_hbox->get_child_count(); i++) {
9111 Control *child = Object::cast_to<Control>(context_toolbar_hbox->get_child(i));
9112 if (!child || !context_toolbar_separators.has(child)) {
9113 continue;
9114 }
9115 if (child->is_visible()) {
9116 first_visible = !has_visible;
9117 has_visible = true;
9118 }
9119
9120 VSeparator *sep = context_toolbar_separators[child];
9121 sep->set_visible(!first_visible && child->is_visible());
9122 }
9123
9124 context_toolbar_panel->set_visible(has_visible);
9125 }
9126
9127 void Node3DEditor::set_can_preview(Camera3D *p_preview) {
9128 for (int i = 0; i < 4; i++) {
9129 viewports[i]->set_can_preview(p_preview);
9130 }
9131 }
9132
9133 VSplitContainer *Node3DEditor::get_shader_split() {
9134 return shader_split;
9135 }
9136
9137 Node3DEditorViewport *Node3DEditor::get_last_used_viewport() {
9138 return viewports[last_used_viewport];
9139 }
9140
9141 void Node3DEditor::add_control_to_left_panel(Control *p_control) {
9142 left_panel_split->add_child(p_control);
9143 left_panel_split->move_child(p_control, 0);
9144 }
9145
9146 void Node3DEditor::add_control_to_right_panel(Control *p_control) {
9147 right_panel_split->add_child(p_control);
9148 right_panel_split->move_child(p_control, 1);
9149 }
9150
9151 void Node3DEditor::remove_control_from_left_panel(Control *p_control) {
9152 left_panel_split->remove_child(p_control);
9153 }
9154
9155 void Node3DEditor::remove_control_from_right_panel(Control *p_control) {
9156 right_panel_split->remove_child(p_control);
9157 }
9158
9159 void Node3DEditor::move_control_to_left_panel(Control *p_control) {
9160 ERR_FAIL_NULL(p_control);
9161 if (p_control->get_parent() == left_panel_split) {
9162 return;
9163 }
9164
9165 ERR_FAIL_COND(p_control->get_parent() != right_panel_split);
9166 right_panel_split->remove_child(p_control);
9167
9168 add_control_to_left_panel(p_control);
9169 }
9170
9171 void Node3DEditor::move_control_to_right_panel(Control *p_control) {
9172 ERR_FAIL_NULL(p_control);
9173 if (p_control->get_parent() == right_panel_split) {
9174 return;
9175 }
9176
9177 ERR_FAIL_COND(p_control->get_parent() != left_panel_split);
9178 left_panel_split->remove_child(p_control);
9179
9180 add_control_to_right_panel(p_control);
9181 }
9182
9183 void Node3DEditor::_request_gizmo(Object *p_obj) {
9184 Node3D *sp = Object::cast_to<Node3D>(p_obj);
9185 if (!sp) {
9186 return;
9187 }
9188
9189 bool is_selected = (sp == selected);
9190
9191 Node *edited_scene = EditorNode::get_singleton()->get_edited_scene();
9192 if (edited_scene && (sp == edited_scene || (sp->get_owner() && edited_scene->is_ancestor_of(sp)))) {
9193 for (int i = 0; i < gizmo_plugins_by_priority.size(); ++i) {
9194 Ref<EditorNode3DGizmo> seg = gizmo_plugins_by_priority.write[i]->get_gizmo(sp);
9195
9196 if (seg.is_valid()) {
9197 sp->add_gizmo(seg);
9198
9199 if (is_selected != seg->is_selected()) {
9200 seg->set_selected(is_selected);
9201 }
9202 }
9203 }
9204 if (!sp->get_gizmos().is_empty()) {
9205 sp->update_gizmos();
9206 }
9207 }
9208 }
9209
9210 void Node3DEditor::_request_gizmo_for_id(ObjectID p_id) {
9211 Node3D *node = ObjectDB::get_instance<Node3D>(p_id);
9212 if (node) {
9213 _request_gizmo(node);
9214 }
9215 }
9216
9217 void Node3DEditor::_set_subgizmo_selection(Object *p_obj, Ref<Node3DGizmo> p_gizmo, int p_id, Transform3D p_transform) {
9218 if (p_id == -1) {
9219 _clear_subgizmo_selection(p_obj);
9220 return;
9221 }
9222
9223 Node3D *sp = nullptr;
9224 if (p_obj) {
9225 sp = Object::cast_to<Node3D>(p_obj);
9226 } else {
9227 sp = selected;
9228 }
9229
9230 if (!sp) {
9231 return;
9232 }
9233
9234 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
9235 if (se) {
9236 se->subgizmos.clear();
9237 se->subgizmos.insert(p_id, p_transform);
9238 se->gizmo = p_gizmo;
9239 sp->update_gizmos();
9240 update_transform_gizmo();
9241 }
9242 }
9243
9244 void Node3DEditor::_clear_subgizmo_selection(Object *p_obj) {
9245 Node3D *sp = nullptr;
9246 if (p_obj) {
9247 sp = Object::cast_to<Node3D>(p_obj);
9248 } else {
9249 sp = selected;
9250 }
9251
9252 if (!sp) {
9253 return;
9254 }
9255
9256 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(sp);
9257 if (se) {
9258 se->subgizmos.clear();
9259 se->gizmo.unref();
9260 sp->update_gizmos();
9261 update_transform_gizmo();
9262 }
9263 }
9264
9265 void Node3DEditor::_toggle_maximize_view(Object *p_viewport) {
9266 if (!p_viewport) {
9267 return;
9268 }
9269 Node3DEditorViewport *current_viewport = Object::cast_to<Node3DEditorViewport>(p_viewport);
9270 if (!current_viewport) {
9271 return;
9272 }
9273
9274 int index = -1;
9275 bool maximized = false;
9276 for (int i = 0; i < 4; i++) {
9277 if (viewports[i] == current_viewport) {
9278 index = i;
9279 if (current_viewport->get_global_rect() == viewport_base->get_global_rect()) {
9280 maximized = true;
9281 }
9282 break;
9283 }
9284 }
9285 if (index == -1) {
9286 return;
9287 }
9288
9289 if (!maximized) {
9290 for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
9291 if (i == (uint32_t)index) {
9292 viewports[i]->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
9293 } else {
9294 viewports[i]->hide();
9295 }
9296 }
9297 } else {
9298 for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
9299 viewports[i]->show();
9300 }
9301
9302 if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT))) {
9303 _menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
9304 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS))) {
9305 _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
9306 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT))) {
9307 _menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
9308 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS))) {
9309 _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
9310 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT))) {
9311 _menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
9312 } else if (view_layout_menu->get_popup()->is_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS))) {
9313 _menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
9314 }
9315 }
9316 }
9317
9318 void Node3DEditor::_viewport_clicked(int p_viewport_idx) {
9319 last_used_viewport = p_viewport_idx;
9320 }
9321
9322 void Node3DEditor::_node_added(Node *p_node) {
9323 if (EditorNode::get_singleton()->get_scene_root()->is_ancestor_of(p_node)) {
9324 if (Object::cast_to<WorldEnvironment>(p_node)) {
9325 world_env_count++;
9326 if (world_env_count == 1) {
9327 _update_preview_environment();
9328 }
9329 } else if (Object::cast_to<DirectionalLight3D>(p_node)) {
9330 directional_light_count++;
9331 if (directional_light_count == 1) {
9332 _update_preview_environment();
9333 }
9334 }
9335 }
9336 }
9337
9338 void Node3DEditor::_node_removed(Node *p_node) {
9339 if (EditorNode::get_singleton()->get_scene_root()->is_ancestor_of(p_node)) {
9340 if (Object::cast_to<WorldEnvironment>(p_node)) {
9341 world_env_count--;
9342 if (world_env_count == 0) {
9343 _update_preview_environment();
9344 }
9345 } else if (Object::cast_to<DirectionalLight3D>(p_node)) {
9346 directional_light_count--;
9347 if (directional_light_count == 0) {
9348 _update_preview_environment();
9349 }
9350 }
9351 }
9352
9353 if (p_node == selected) {
9354 Node3DEditorSelectedItem *se = editor_selection->get_node_editor_data<Node3DEditorSelectedItem>(selected);
9355 if (se) {
9356 se->gizmo.unref();
9357 se->subgizmos.clear();
9358 }
9359 selected = nullptr;
9360 update_transform_gizmo();
9361 }
9362 }
9363
9364 void Node3DEditor::_register_all_gizmos() {
9365 add_gizmo_plugin(Ref<Camera3DGizmoPlugin>(memnew(Camera3DGizmoPlugin)));
9366 add_gizmo_plugin(Ref<Light3DGizmoPlugin>(memnew(Light3DGizmoPlugin)));
9367 add_gizmo_plugin(Ref<AudioStreamPlayer3DGizmoPlugin>(memnew(AudioStreamPlayer3DGizmoPlugin)));
9368 add_gizmo_plugin(Ref<AudioListener3DGizmoPlugin>(memnew(AudioListener3DGizmoPlugin)));
9369 add_gizmo_plugin(Ref<MeshInstance3DGizmoPlugin>(memnew(MeshInstance3DGizmoPlugin)));
9370 add_gizmo_plugin(Ref<OccluderInstance3DGizmoPlugin>(memnew(OccluderInstance3DGizmoPlugin)));
9371 add_gizmo_plugin(Ref<SoftBody3DGizmoPlugin>(memnew(SoftBody3DGizmoPlugin)));
9372 add_gizmo_plugin(Ref<SpriteBase3DGizmoPlugin>(memnew(SpriteBase3DGizmoPlugin)));
9373 add_gizmo_plugin(Ref<Label3DGizmoPlugin>(memnew(Label3DGizmoPlugin)));
9374 add_gizmo_plugin(Ref<GeometryInstance3DGizmoPlugin>(memnew(GeometryInstance3DGizmoPlugin)));
9375 add_gizmo_plugin(Ref<Marker3DGizmoPlugin>(memnew(Marker3DGizmoPlugin)));
9376 add_gizmo_plugin(Ref<RayCast3DGizmoPlugin>(memnew(RayCast3DGizmoPlugin)));
9377 add_gizmo_plugin(Ref<ShapeCast3DGizmoPlugin>(memnew(ShapeCast3DGizmoPlugin)));
9378 add_gizmo_plugin(Ref<SpringArm3DGizmoPlugin>(memnew(SpringArm3DGizmoPlugin)));
9379 add_gizmo_plugin(Ref<SpringBoneCollision3DGizmoPlugin>(memnew(SpringBoneCollision3DGizmoPlugin)));
9380 add_gizmo_plugin(Ref<SpringBoneSimulator3DGizmoPlugin>(memnew(SpringBoneSimulator3DGizmoPlugin)));
9381 add_gizmo_plugin(Ref<VehicleWheel3DGizmoPlugin>(memnew(VehicleWheel3DGizmoPlugin)));
9382 add_gizmo_plugin(Ref<VisibleOnScreenNotifier3DGizmoPlugin>(memnew(VisibleOnScreenNotifier3DGizmoPlugin)));
9383 add_gizmo_plugin(Ref<GPUParticles3DGizmoPlugin>(memnew(GPUParticles3DGizmoPlugin)));
9384 add_gizmo_plugin(Ref<GPUParticlesCollision3DGizmoPlugin>(memnew(GPUParticlesCollision3DGizmoPlugin)));
9385 add_gizmo_plugin(Ref<Particles3DEmissionShapeGizmoPlugin>(memnew(Particles3DEmissionShapeGizmoPlugin)));
9386 add_gizmo_plugin(Ref<CPUParticles3DGizmoPlugin>(memnew(CPUParticles3DGizmoPlugin)));
9387 add_gizmo_plugin(Ref<ReflectionProbeGizmoPlugin>(memnew(ReflectionProbeGizmoPlugin)));
9388 add_gizmo_plugin(Ref<DecalGizmoPlugin>(memnew(DecalGizmoPlugin)));
9389 add_gizmo_plugin(Ref<VoxelGIGizmoPlugin>(memnew(VoxelGIGizmoPlugin)));
9390 add_gizmo_plugin(Ref<LightmapGIGizmoPlugin>(memnew(LightmapGIGizmoPlugin)));
9391 add_gizmo_plugin(Ref<LightmapProbeGizmoPlugin>(memnew(LightmapProbeGizmoPlugin)));
9392 add_gizmo_plugin(Ref<CollisionObject3DGizmoPlugin>(memnew(CollisionObject3DGizmoPlugin)));
9393 add_gizmo_plugin(Ref<CollisionShape3DGizmoPlugin>(memnew(CollisionShape3DGizmoPlugin)));
9394 add_gizmo_plugin(Ref<CollisionPolygon3DGizmoPlugin>(memnew(CollisionPolygon3DGizmoPlugin)));
9395 add_gizmo_plugin(Ref<Joint3DGizmoPlugin>(memnew(Joint3DGizmoPlugin)));
9396 add_gizmo_plugin(Ref<PhysicalBone3DGizmoPlugin>(memnew(PhysicalBone3DGizmoPlugin)));
9397 add_gizmo_plugin(Ref<FogVolumeGizmoPlugin>(memnew(FogVolumeGizmoPlugin)));
9398 add_gizmo_plugin(Ref<TwoBoneIK3DGizmoPlugin>(memnew(TwoBoneIK3DGizmoPlugin)));
9399 add_gizmo_plugin(Ref<ChainIK3DGizmoPlugin>(memnew(ChainIK3DGizmoPlugin)));
9400 }
9401
9402 void Node3DEditor::_bind_methods() {
9403 ClassDB::bind_method("_get_editor_data", &Node3DEditor::_get_editor_data);
9404 ClassDB::bind_method("_request_gizmo", &Node3DEditor::_request_gizmo);
9405 ClassDB::bind_method("_request_gizmo_for_id", &Node3DEditor::_request_gizmo_for_id);
9406 ClassDB::bind_method("_set_subgizmo_selection", &Node3DEditor::_set_subgizmo_selection);
9407 ClassDB::bind_method("_clear_subgizmo_selection", &Node3DEditor::_clear_subgizmo_selection);
9408 ClassDB::bind_method("_refresh_menu_icons", &Node3DEditor::_refresh_menu_icons);
9409 ClassDB::bind_method("_preview_settings_changed", &Node3DEditor::_preview_settings_changed);
9410
9411 ClassDB::bind_method("update_all_gizmos", &Node3DEditor::update_all_gizmos);
9412 ClassDB::bind_method("update_transform_gizmo", &Node3DEditor::update_transform_gizmo);
9413
9414 ADD_SIGNAL(MethodInfo("transform_key_request"));
9415 ADD_SIGNAL(MethodInfo("item_lock_status_changed"));
9416 ADD_SIGNAL(MethodInfo("item_group_status_changed"));
9417 }
9418
9419 void Node3DEditor::clear() {
9420 settings_fov->set_value(EDITOR_GET("editors/3d/default_fov"));
9421 settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near"));
9422 settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far"));
9423
9424 snap_translate_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_translate_value", 1);
9425 snap_rotate_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_rotate_value", 15);
9426 snap_scale_value = EditorSettings::get_singleton()->get_project_metadata("3d_editor", "snap_scale_value", 10);
9427 _snap_update();
9428
9429 for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
9430 viewports[i]->reset();
9431 }
9432
9433 if (origin_instance.is_valid()) {
9434 RenderingServer::get_singleton()->instance_set_visible(origin_instance, true);
9435 }
9436
9437 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
9438 for (int i = 0; i < 3; ++i) {
9439 if (grid_enable[i]) {
9440 grid_visible[i] = true;
9441 }
9442 }
9443
9444 for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
9445 viewports[i]->view_display_menu->get_popup()->set_item_checked(viewports[i]->view_display_menu->get_popup()->get_item_index(Node3DEditorViewport::VIEW_AUDIO_LISTENER), i == 0);
9446 viewports[i]->viewport->set_as_audio_listener_3d(i == 0);
9447 }
9448
9449 view_layout_menu->get_popup()->set_item_checked(view_layout_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true);
9450 grid_enabled = true;
9451 grid_init_draw = false;
9452 }
9453
9454 void Node3DEditor::_sun_direction_draw() {
9455 sun_direction->draw_rect(Rect2(Vector2(), sun_direction->get_size()), Color(1, 1, 1, 1));
9456 Vector3 z_axis = preview_sun->get_transform().basis.get_column(Vector3::AXIS_Z);
9457 z_axis = get_editor_viewport(0)->camera->get_camera_transform().basis.xform_inv(z_axis);
9458 sun_direction_material->set_shader_parameter("sun_direction", Vector3(z_axis.x, -z_axis.y, z_axis.z));
9459 Color color = sun_color->get_pick_color() * sun_energy->get_value();
9460 sun_direction_material->set_shader_parameter("sun_color", Vector3(color.r, color.g, color.b));
9461 }
9462
9463 void Node3DEditor::_preview_settings_changed() {
9464 if (sun_environ_updating) {
9465 return;
9466 }
9467
9468 { // preview sun
9469 sun_rotation.x = Math::deg_to_rad(-sun_angle_altitude->get_value());
9470 sun_rotation.y = Math::deg_to_rad(180.0 - sun_angle_azimuth->get_value());
9471 Transform3D t;
9472 t.basis = Basis::from_euler(Vector3(sun_rotation.x, sun_rotation.y, 0));
9473 preview_sun->set_transform(t);
9474 sun_direction->queue_redraw();
9475 preview_sun->set_param(Light3D::PARAM_ENERGY, sun_energy->get_value());
9476 preview_sun->set_param(Light3D::PARAM_SHADOW_MAX_DISTANCE, sun_shadow_max_distance->get_value());
9477 preview_sun->set_color(sun_color->get_pick_color());
9478 }
9479
9480 { //preview env
9481 sky_material->set_energy_multiplier(environ_energy->get_value());
9482 Color hz_color = environ_sky_color->get_pick_color().lerp(environ_ground_color->get_pick_color(), 0.5);
9483 float hz_lum = hz_color.get_luminance() * 3.333;
9484 hz_color = hz_color.lerp(Color(hz_lum, hz_lum, hz_lum), 0.5);
9485 sky_material->set_sky_top_color(environ_sky_color->get_pick_color());
9486 sky_material->set_sky_horizon_color(hz_color);
9487 sky_material->set_ground_bottom_color(environ_ground_color->get_pick_color());
9488 sky_material->set_ground_horizon_color(hz_color);
9489
9490 environment->set_ssao_enabled(environ_ao_button->is_pressed());
9491 environment->set_glow_enabled(environ_glow_button->is_pressed());
9492 environment->set_sdfgi_enabled(environ_gi_button->is_pressed());
9493 environment->set_tonemapper(environ_tonemap_button->is_pressed() ? Environment::TONE_MAPPER_FILMIC : Environment::TONE_MAPPER_LINEAR);
9494 }
9495 }
9496
9497 void Node3DEditor::_load_default_preview_settings() {
9498 sun_environ_updating = true;
9499
9500 // These default rotations place the preview sun at an angular altitude
9501 // of 60 degrees (must be negative) and an azimuth of 30 degrees clockwise
9502 // from north (or 150 CCW from south), from north east, facing south west.
9503 // On any not-tidally-locked planet, a sun would have an angular altitude
9504 // of 60 degrees as the average of all points on the sphere at noon.
9505 // The azimuth choice is arbitrary, but ideally shouldn't be on an axis.
9506 sun_rotation = Vector2(-Math::deg_to_rad(60.0), Math::deg_to_rad(150.0));
9507
9508 sun_angle_altitude->set_value_no_signal(-Math::rad_to_deg(sun_rotation.x));
9509 sun_angle_azimuth->set_value_no_signal(180.0 - Math::rad_to_deg(sun_rotation.y));
9510 sun_direction->queue_redraw();
9511 environ_sky_color->set_pick_color(Color(0.385, 0.454, 0.55));
9512 environ_ground_color->set_pick_color(Color(0.2, 0.169, 0.133));
9513 environ_energy->set_value_no_signal(1.0);
9514 if (OS::get_singleton()->get_current_rendering_method() != "gl_compatibility" && OS::get_singleton()->get_current_rendering_method() != "dummy") {
9515 environ_glow_button->set_pressed_no_signal(true);
9516 }
9517 environ_tonemap_button->set_pressed_no_signal(true);
9518 environ_ao_button->set_pressed_no_signal(false);
9519 environ_gi_button->set_pressed_no_signal(false);
9520 sun_shadow_max_distance->set_value_no_signal(100);
9521
9522 sun_color->set_pick_color(Color(1, 1, 1));
9523 sun_energy->set_value_no_signal(1.0);
9524
9525 sun_environ_updating = false;
9526 }
9527
9528 void Node3DEditor::_update_preview_environment() {
9529 bool disable_light = directional_light_count > 0 || !sun_button->is_pressed();
9530
9531 sun_button->set_disabled(directional_light_count > 0);
9532
9533 if (disable_light) {
9534 if (preview_sun->get_parent()) {
9535 preview_sun->get_parent()->remove_child(preview_sun);
9536 sun_state->show();
9537 sun_vb->hide();
9538 preview_sun_dangling = true;
9539 }
9540
9541 if (directional_light_count > 0) {
9542 sun_state->set_text(TTRC("Scene contains\nDirectionalLight3D.\nPreview disabled."));
9543 } else {
9544 sun_state->set_text(TTRC("Preview disabled."));
9545 }
9546
9547 } else {
9548 if (!preview_sun->get_parent()) {
9549 add_child(preview_sun, true);
9550 sun_state->hide();
9551 sun_vb->show();
9552 preview_sun_dangling = false;
9553 }
9554 }
9555
9556 sun_angle_altitude->set_value_no_signal(-Math::rad_to_deg(sun_rotation.x));
9557 sun_angle_azimuth->set_value_no_signal(180.0 - Math::rad_to_deg(sun_rotation.y));
9558
9559 bool disable_env = world_env_count > 0 || !environ_button->is_pressed();
9560
9561 environ_button->set_disabled(world_env_count > 0);
9562
9563 if (disable_env) {
9564 if (preview_environment->get_parent()) {
9565 preview_environment->get_parent()->remove_child(preview_environment);
9566 environ_state->show();
9567 environ_vb->hide();
9568 preview_env_dangling = true;
9569 }
9570 if (world_env_count > 0) {
9571 environ_state->set_text(TTRC("Scene contains\nWorldEnvironment.\nPreview disabled."));
9572 } else {
9573 environ_state->set_text(TTRC("Preview disabled."));
9574 }
9575
9576 } else {
9577 if (!preview_environment->get_parent()) {
9578 add_child(preview_environment);
9579 environ_state->hide();
9580 environ_vb->show();
9581 preview_env_dangling = false;
9582 }
9583 }
9584 }
9585
9586 void Node3DEditor::_sun_direction_input(const Ref<InputEvent> &p_event) {
9587 Ref<InputEventMouseMotion> mm = p_event;
9588 if (mm.is_valid() && mm->get_button_mask().has_flag(MouseButtonMask::LEFT)) {
9589 sun_rotation.x += mm->get_relative().y * (0.02 * EDSCALE);
9590 sun_rotation.y -= mm->get_relative().x * (0.02 * EDSCALE);
9591 sun_rotation.x = CLAMP(sun_rotation.x, -Math::TAU / 4, Math::TAU / 4);
9592
9593 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9594 undo_redo->create_action(TTR("Set Preview Sun Direction"), UndoRedo::MergeMode::MERGE_ENDS);
9595 undo_redo->add_do_method(sun_angle_altitude, "set_value_no_signal", -Math::rad_to_deg(sun_rotation.x));
9596 undo_redo->add_undo_method(sun_angle_altitude, "set_value_no_signal", sun_angle_altitude->get_value());
9597 undo_redo->add_do_method(sun_angle_azimuth, "set_value_no_signal", 180.0 - Math::rad_to_deg(sun_rotation.y));
9598 undo_redo->add_undo_method(sun_angle_azimuth, "set_value_no_signal", sun_angle_azimuth->get_value());
9599 undo_redo->add_do_method(this, "_preview_settings_changed");
9600 undo_redo->add_undo_method(this, "_preview_settings_changed");
9601 undo_redo->commit_action();
9602 }
9603 }
9604
9605 void Node3DEditor::_sun_direction_set_altitude(float p_altitude) {
9606 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9607 undo_redo->create_action(TTR("Set Preview Sun Altitude"), UndoRedo::MergeMode::MERGE_ENDS);
9608 undo_redo->add_do_method(sun_angle_altitude, "set_value_no_signal", p_altitude);
9609 undo_redo->add_undo_method(sun_angle_altitude, "set_value_no_signal", -Math::rad_to_deg(sun_rotation.x));
9610 undo_redo->add_do_method(this, "_preview_settings_changed");
9611 undo_redo->add_undo_method(this, "_preview_settings_changed");
9612 undo_redo->commit_action();
9613 }
9614
9615 void Node3DEditor::_sun_direction_set_azimuth(float p_azimuth) {
9616 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9617 undo_redo->create_action(TTR("Set Preview Sun Azimuth"), UndoRedo::MergeMode::MERGE_ENDS);
9618 undo_redo->add_do_method(sun_angle_azimuth, "set_value_no_signal", p_azimuth);
9619 undo_redo->add_undo_method(sun_angle_azimuth, "set_value_no_signal", 180.0 - Math::rad_to_deg(sun_rotation.y));
9620 undo_redo->add_do_method(this, "_preview_settings_changed");
9621 undo_redo->add_undo_method(this, "_preview_settings_changed");
9622 undo_redo->commit_action();
9623 }
9624
9625 void Node3DEditor::_sun_set_color(const Color &p_color) {
9626 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9627 undo_redo->create_action(TTR("Set Preview Sun Color"), UndoRedo::MergeMode::MERGE_ENDS);
9628 undo_redo->add_do_method(sun_color, "set_pick_color", p_color);
9629 undo_redo->add_undo_method(sun_color, "set_pick_color", preview_sun->get_color());
9630 undo_redo->add_do_method(this, "_preview_settings_changed");
9631 undo_redo->add_undo_method(this, "_preview_settings_changed");
9632 undo_redo->commit_action();
9633 }
9634
9635 void Node3DEditor::_sun_set_energy(float p_energy) {
9636 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9637 undo_redo->create_action(TTR("Set Preview Sun Energy"), UndoRedo::MergeMode::MERGE_ENDS);
9638 undo_redo->add_do_method(sun_energy, "set_value_no_signal", p_energy);
9639 undo_redo->add_undo_method(sun_energy, "set_value_no_signal", preview_sun->get_param(Light3D::PARAM_ENERGY));
9640 undo_redo->add_do_method(this, "_preview_settings_changed");
9641 undo_redo->add_undo_method(this, "_preview_settings_changed");
9642 undo_redo->commit_action();
9643 }
9644
9645 void Node3DEditor::_sun_set_shadow_max_distance(float p_shadow_max_distance) {
9646 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9647 undo_redo->create_action(TTR("Set Preview Sun Max Shadow Distance"), UndoRedo::MergeMode::MERGE_ENDS);
9648 undo_redo->add_do_method(sun_shadow_max_distance, "set_value_no_signal", p_shadow_max_distance);
9649 undo_redo->add_undo_method(sun_shadow_max_distance, "set_value_no_signal", preview_sun->get_param(Light3D::PARAM_SHADOW_MAX_DISTANCE));
9650 undo_redo->add_do_method(this, "_preview_settings_changed");
9651 undo_redo->add_undo_method(this, "_preview_settings_changed");
9652 undo_redo->commit_action();
9653 }
9654
9655 void Node3DEditor::_environ_set_sky_color(const Color &p_color) {
9656 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9657 undo_redo->create_action(TTR("Set Preview Environment Sky Color"), UndoRedo::MergeMode::MERGE_ENDS);
9658 undo_redo->add_do_method(environ_sky_color, "set_pick_color", p_color);
9659 undo_redo->add_undo_method(environ_sky_color, "set_pick_color", sky_material->get_sky_top_color());
9660 undo_redo->add_do_method(this, "_preview_settings_changed");
9661 undo_redo->add_undo_method(this, "_preview_settings_changed");
9662 undo_redo->commit_action();
9663 }
9664
9665 void Node3DEditor::_environ_set_ground_color(const Color &p_color) {
9666 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9667 undo_redo->create_action(TTR("Set Preview Environment Ground Color"), UndoRedo::MergeMode::MERGE_ENDS);
9668 undo_redo->add_do_method(environ_ground_color, "set_pick_color", p_color);
9669 undo_redo->add_undo_method(environ_ground_color, "set_pick_color", sky_material->get_ground_bottom_color());
9670 undo_redo->add_do_method(this, "_preview_settings_changed");
9671 undo_redo->add_undo_method(this, "_preview_settings_changed");
9672 undo_redo->commit_action();
9673 }
9674
9675 void Node3DEditor::_environ_set_sky_energy(float p_energy) {
9676 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9677 undo_redo->create_action(TTR("Set Preview Environment Energy"), UndoRedo::MergeMode::MERGE_ENDS);
9678 undo_redo->add_do_method(environ_energy, "set_value_no_signal", p_energy);
9679 undo_redo->add_undo_method(environ_energy, "set_value_no_signal", sky_material->get_energy_multiplier());
9680 undo_redo->add_do_method(this, "_preview_settings_changed");
9681 undo_redo->add_undo_method(this, "_preview_settings_changed");
9682 undo_redo->commit_action();
9683 }
9684
9685 void Node3DEditor::_environ_set_ao() {
9686 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9687 undo_redo->create_action(TTR("Set Preview Environment Ambient Occlusion"));
9688 undo_redo->add_do_method(environ_ao_button, "set_pressed", environ_ao_button->is_pressed());
9689 undo_redo->add_undo_method(environ_ao_button, "set_pressed", !environ_ao_button->is_pressed());
9690 undo_redo->add_do_method(this, "_preview_settings_changed");
9691 undo_redo->add_undo_method(this, "_preview_settings_changed");
9692 undo_redo->commit_action();
9693 }
9694
9695 void Node3DEditor::_environ_set_glow() {
9696 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9697 undo_redo->create_action(TTR("Set Preview Environment Glow"));
9698 undo_redo->add_do_method(environ_glow_button, "set_pressed", environ_glow_button->is_pressed());
9699 undo_redo->add_undo_method(environ_glow_button, "set_pressed", !environ_glow_button->is_pressed());
9700 undo_redo->add_do_method(this, "_preview_settings_changed");
9701 undo_redo->add_undo_method(this, "_preview_settings_changed");
9702 undo_redo->commit_action();
9703 }
9704
9705 void Node3DEditor::_environ_set_tonemap() {
9706 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9707 undo_redo->create_action(TTR("Set Preview Environment Tonemap"));
9708 undo_redo->add_do_method(environ_tonemap_button, "set_pressed", environ_tonemap_button->is_pressed());
9709 undo_redo->add_undo_method(environ_tonemap_button, "set_pressed", !environ_tonemap_button->is_pressed());
9710 undo_redo->add_do_method(this, "_preview_settings_changed");
9711 undo_redo->add_undo_method(this, "_preview_settings_changed");
9712 undo_redo->commit_action();
9713 }
9714
9715 void Node3DEditor::_environ_set_gi() {
9716 EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
9717 undo_redo->create_action(TTR("Set Preview Environment Global Illumination"));
9718 undo_redo->add_do_method(environ_gi_button, "set_pressed", environ_gi_button->is_pressed());
9719 undo_redo->add_undo_method(environ_gi_button, "set_pressed", !environ_gi_button->is_pressed());
9720 undo_redo->add_do_method(this, "_preview_settings_changed");
9721 undo_redo->add_undo_method(this, "_preview_settings_changed");
9722 undo_redo->commit_action();
9723 }
9724
9725 void Node3DEditor::PreviewSunEnvPopup::shortcut_input(const Ref<InputEvent> &p_event) {
9726 const Ref<InputEventKey> k = p_event;
9727 if (k.is_valid() && k->is_pressed()) {
9728 bool handled = false;
9729
9730 if (ED_IS_SHORTCUT("ui_undo", p_event)) {
9731 EditorNode::get_singleton()->undo();
9732 handled = true;
9733 }
9734
9735 if (ED_IS_SHORTCUT("ui_redo", p_event)) {
9736 EditorNode::get_singleton()->redo();
9737 handled = true;
9738 }
9739
9740 if (handled) {
9741 set_input_as_handled();
9742 }
9743 }
9744 }
9745
9746 Node3DEditor::Node3DEditor() {
9747 gizmo.visible = true;
9748 gizmo.scale = 1.0;
9749
9750 viewport_environment.instantiate();
9751 VBoxContainer *vbc = this;
9752
9753 custom_camera = nullptr;
9754 ERR_FAIL_COND_MSG(singleton != nullptr, "A Node3DEditor singleton already exists.");
9755 singleton = this;
9756 editor_selection = EditorNode::get_singleton()->get_editor_selection();
9757 editor_selection->add_editor_plugin(this);
9758
9759 snap_enabled = false;
9760 snap_key_enabled = false;
9761 tool_mode = TOOL_MODE_TRANSFORM;
9762
9763 MarginContainer *toolbar_margin = memnew(MarginContainer);
9764 toolbar_margin->set_theme_type_variation("MainToolBarMargin");
9765 vbc->add_child(toolbar_margin);
9766
9767 // A fluid container for all toolbars.
9768 HFlowContainer *main_flow = memnew(HFlowContainer);
9769 toolbar_margin->add_child(main_flow);
9770
9771 // Main toolbars.
9772 HBoxContainer *main_menu_hbox = memnew(HBoxContainer);
9773 main_flow->add_child(main_menu_hbox);
9774
9775 String sct;
9776
9777 tool_button[TOOL_MODE_TRANSFORM] = memnew(Button);
9778 main_menu_hbox->add_child(tool_button[TOOL_MODE_TRANSFORM]);
9779 tool_button[TOOL_MODE_TRANSFORM]->set_toggle_mode(true);
9780 tool_button[TOOL_MODE_TRANSFORM]->set_theme_type_variation(SceneStringName(FlatButton));
9781 tool_button[TOOL_MODE_TRANSFORM]->set_pressed(true);
9782 tool_button[TOOL_MODE_TRANSFORM]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_TRANSFORM));
9783 tool_button[TOOL_MODE_TRANSFORM]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_transform", TTRC("Transform Mode"), Key::Q, true));
9784 tool_button[TOOL_MODE_TRANSFORM]->set_shortcut_context(this);
9785 tool_button[TOOL_MODE_TRANSFORM]->set_accessibility_name(TTRC("Transform Mode"));
9786
9787 tool_button[TOOL_MODE_MOVE] = memnew(Button);
9788 main_menu_hbox->add_child(tool_button[TOOL_MODE_MOVE]);
9789 tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
9790 tool_button[TOOL_MODE_MOVE]->set_tooltip_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
9791 tool_button[TOOL_MODE_MOVE]->set_theme_type_variation(SceneStringName(FlatButton));
9792
9793 tool_button[TOOL_MODE_MOVE]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_MOVE));
9794 tool_button[TOOL_MODE_MOVE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_move", TTRC("Move Mode"), Key::W, true));
9795 tool_button[TOOL_MODE_MOVE]->set_shortcut_context(this);
9796 tool_button[TOOL_MODE_MOVE]->set_accessibility_name(TTRC("Move Mode"));
9797
9798 tool_button[TOOL_MODE_ROTATE] = memnew(Button);
9799 main_menu_hbox->add_child(tool_button[TOOL_MODE_ROTATE]);
9800 tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
9801 tool_button[TOOL_MODE_ROTATE]->set_tooltip_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
9802 tool_button[TOOL_MODE_ROTATE]->set_theme_type_variation(SceneStringName(FlatButton));
9803 tool_button[TOOL_MODE_ROTATE]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_ROTATE));
9804 tool_button[TOOL_MODE_ROTATE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_rotate", TTRC("Rotate Mode"), Key::E, true));
9805 tool_button[TOOL_MODE_ROTATE]->set_shortcut_context(this);
9806 tool_button[TOOL_MODE_ROTATE]->set_accessibility_name(TTRC("Rotate Mode"));
9807
9808 tool_button[TOOL_MODE_SCALE] = memnew(Button);
9809 main_menu_hbox->add_child(tool_button[TOOL_MODE_SCALE]);
9810 tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
9811 tool_button[TOOL_MODE_SCALE]->set_tooltip_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
9812 tool_button[TOOL_MODE_SCALE]->set_theme_type_variation(SceneStringName(FlatButton));
9813 tool_button[TOOL_MODE_SCALE]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_SCALE));
9814 tool_button[TOOL_MODE_SCALE]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_scale", TTRC("Scale Mode"), Key::R, true));
9815 tool_button[TOOL_MODE_SCALE]->set_shortcut_context(this);
9816 tool_button[TOOL_MODE_SCALE]->set_accessibility_name(TTRC("Scale Mode"));
9817
9818 tool_button[TOOL_MODE_SELECT] = memnew(Button);
9819 main_menu_hbox->add_child(tool_button[TOOL_MODE_SELECT]);
9820 tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
9821 tool_button[TOOL_MODE_SELECT]->set_tooltip_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
9822 tool_button[TOOL_MODE_SELECT]->set_theme_type_variation(SceneStringName(FlatButton));
9823 tool_button[TOOL_MODE_SELECT]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_SELECT));
9824 tool_button[TOOL_MODE_SELECT]->set_shortcut(ED_SHORTCUT("spatial_editor/tool_select", TTRC("Select Mode"), Key::V, true));
9825 tool_button[TOOL_MODE_SELECT]->set_shortcut_context(this);
9826 tool_button[TOOL_MODE_SELECT]->set_accessibility_name(TTRC("Select Mode"));
9827
9828 main_menu_hbox->add_child(memnew(VSeparator));
9829
9830 tool_button[TOOL_MODE_LIST_SELECT] = memnew(Button);
9831 main_menu_hbox->add_child(tool_button[TOOL_MODE_LIST_SELECT]);
9832 tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
9833 tool_button[TOOL_MODE_LIST_SELECT]->set_theme_type_variation(SceneStringName(FlatButton));
9834 tool_button[TOOL_MODE_LIST_SELECT]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_TOOL_LIST_SELECT));
9835 tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip_text(TTRC("Show list of selectable nodes at position clicked."));
9836
9837 tool_button[TOOL_LOCK_SELECTED] = memnew(Button);
9838 main_menu_hbox->add_child(tool_button[TOOL_LOCK_SELECTED]);
9839 tool_button[TOOL_LOCK_SELECTED]->set_theme_type_variation(SceneStringName(FlatButton));
9840 tool_button[TOOL_LOCK_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_LOCK_SELECTED));
9841 tool_button[TOOL_LOCK_SELECTED]->set_tooltip_text(TTRC("Lock selected node, preventing selection and movement."));
9842 // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
9843 tool_button[TOOL_LOCK_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/lock_selected_nodes"));
9844 tool_button[TOOL_LOCK_SELECTED]->set_accessibility_name(TTRC("Lock"));
9845
9846 tool_button[TOOL_UNLOCK_SELECTED] = memnew(Button);
9847 main_menu_hbox->add_child(tool_button[TOOL_UNLOCK_SELECTED]);
9848 tool_button[TOOL_UNLOCK_SELECTED]->set_theme_type_variation(SceneStringName(FlatButton));
9849 tool_button[TOOL_UNLOCK_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_UNLOCK_SELECTED));
9850 tool_button[TOOL_UNLOCK_SELECTED]->set_tooltip_text(TTRC("Unlock selected node, allowing selection and movement."));
9851 // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
9852 tool_button[TOOL_UNLOCK_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/unlock_selected_nodes"));
9853 tool_button[TOOL_UNLOCK_SELECTED]->set_accessibility_name(TTRC("Unlock"));
9854
9855 tool_button[TOOL_GROUP_SELECTED] = memnew(Button);
9856 main_menu_hbox->add_child(tool_button[TOOL_GROUP_SELECTED]);
9857 tool_button[TOOL_GROUP_SELECTED]->set_theme_type_variation(SceneStringName(FlatButton));
9858 tool_button[TOOL_GROUP_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_GROUP_SELECTED));
9859 tool_button[TOOL_GROUP_SELECTED]->set_tooltip_text(TTRC("Groups the selected node with its children. This selects the parent when any child node is clicked in 2D and 3D view."));
9860 // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
9861 tool_button[TOOL_GROUP_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/group_selected_nodes"));
9862 tool_button[TOOL_GROUP_SELECTED]->set_accessibility_name(TTRC("Group"));
9863
9864 tool_button[TOOL_UNGROUP_SELECTED] = memnew(Button);
9865 main_menu_hbox->add_child(tool_button[TOOL_UNGROUP_SELECTED]);
9866 tool_button[TOOL_UNGROUP_SELECTED]->set_theme_type_variation(SceneStringName(FlatButton));
9867 tool_button[TOOL_UNGROUP_SELECTED]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_UNGROUP_SELECTED));
9868 tool_button[TOOL_UNGROUP_SELECTED]->set_tooltip_text(TTRC("Ungroups the selected node from its children. Child nodes will be individual items in 2D and 3D view."));
9869 // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
9870 tool_button[TOOL_UNGROUP_SELECTED]->set_shortcut(ED_GET_SHORTCUT("editor/ungroup_selected_nodes"));
9871 tool_button[TOOL_UNGROUP_SELECTED]->set_accessibility_name(TTRC("Ungroup"));
9872
9873 tool_button[TOOL_RULER] = memnew(Button);
9874 main_menu_hbox->add_child(tool_button[TOOL_RULER]);
9875 tool_button[TOOL_RULER]->set_toggle_mode(true);
9876 tool_button[TOOL_RULER]->set_theme_type_variation("FlatButton");
9877 tool_button[TOOL_RULER]->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed).bind(MENU_RULER));
9878 tool_button[TOOL_RULER]->set_tooltip_text(TTRC("LMB+Drag: Measure the distance between two points in 3D space."));
9879 // Define the shortcut globally (without a context) so that it works if the Scene tree dock is currently focused.
9880 tool_button[TOOL_RULER]->set_shortcut(ED_SHORTCUT("spatial_editor/measure", TTRC("Ruler Mode"), Key::M));
9881 tool_button[TOOL_RULER]->set_accessibility_name(TTRC("Ruler Mode"));
9882
9883 main_menu_hbox->add_child(memnew(VSeparator));
9884
9885 tool_option_button[TOOL_OPT_LOCAL_COORDS] = memnew(Button);
9886 main_menu_hbox->add_child(tool_option_button[TOOL_OPT_LOCAL_COORDS]);
9887 tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_toggle_mode(true);
9888 tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_theme_type_variation(SceneStringName(FlatButton));
9889 tool_option_button[TOOL_OPT_LOCAL_COORDS]->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_LOCAL_COORDS));
9890 tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut(ED_SHORTCUT("spatial_editor/local_coords", TTRC("Use Local Space"), Key::T));
9891 tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_shortcut_context(this);
9892 tool_option_button[TOOL_OPT_LOCAL_COORDS]->set_accessibility_name(TTRC("Use Local Space"));
9893
9894 tool_option_button[TOOL_OPT_USE_SNAP] = memnew(Button);
9895 main_menu_hbox->add_child(tool_option_button[TOOL_OPT_USE_SNAP]);
9896 tool_option_button[TOOL_OPT_USE_SNAP]->set_toggle_mode(true);
9897 tool_option_button[TOOL_OPT_USE_SNAP]->set_theme_type_variation(SceneStringName(FlatButton));
9898 tool_option_button[TOOL_OPT_USE_SNAP]->connect(SceneStringName(toggled), callable_mp(this, &Node3DEditor::_menu_item_toggled).bind(MENU_TOOL_USE_SNAP));
9899 tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut(ED_SHORTCUT("spatial_editor/snap", TTRC("Use Snap"), Key::Y));
9900 tool_option_button[TOOL_OPT_USE_SNAP]->set_shortcut_context(this);
9901 tool_option_button[TOOL_OPT_USE_SNAP]->set_accessibility_name(TTRC("Use Snap"));
9902
9903 main_menu_hbox->add_child(memnew(VSeparator));
9904 sun_button = memnew(Button);
9905 sun_button->set_tooltip_text(TTRC("Toggle preview sunlight.\nIf a DirectionalLight3D node is added to the scene, preview sunlight is disabled."));
9906 sun_button->set_toggle_mode(true);
9907 sun_button->set_accessibility_name(TTRC("Toggle preview sunlight."));
9908 sun_button->set_theme_type_variation(SceneStringName(FlatButton));
9909 sun_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_update_preview_environment), CONNECT_DEFERRED);
9910 // Preview is enabled by default - ensure this applies on editor startup when there is no state yet.
9911 sun_button->set_pressed(true);
9912
9913 main_menu_hbox->add_child(sun_button);
9914
9915 environ_button = memnew(Button);
9916 environ_button->set_tooltip_text(TTRC("Toggle preview environment.\nIf a WorldEnvironment node is added to the scene, preview environment is disabled."));
9917 environ_button->set_toggle_mode(true);
9918 environ_button->set_accessibility_name(TTRC("Toggle preview environment."));
9919 environ_button->set_theme_type_variation(SceneStringName(FlatButton));
9920 environ_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_update_preview_environment), CONNECT_DEFERRED);
9921 // Preview is enabled by default - ensure this applies on editor startup when there is no state yet.
9922 environ_button->set_pressed(true);
9923
9924 main_menu_hbox->add_child(environ_button);
9925
9926 sun_environ_settings = memnew(Button);
9927 sun_environ_settings->set_tooltip_text(TTRC("Edit Sun and Environment settings."));
9928 sun_environ_settings->set_theme_type_variation(SceneStringName(FlatButton));
9929 sun_environ_settings->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_sun_environ_settings_pressed));
9930
9931 main_menu_hbox->add_child(sun_environ_settings);
9932
9933 main_menu_hbox->add_child(memnew(VSeparator));
9934
9935 // Drag and drop support;
9936 preview_node = memnew(Node3D);
9937 preview_bounds = AABB();
9938
9939 ED_SHORTCUT("spatial_editor/bottom_view", TTRC("Bottom View"), KeyModifierMask::ALT + Key::KP_7);
9940 ED_SHORTCUT("spatial_editor/top_view", TTRC("Top View"), Key::KP_7);
9941 ED_SHORTCUT("spatial_editor/rear_view", TTRC("Rear View"), KeyModifierMask::ALT + Key::KP_1);
9942 ED_SHORTCUT("spatial_editor/front_view", TTRC("Front View"), Key::KP_1);
9943 ED_SHORTCUT("spatial_editor/left_view", TTRC("Left View"), KeyModifierMask::ALT + Key::KP_3);
9944 ED_SHORTCUT("spatial_editor/right_view", TTRC("Right View"), Key::KP_3);
9945 ED_SHORTCUT("spatial_editor/orbit_view_down", TTRC("Orbit View Down"), Key::KP_2);
9946 ED_SHORTCUT("spatial_editor/orbit_view_left", TTRC("Orbit View Left"), Key::KP_4);
9947 ED_SHORTCUT("spatial_editor/orbit_view_right", TTRC("Orbit View Right"), Key::KP_6);
9948 ED_SHORTCUT("spatial_editor/orbit_view_up", TTRC("Orbit View Up"), Key::KP_8);
9949 ED_SHORTCUT("spatial_editor/orbit_view_180", TTRC("Orbit View 180"), Key::KP_9);
9950 ED_SHORTCUT("spatial_editor/switch_perspective_orthogonal", TTRC("Switch Perspective/Orthogonal View"), Key::KP_5);
9951 ED_SHORTCUT("spatial_editor/insert_anim_key", TTRC("Insert Animation Key"), Key::K);
9952 ED_SHORTCUT("spatial_editor/focus_origin", TTRC("Focus Origin"), Key::O);
9953 ED_SHORTCUT("spatial_editor/focus_selection", TTRC("Focus Selection"), Key::F);
9954 ED_SHORTCUT_ARRAY("spatial_editor/align_transform_with_view", TTRC("Align Transform with View"),
9955 { int32_t(KeyModifierMask::ALT | KeyModifierMask::CTRL | Key::KP_0),
9956 int32_t(KeyModifierMask::ALT | KeyModifierMask::CTRL | Key::M),
9957 int32_t(KeyModifierMask::ALT | KeyModifierMask::CTRL | Key::G) });
9958 ED_SHORTCUT_OVERRIDE_ARRAY("spatial_editor/align_transform_with_view", "macos",
9959 { int32_t(KeyModifierMask::ALT | KeyModifierMask::META | Key::KP_0),
9960 int32_t(KeyModifierMask::ALT | KeyModifierMask::META | Key::G) });
9961 ED_SHORTCUT("spatial_editor/align_rotation_with_view", TTRC("Align Rotation with View"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::F);
9962 ED_SHORTCUT("spatial_editor/freelook_toggle", TTRC("Toggle Freelook"), KeyModifierMask::SHIFT + Key::F);
9963 ED_SHORTCUT("spatial_editor/decrease_fov", TTRC("Decrease Field of View"), KeyModifierMask::CMD_OR_CTRL + Key::EQUAL); // Usually direct access key for `KEY_PLUS`.
9964 ED_SHORTCUT("spatial_editor/increase_fov", TTRC("Increase Field of View"), KeyModifierMask::CMD_OR_CTRL + Key::MINUS);
9965 ED_SHORTCUT("spatial_editor/reset_fov", TTRC("Reset Field of View to Default"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_0);
9966
9967 PopupMenu *p;
9968
9969 transform_menu = memnew(MenuButton);
9970 transform_menu->set_flat(false);
9971 transform_menu->set_theme_type_variation("FlatMenuButton");
9972 transform_menu->set_text(TTRC("Transform"));
9973 transform_menu->set_switch_on_hover(true);
9974 transform_menu->set_shortcut_context(this);
9975 main_menu_hbox->add_child(transform_menu);
9976
9977 p = transform_menu->get_popup();
9978 p->add_shortcut(ED_SHORTCUT("spatial_editor/snap_to_floor", TTRC("Snap Object to Floor"), Key::PAGEDOWN), MENU_SNAP_TO_FLOOR);
9979 p->add_shortcut(ED_SHORTCUT("spatial_editor/transform_dialog", TTRC("Transform Dialog...")), MENU_TRANSFORM_DIALOG);
9980
9981 p->add_separator();
9982 p->add_shortcut(ED_SHORTCUT("spatial_editor/configure_snap", TTRC("Configure Snap...")), MENU_TRANSFORM_CONFIGURE_SNAP);
9983
9984 p->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed));
9985
9986 view_layout_menu = memnew(MenuButton);
9987 view_layout_menu->set_flat(false);
9988 view_layout_menu->set_theme_type_variation("FlatMenuButton");
9989 // TRANSLATORS: Noun, name of the 2D/3D View menus.
9990 view_layout_menu->set_text(TTRC("View"));
9991 view_layout_menu->set_switch_on_hover(true);
9992 view_layout_menu->set_shortcut_context(this);
9993 main_menu_hbox->add_child(view_layout_menu);
9994
9995 main_menu_hbox->add_child(memnew(VSeparator));
9996
9997 context_toolbar_panel = memnew(PanelContainer);
9998 context_toolbar_hbox = memnew(HBoxContainer);
9999 context_toolbar_panel->add_child(context_toolbar_hbox);
10000 main_flow->add_child(context_toolbar_panel);
10001
10002 // Get the view menu popup and have it stay open when a checkable item is selected
10003 p = view_layout_menu->get_popup();
10004 p->set_hide_on_checkable_item_selection(false);
10005
10006 accept = memnew(AcceptDialog);
10007 EditorNode::get_singleton()->get_gui_base()->add_child(accept);
10008
10009 p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/1_viewport", TTRC("1 Viewport"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_1, true), MENU_VIEW_USE_1_VIEWPORT);
10010 p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports", TTRC("2 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_2, true), MENU_VIEW_USE_2_VIEWPORTS);
10011 p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/2_viewports_alt", TTRC("2 Viewports (Alt)"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::KEY_2, true), MENU_VIEW_USE_2_VIEWPORTS_ALT);
10012 p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports", TTRC("3 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_3, true), MENU_VIEW_USE_3_VIEWPORTS);
10013 p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/3_viewports_alt", TTRC("3 Viewports (Alt)"), KeyModifierMask::ALT + KeyModifierMask::CMD_OR_CTRL + Key::KEY_3, true), MENU_VIEW_USE_3_VIEWPORTS_ALT);
10014 p->add_radio_check_shortcut(ED_SHORTCUT("spatial_editor/4_viewports", TTRC("4 Viewports"), KeyModifierMask::CMD_OR_CTRL + Key::KEY_4, true), MENU_VIEW_USE_4_VIEWPORTS);
10015 p->add_separator();
10016
10017 gizmos_menu = memnew(PopupMenu);
10018 gizmos_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
10019 gizmos_menu->set_hide_on_checkable_item_selection(false);
10020 p->add_submenu_node_item(TTRC("Gizmos"), gizmos_menu);
10021 gizmos_menu->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditor::_menu_gizmo_toggled));
10022
10023 p->add_separator();
10024 p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_origin", TTRC("View Origin")), MENU_VIEW_ORIGIN);
10025 p->add_check_shortcut(ED_SHORTCUT("spatial_editor/view_grid", TTRC("View Grid"), Key::NUMBERSIGN), MENU_VIEW_GRID);
10026
10027 p->add_separator();
10028 p->add_submenu_node_item(TTRC("Preview Translation"), memnew(EditorTranslationPreviewMenu));
10029
10030 p->add_separator();
10031 p->add_shortcut(ED_SHORTCUT("spatial_editor/settings", TTRC("Settings...")), MENU_VIEW_CAMERA_SETTINGS);
10032
10033 p->set_item_checked(p->get_item_index(MENU_VIEW_ORIGIN), true);
10034 p->set_item_checked(p->get_item_index(MENU_VIEW_GRID), true);
10035
10036 p->connect(SceneStringName(id_pressed), callable_mp(this, &Node3DEditor::_menu_item_pressed));
10037
10038 /* REST OF MENU */
10039
10040 left_panel_split = memnew(HSplitContainer);
10041 left_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
10042 vbc->add_child(left_panel_split);
10043
10044 right_panel_split = memnew(HSplitContainer);
10045 right_panel_split->set_v_size_flags(SIZE_EXPAND_FILL);
10046 left_panel_split->add_child(right_panel_split);
10047
10048 shader_split = memnew(VSplitContainer);
10049 shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
10050 right_panel_split->add_child(shader_split);
10051 viewport_base = memnew(Node3DEditorViewportContainer);
10052 shader_split->add_child(viewport_base);
10053 viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
10054 for (uint32_t i = 0; i < VIEWPORTS_COUNT; i++) {
10055 viewports[i] = memnew(Node3DEditorViewport(this, i));
10056 viewports[i]->connect("toggle_maximize_view", callable_mp(this, &Node3DEditor::_toggle_maximize_view));
10057 viewports[i]->connect("clicked", callable_mp(this, &Node3DEditor::_viewport_clicked).bind(i));
10058 viewports[i]->assign_pending_data_pointers(preview_node, &preview_bounds, accept);
10059 viewport_base->add_child(viewports[i]);
10060 }
10061
10062 /* SNAP DIALOG */
10063
10064 snap_dialog = memnew(ConfirmationDialog);
10065 snap_dialog->set_title(TTRC("Snap Settings"));
10066 add_child(snap_dialog);
10067 snap_dialog->connect(SceneStringName(confirmed), callable_mp(this, &Node3DEditor::_snap_changed));
10068 snap_dialog->get_cancel_button()->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_snap_update));
10069
10070 VBoxContainer *snap_dialog_vbc = memnew(VBoxContainer);
10071 snap_dialog->add_child(snap_dialog_vbc);
10072
10073 snap_translate = memnew(EditorSpinSlider);
10074 snap_translate->set_min(0.0);
10075 snap_translate->set_step(0.001);
10076 snap_translate->set_max(10.0);
10077 snap_translate->set_suffix("m");
10078 snap_translate->set_allow_greater(true);
10079 snap_translate->set_accessibility_name(TTRC("Translate Snap"));
10080 snap_dialog_vbc->add_margin_child(TTR("Translate Snap:"), snap_translate);
10081
10082 snap_rotate = memnew(EditorSpinSlider);
10083 snap_rotate->set_min(0.0);
10084 snap_rotate->set_step(0.1);
10085 snap_rotate->set_max(360);
10086 snap_rotate->set_suffix(U"°");
10087 snap_rotate->set_accessibility_name(TTRC("Rotate Snap"));
10088 snap_dialog_vbc->add_margin_child(TTR("Rotate Snap:"), snap_rotate);
10089
10090 snap_scale = memnew(EditorSpinSlider);
10091 snap_scale->set_min(0.0);
10092 snap_scale->set_step(1.0);
10093 snap_scale->set_max(100);
10094 snap_scale->set_suffix("%");
10095 snap_scale->set_accessibility_name(TTRC("Scale Snap"));
10096 snap_dialog_vbc->add_margin_child(TTR("Scale Snap:"), snap_scale);
10097
10098 /* SETTINGS DIALOG */
10099
10100 settings_dialog = memnew(ConfirmationDialog);
10101 settings_dialog->set_title(TTRC("Viewport Settings"));
10102 add_child(settings_dialog);
10103 settings_vbc = memnew(VBoxContainer);
10104 settings_vbc->set_custom_minimum_size(Size2(200, 0) * EDSCALE);
10105 settings_dialog->add_child(settings_vbc);
10106
10107 settings_fov = memnew(SpinBox);
10108 settings_fov->set_max(MAX_FOV);
10109 settings_fov->set_min(MIN_FOV);
10110 settings_fov->set_step(0.1);
10111 settings_fov->set_value(EDITOR_GET("editors/3d/default_fov"));
10112 settings_fov->set_select_all_on_focus(true);
10113 settings_fov->set_tooltip_text(TTRC("FOV is defined as a vertical value, as the editor camera always uses the Keep Height aspect mode."));
10114 settings_fov->set_accessibility_name(TTRC("Perspective VFOV (deg.):"));
10115 settings_vbc->add_margin_child(TTRC("Perspective VFOV (deg.):"), settings_fov);
10116
10117 settings_znear = memnew(SpinBox);
10118 settings_znear->set_max(MAX_Z);
10119 settings_znear->set_min(MIN_Z);
10120 settings_znear->set_step(0.01);
10121 settings_znear->set_accessibility_name(TTRC("View Z-Near:"));
10122 settings_znear->set_value(EDITOR_GET("editors/3d/default_z_near"));
10123 settings_znear->set_select_all_on_focus(true);
10124 settings_vbc->add_margin_child(TTRC("View Z-Near:"), settings_znear);
10125
10126 settings_zfar = memnew(SpinBox);
10127 settings_zfar->set_max(MAX_Z);
10128 settings_zfar->set_min(MIN_Z);
10129 settings_zfar->set_step(0.1);
10130 settings_zfar->set_accessibility_name(TTRC("View Z-Far:"));
10131 settings_zfar->set_value(EDITOR_GET("editors/3d/default_z_far"));
10132 settings_zfar->set_select_all_on_focus(true);
10133 settings_vbc->add_margin_child(TTRC("View Z-Far:"), settings_zfar);
10134
10135 for (uint32_t i = 0; i < VIEWPORTS_COUNT; ++i) {
10136 settings_dialog->connect(SceneStringName(confirmed), callable_mp(viewports[i], &Node3DEditorViewport::_view_settings_confirmed).bind(0.0));
10137 }
10138
10139 /* XFORM DIALOG */
10140
10141 xform_dialog = memnew(ConfirmationDialog);
10142 xform_dialog->set_title(TTRC("Transform Change"));
10143 add_child(xform_dialog);
10144
10145 VBoxContainer *xform_vbc = memnew(VBoxContainer);
10146 xform_dialog->add_child(xform_vbc);
10147
10148 HBoxContainer *translate_hb = memnew(HBoxContainer);
10149 xform_vbc->add_margin_child(TTRC("Translate:"), translate_hb);
10150 HBoxContainer *rotate_hb = memnew(HBoxContainer);
10151 xform_vbc->add_margin_child(TTRC("Rotate (deg.):"), rotate_hb);
10152 HBoxContainer *scale_hb = memnew(HBoxContainer);
10153 xform_vbc->add_margin_child(TTRC("Scale (ratio):"), scale_hb);
10154
10155 for (int i = 0; i < 3; i++) {
10156 xform_translate[i] = memnew(LineEdit);
10157 xform_translate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
10158 xform_translate[i]->set_select_all_on_focus(true);
10159 translate_hb->add_child(xform_translate[i]);
10160
10161 xform_rotate[i] = memnew(LineEdit);
10162 xform_rotate[i]->set_h_size_flags(SIZE_EXPAND_FILL);
10163 xform_rotate[i]->set_select_all_on_focus(true);
10164 rotate_hb->add_child(xform_rotate[i]);
10165
10166 xform_scale[i] = memnew(LineEdit);
10167 xform_scale[i]->set_h_size_flags(SIZE_EXPAND_FILL);
10168 xform_scale[i]->set_select_all_on_focus(true);
10169 scale_hb->add_child(xform_scale[i]);
10170 }
10171
10172 xform_type = memnew(OptionButton);
10173 xform_type->set_h_size_flags(SIZE_EXPAND_FILL);
10174 xform_type->set_accessibility_name(TTRC("Transform Type"));
10175 xform_type->add_item(TTRC("Pre"));
10176 xform_type->add_item(TTRC("Post"));
10177 xform_vbc->add_margin_child(TTRC("Transform Type"), xform_type);
10178
10179 xform_dialog->connect(SceneStringName(confirmed), callable_mp(this, &Node3DEditor::_xform_dialog_action));
10180
10181 selected = nullptr;
10182
10183 set_process_shortcut_input(true);
10184 add_to_group(SceneStringName(_spatial_editor_group));
10185
10186 current_hover_gizmo_handle = -1;
10187 current_hover_gizmo_handle_secondary = false;
10188 {
10189 // Sun/preview environment popup.
10190 sun_environ_popup = memnew(PreviewSunEnvPopup);
10191 add_child(sun_environ_popup);
10192
10193 HBoxContainer *sun_environ_hb = memnew(HBoxContainer);
10194
10195 sun_environ_popup->add_child(sun_environ_hb);
10196
10197 sun_vb = memnew(VBoxContainer);
10198 sun_environ_hb->add_child(sun_vb);
10199 sun_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0));
10200 sun_vb->hide();
10201
10202 sun_title = memnew(Label);
10203 sun_title->set_theme_type_variation("HeaderMedium");
10204 sun_vb->add_child(sun_title);
10205 sun_title->set_text(TTRC("Preview Sun"));
10206 sun_title->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
10207
10208 CenterContainer *sun_direction_center = memnew(CenterContainer);
10209 sun_direction = memnew(Control);
10210 sun_direction->set_custom_minimum_size(Size2(128, 128) * EDSCALE);
10211 sun_direction_center->add_child(sun_direction);
10212 sun_vb->add_margin_child(TTRC("Sun Direction"), sun_direction_center);
10213 sun_direction->connect(SceneStringName(gui_input), callable_mp(this, &Node3DEditor::_sun_direction_input));
10214 sun_direction->connect(SceneStringName(draw), callable_mp(this, &Node3DEditor::_sun_direction_draw));
10215 sun_direction->set_default_cursor_shape(CURSOR_MOVE);
10216
10217 sun_direction_shader.instantiate();
10218 sun_direction_shader->set_code(R"(
10219 // 3D editor Preview Sun direction shader.
10220
10221 shader_type canvas_item;
10222
10223 uniform vec3 sun_direction;
10224 uniform vec3 sun_color;
10225
10226 void fragment() {
10227 vec3 n;
10228 n.xy = UV * 2.0 - 1.0;
10229 n.z = sqrt(max(0.0, 1.0 - dot(n.xy, n.xy)));
10230 COLOR.rgb = dot(n, sun_direction) * sun_color;
10231 COLOR.a = 1.0 - smoothstep(0.99, 1.0, length(n.xy));
10232 }
10233 )");
10234 sun_direction_material.instantiate();
10235 sun_direction_material->set_shader(sun_direction_shader);
10236 sun_direction_material->set_shader_parameter("sun_direction", Vector3(0, 0, 1));
10237 sun_direction_material->set_shader_parameter("sun_color", Vector3(1, 1, 1));
10238 sun_direction->set_material(sun_direction_material);
10239
10240 HBoxContainer *sun_angle_hbox = memnew(HBoxContainer);
10241 sun_angle_hbox->set_h_size_flags(SIZE_EXPAND_FILL);
10242 VBoxContainer *sun_angle_altitude_vbox = memnew(VBoxContainer);
10243 sun_angle_altitude_vbox->set_h_size_flags(SIZE_EXPAND_FILL);
10244 Label *sun_angle_altitude_label = memnew(Label);
10245 sun_angle_altitude_label->set_text(TTRC("Angular Altitude"));
10246 sun_angle_altitude_vbox->add_child(sun_angle_altitude_label);
10247 sun_angle_altitude = memnew(EditorSpinSlider);
10248 sun_angle_altitude->set_suffix(U"\u00B0");
10249 sun_angle_altitude->set_max(90);
10250 sun_angle_altitude->set_min(-90);
10251 sun_angle_altitude->set_step(0.1);
10252 sun_angle_altitude->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_sun_direction_set_altitude));
10253 sun_angle_altitude_vbox->add_child(sun_angle_altitude);
10254 sun_angle_hbox->add_child(sun_angle_altitude_vbox);
10255 VBoxContainer *sun_angle_azimuth_vbox = memnew(VBoxContainer);
10256 sun_angle_azimuth_vbox->set_h_size_flags(SIZE_EXPAND_FILL);
10257 sun_angle_azimuth_vbox->set_custom_minimum_size(Vector2(100, 0));
10258 Label *sun_angle_azimuth_label = memnew(Label);
10259 sun_angle_azimuth_label->set_text(TTRC("Azimuth"));
10260 sun_angle_azimuth_vbox->add_child(sun_angle_azimuth_label);
10261 sun_angle_azimuth = memnew(EditorSpinSlider);
10262 sun_angle_azimuth->set_suffix(U"\u00B0");
10263 sun_angle_azimuth->set_max(180);
10264 sun_angle_azimuth->set_min(-180);
10265 sun_angle_azimuth->set_step(0.1);
10266 sun_angle_azimuth->set_allow_greater(true);
10267 sun_angle_azimuth->set_allow_lesser(true);
10268 sun_angle_azimuth->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_sun_direction_set_azimuth));
10269 sun_angle_azimuth_vbox->add_child(sun_angle_azimuth);
10270 sun_angle_hbox->add_child(sun_angle_azimuth_vbox);
10271 sun_angle_hbox->add_theme_constant_override("separation", 10);
10272 sun_vb->add_child(sun_angle_hbox);
10273
10274 sun_color = memnew(ColorPickerButton);
10275 sun_color->set_edit_alpha(false);
10276 sun_vb->add_margin_child(TTRC("Sun Color"), sun_color);
10277 sun_color->connect("color_changed", callable_mp(this, &Node3DEditor::_sun_set_color));
10278 sun_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(sun_color->get_picker()));
10279
10280 sun_energy = memnew(EditorSpinSlider);
10281 sun_energy->set_max(64.0);
10282 sun_energy->set_min(0);
10283 sun_energy->set_step(0.05);
10284 sun_vb->add_margin_child(TTRC("Sun Energy"), sun_energy);
10285 sun_energy->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_sun_set_energy));
10286
10287 sun_shadow_max_distance = memnew(EditorSpinSlider);
10288 sun_vb->add_margin_child(TTRC("Shadow Max Distance"), sun_shadow_max_distance);
10289 sun_shadow_max_distance->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_sun_set_shadow_max_distance));
10290 sun_shadow_max_distance->set_min(1);
10291 sun_shadow_max_distance->set_max(4096);
10292
10293 sun_add_to_scene = memnew(Button);
10294 sun_add_to_scene->set_text(TTRC("Add Sun to Scene"));
10295 sun_add_to_scene->set_tooltip_text(TTRC("Adds a DirectionalLight3D node matching the preview sun settings to the current scene.\nHold Shift while clicking to also add the preview environment to the current scene."));
10296 sun_add_to_scene->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_add_sun_to_scene).bind(false));
10297 sun_vb->add_spacer();
10298 sun_vb->add_child(sun_add_to_scene);
10299
10300 sun_state = memnew(Label);
10301 sun_environ_hb->add_child(sun_state);
10302 sun_state->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
10303 sun_state->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
10304 sun_state->set_h_size_flags(SIZE_EXPAND_FILL);
10305
10306 VSeparator *sc = memnew(VSeparator);
10307 sc->set_custom_minimum_size(Size2(10 * EDSCALE, 0));
10308 sc->set_v_size_flags(SIZE_EXPAND_FILL);
10309 sun_environ_hb->add_child(sc);
10310
10311 environ_vb = memnew(VBoxContainer);
10312 sun_environ_hb->add_child(environ_vb);
10313 environ_vb->set_custom_minimum_size(Size2(200 * EDSCALE, 0));
10314 environ_vb->hide();
10315
10316 environ_title = memnew(Label);
10317 environ_title->set_theme_type_variation("HeaderMedium");
10318
10319 environ_vb->add_child(environ_title);
10320 environ_title->set_text(TTRC("Preview Environment"));
10321 environ_title->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
10322
10323 environ_sky_color = memnew(ColorPickerButton);
10324 environ_sky_color->set_edit_alpha(false);
10325 environ_sky_color->connect("color_changed", callable_mp(this, &Node3DEditor::_environ_set_sky_color));
10326 environ_sky_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(environ_sky_color->get_picker()));
10327 environ_vb->add_margin_child(TTRC("Sky Color"), environ_sky_color);
10328 environ_ground_color = memnew(ColorPickerButton);
10329 environ_ground_color->connect("color_changed", callable_mp(this, &Node3DEditor::_environ_set_ground_color));
10330 environ_ground_color->set_edit_alpha(false);
10331 environ_ground_color->get_popup()->connect("about_to_popup", callable_mp(EditorNode::get_singleton(), &EditorNode::setup_color_picker).bind(environ_ground_color->get_picker()));
10332 environ_vb->add_margin_child(TTRC("Ground Color"), environ_ground_color);
10333 environ_energy = memnew(EditorSpinSlider);
10334 environ_energy->set_max(8.0);
10335 environ_energy->set_min(0);
10336 environ_energy->set_step(0.05);
10337 environ_energy->connect(SceneStringName(value_changed), callable_mp(this, &Node3DEditor::_environ_set_sky_energy));
10338 environ_vb->add_margin_child(TTRC("Sky Energy"), environ_energy);
10339 HBoxContainer *fx_vb = memnew(HBoxContainer);
10340 fx_vb->set_h_size_flags(SIZE_EXPAND_FILL);
10341
10342 environ_ao_button = memnew(Button);
10343 environ_ao_button->set_text(TTRC("AO"));
10344 environ_ao_button->set_h_size_flags(SIZE_EXPAND_FILL);
10345 environ_ao_button->set_toggle_mode(true);
10346 environ_ao_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_environ_set_ao), CONNECT_DEFERRED);
10347 fx_vb->add_child(environ_ao_button);
10348 environ_glow_button = memnew(Button);
10349 environ_glow_button->set_text(TTRC("Glow"));
10350 environ_glow_button->set_h_size_flags(SIZE_EXPAND_FILL);
10351 environ_glow_button->set_toggle_mode(true);
10352 environ_glow_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_environ_set_glow), CONNECT_DEFERRED);
10353 fx_vb->add_child(environ_glow_button);
10354 environ_tonemap_button = memnew(Button);
10355 environ_tonemap_button->set_text(TTRC("Tonemap"));
10356 environ_tonemap_button->set_h_size_flags(SIZE_EXPAND_FILL);
10357 environ_tonemap_button->set_toggle_mode(true);
10358 environ_tonemap_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_environ_set_tonemap), CONNECT_DEFERRED);
10359 fx_vb->add_child(environ_tonemap_button);
10360 environ_gi_button = memnew(Button);
10361 environ_gi_button->set_text(TTRC("GI"));
10362 environ_gi_button->set_h_size_flags(SIZE_EXPAND_FILL);
10363 environ_gi_button->set_toggle_mode(true);
10364 environ_gi_button->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_environ_set_gi), CONNECT_DEFERRED);
10365 fx_vb->add_child(environ_gi_button);
10366 environ_vb->add_margin_child(TTRC("Post Process"), fx_vb);
10367
10368 environ_add_to_scene = memnew(Button);
10369 environ_add_to_scene->set_text(TTRC("Add Environment to Scene"));
10370 environ_add_to_scene->set_tooltip_text(TTRC("Adds a WorldEnvironment node matching the preview environment settings to the current scene.\nHold Shift while clicking to also add the preview sun to the current scene."));
10371 environ_add_to_scene->connect(SceneStringName(pressed), callable_mp(this, &Node3DEditor::_add_environment_to_scene).bind(false));
10372 environ_vb->add_spacer();
10373 environ_vb->add_child(environ_add_to_scene);
10374
10375 environ_state = memnew(Label);
10376 sun_environ_hb->add_child(environ_state);
10377 environ_state->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
10378 environ_state->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
10379 environ_state->set_h_size_flags(SIZE_EXPAND_FILL);
10380
10381 preview_sun = memnew(DirectionalLight3D);
10382 preview_sun->set_shadow(true);
10383 preview_sun->set_shadow_mode(DirectionalLight3D::SHADOW_PARALLEL_4_SPLITS);
10384 preview_environment = memnew(WorldEnvironment);
10385 environment.instantiate();
10386 preview_environment->set_environment(environment);
10387 if (GLOBAL_GET("rendering/lights_and_shadows/use_physical_light_units")) {
10388 camera_attributes.instantiate();
10389 preview_environment->set_camera_attributes(camera_attributes);
10390 }
10391 Ref<Sky> sky;
10392 sky.instantiate();
10393 sky_material.instantiate();
10394 sky->set_material(sky_material);
10395 environment->set_sky(sky);
10396 environment->set_background(Environment::BG_SKY);
10397
10398 sun_environ_popup->set_process_shortcut_input(true);
10399
10400 _load_default_preview_settings();
10401 _preview_settings_changed();
10402 }
10403 clear(); // Make sure values are initialized. Will call _snap_update() for us.
10404 }
10405 Node3DEditor::~Node3DEditor() {
10406 singleton = nullptr;
10407 memdelete(preview_node);
10408 if (preview_sun_dangling && preview_sun) {
10409 memdelete(preview_sun);
10410 }
10411 if (preview_env_dangling && preview_environment) {
10412 memdelete(preview_environment);
10413 }
10414 }
10415
10416 void Node3DEditorPlugin::make_visible(bool p_visible) {
10417 if (p_visible) {
10418 spatial_editor->show();
10419 spatial_editor->set_process(true);
10420 spatial_editor->set_physics_process(true);
10421 spatial_editor->refresh_dirty_gizmos();
10422 } else {
10423 spatial_editor->hide();
10424 spatial_editor->set_process(false);
10425 spatial_editor->set_physics_process(false);
10426 }
10427 }
10428
10429 void Node3DEditorPlugin::edit(Object *p_object) {
10430 spatial_editor->edit(Object::cast_to<Node3D>(p_object));
10431 }
10432
10433 bool Node3DEditorPlugin::handles(Object *p_object) const {
10434 return p_object->is_class("Node3D");
10435 }
10436
10437 Dictionary Node3DEditorPlugin::get_state() const {
10438 return spatial_editor->get_state();
10439 }
10440
10441 void Node3DEditorPlugin::set_state(const Dictionary &p_state) {
10442 spatial_editor->set_state(p_state);
10443 }
10444
10445 Size2i Node3DEditor::get_camera_viewport_size(Camera3D *p_camera) {
10446 Viewport *viewport = p_camera->get_viewport();
10447
10448 Window *window = Object::cast_to<Window>(viewport);
10449 if (window) {
10450 return window->get_size();
10451 }
10452
10453 SubViewport *sub_viewport = Object::cast_to<SubViewport>(viewport);
10454 ERR_FAIL_NULL_V(sub_viewport, Size2i());
10455
10456 if (sub_viewport == EditorNode::get_singleton()->get_scene_root()) {
10457 return Size2(GLOBAL_GET("display/window/size/viewport_width"), GLOBAL_GET("display/window/size/viewport_height"));
10458 }
10459
10460 return sub_viewport->get_size();
10461 }
10462
10463 Vector3 Node3DEditor::snap_point(Vector3 p_target, Vector3 p_start) const {
10464 if (is_snap_enabled()) {
10465 real_t snap = get_translate_snap();
10466 p_target.snapf(snap);
10467 }
10468 return p_target;
10469 }
10470
10471 bool Node3DEditor::is_gizmo_visible() const {
10472 if (selected) {
10473 return gizmo.visible && selected->is_transform_gizmo_visible();
10474 }
10475 return gizmo.visible;
10476 }
10477
10478 real_t Node3DEditor::get_translate_snap() const {
10479 real_t snap_value = snap_translate_value;
10480 if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
10481 snap_value /= 10.0f;
10482 }
10483 return snap_value;
10484 }
10485
10486 real_t Node3DEditor::get_rotate_snap() const {
10487 real_t snap_value = snap_rotate_value;
10488 if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
10489 snap_value /= 3.0f;
10490 }
10491 return snap_value;
10492 }
10493
10494 real_t Node3DEditor::get_scale_snap() const {
10495 real_t snap_value = snap_scale_value;
10496 if (Input::get_singleton()->is_key_pressed(Key::SHIFT)) {
10497 snap_value /= 2.0f;
10498 }
10499 return snap_value;
10500 }
10501
10502 struct _GizmoPluginPriorityComparator {
10503 bool operator()(const Ref<EditorNode3DGizmoPlugin> &p_a, const Ref<EditorNode3DGizmoPlugin> &p_b) const {
10504 if (p_a->get_priority() == p_b->get_priority()) {
10505 return p_a->get_gizmo_name() < p_b->get_gizmo_name();
10506 }
10507 return p_a->get_priority() > p_b->get_priority();
10508 }
10509 };
10510
10511 struct _GizmoPluginNameComparator {
10512 bool operator()(const Ref<EditorNode3DGizmoPlugin> &p_a, const Ref<EditorNode3DGizmoPlugin> &p_b) const {
10513 return p_a->get_gizmo_name() < p_b->get_gizmo_name();
10514 }
10515 };
10516
10517 void Node3DEditor::add_gizmo_plugin(Ref<EditorNode3DGizmoPlugin> p_plugin) {
10518 ERR_FAIL_COND(p_plugin.is_null());
10519
10520 gizmo_plugins_by_priority.push_back(p_plugin);
10521 gizmo_plugins_by_priority.sort_custom<_GizmoPluginPriorityComparator>();
10522
10523 gizmo_plugins_by_name.push_back(p_plugin);
10524 gizmo_plugins_by_name.sort_custom<_GizmoPluginNameComparator>();
10525
10526 _update_gizmos_menu();
10527 }
10528
10529 void Node3DEditor::remove_gizmo_plugin(Ref<EditorNode3DGizmoPlugin> p_plugin) {
10530 gizmo_plugins_by_priority.erase(p_plugin);
10531 gizmo_plugins_by_name.erase(p_plugin);
10532 _update_gizmos_menu();
10533 }
10534
10535 DynamicBVH::ID Node3DEditor::insert_gizmo_bvh_node(Node3D *p_node, const AABB &p_aabb) {
10536 return gizmo_bvh.insert(p_aabb, p_node);
10537 }
10538
10539 void Node3DEditor::update_gizmo_bvh_node(DynamicBVH::ID p_id, const AABB &p_aabb) {
10540 gizmo_bvh.update(p_id, p_aabb);
10541 gizmo_bvh.optimize_incremental(1);
10542 }
10543
10544 void Node3DEditor::remove_gizmo_bvh_node(DynamicBVH::ID p_id) {
10545 gizmo_bvh.remove(p_id);
10546 }
10547
10548 Vector<Node3D *> Node3DEditor::gizmo_bvh_ray_query(const Vector3 &p_ray_start, const Vector3 &p_ray_end) {
10549 struct Result {
10550 Vector<Node3D *> nodes;
10551 bool operator()(void *p_data) {
10552 nodes.append((Node3D *)p_data);
10553 return false;
10554 }
10555 } result;
10556
10557 gizmo_bvh.ray_query(p_ray_start, p_ray_end, result);
10558
10559 return result.nodes;
10560 }
10561
10562 Vector<Node3D *> Node3DEditor::gizmo_bvh_frustum_query(const Vector<Plane> &p_frustum) {
10563 Vector<Vector3> points = Geometry3D::compute_convex_mesh_points(&p_frustum[0], p_frustum.size());
10564
10565 struct Result {
10566 Vector<Node3D *> nodes;
10567 bool operator()(void *p_data) {
10568 nodes.append((Node3D *)p_data);
10569 return false;
10570 }
10571 } result;
10572
10573 gizmo_bvh.convex_query(p_frustum.ptr(), p_frustum.size(), points.ptr(), points.size(), result);
10574
10575 return result.nodes;
10576 }
10577
10578 Node3DEditorPlugin::Node3DEditorPlugin() {
10579 spatial_editor = memnew(Node3DEditor);
10580 spatial_editor->set_v_size_flags(Control::SIZE_EXPAND_FILL);
10581 EditorNode::get_singleton()->get_editor_main_screen()->get_control()->add_child(spatial_editor);
10582
10583 spatial_editor->hide();
10584 }