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