forked from markaren/threepp
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathEditorApp.cpp
More file actions
4126 lines (3481 loc) · 167 KB
/
Copy pathEditorApp.cpp
File metadata and controls
4126 lines (3481 loc) · 167 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "EditorApp.hpp"
#include "EditorTheme.hpp"
#include "ExampleScenes.hpp"
#include "ImportFormats.hpp"
#include "PanelLayout.hpp"
#include "threepp/extras/editor/AnimationPlaySession.hpp"
#include "threepp/extras/editor/ConveyorConfig.hpp"
#include "threepp/extras/editor/SoundConfig.hpp"
#include "threepp/extras/editor/GeneratorConfig.hpp"
#include "threepp/extras/editor/MaterialTextureSlots.hpp"
#include "threepp/extras/editor/RobotConfig.hpp"
#include "threepp/extras/editor/ScriptConfig.hpp"
#include "threepp/extras/editor/ScriptWorkspace.hpp"
#include "threepp/extras/editor/SplatImportConfig.hpp"
#include "threepp/extras/editor/SplineConfig.hpp"
#include "threepp/extras/editor/ViewSpec.hpp"
#include "threepp/extras/imgui/ImguiContext.hpp"
#ifdef THREEPP_EDITOR_WITH_PYTHON
#include "ScriptHost.hpp"// runAuthoringSource, for the Generator's Regenerate
#endif
#include "threepp/objects/ObjectWithMorphTargetInfluences.hpp"
#ifdef THREEPP_WITH_AUDIO
#include "threepp/audio/Audio.hpp"
#include "threepp/extras/editor/AudioPlaySession.hpp"
#endif
#include "threepp/extras/editor/SensorPlaySession.hpp"
#ifdef THREEPP_EDITOR_WITH_PHYSX
#include "threepp/extras/editor/ConveyorPlaySession.hpp"
#include "threepp/extras/editor/PhysicsPlaySession.hpp"
#include "threepp/extras/editor/PhysxSensorPlaySession.hpp"
#endif
#include "threepp/canvas/Monitor.hpp"
#include "threepp/core/Clock.hpp"
#include "threepp/geometries/BoxGeometry.hpp"
#include "threepp/geometries/PlaneGeometry.hpp"
#include "threepp/helpers/AxesHelper.hpp"
#include "threepp/helpers/CameraHelper.hpp"
#include "threepp/helpers/GridHelper.hpp"
#include "threepp/lights/AmbientLight.hpp"
#include "threepp/lights/DirectionalLight.hpp"
#include "threepp/loaders/AssetSource.hpp"
#include "threepp/loaders/EXRLoader.hpp"
#include "threepp/loaders/ModelLoader.hpp"
#include "threepp/loaders/RGBELoader.hpp"
#include "threepp/loaders/SogLoader.hpp"
#include "threepp/loaders/SplatLoader.hpp"
#include "threepp/loaders/TextureLoader.hpp"
#include "threepp/loaders/URDFLoader.hpp"
#include "threepp/materials/MeshStandardMaterial.hpp"
#include "threepp/materials/interfaces.hpp"
#include "threepp/math/Box3.hpp"
#include "threepp/math/MathUtils.hpp"
#include "threepp/objects/LineSegments.hpp"
#include "threepp/objects/Mesh.hpp"
#include "threepp/objects/ObjectWithMaterials.hpp"
#include "threepp/objects/Points.hpp"
#include "threepp/objects/Robot.hpp"
#include "threepp/objects/SplatCloud.hpp"
#include "threepp/splats/SplatLod.hpp"
#include "threepp/renderers/RendererFactory.hpp"
#include "threepp/scenes/Scene.hpp"
#ifdef THREEPP_WITH_VULKAN
#include "threepp/renderers/VulkanRenderer.hpp"
#endif
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>// std::getenv (THREEPP_BENCH_VSYNC)
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
// GLFW's window-title setter. Declared rather than included: the GLFW headers
// are private to the threepp target, but the symbol is linked into it and the
// signature is a plain C entry point taking an opaque window handle.
extern "C" void glfwSetWindowTitle(void* window, const char* title);
using namespace threepp;
using namespace threepp::editor;
namespace {
constexpr int kDefaultWidth = 1600;
constexpr int kDefaultHeight = 900;
constexpr std::size_t kConsoleLimit = 400;
#ifdef THREEPP_EDITOR_WITH_PYTHON
// A key NAME (as a script writes it) -> ImGuiKey. The vocabulary is deliberately the one
// python/src/bind_render.cpp's keyFromName accepts, so a script that polls 'UP' or 'KP8'
// reads the same in the editor as it does against a Canvas in the wheel. The enums differ
// (ImGuiKey here, threepp::Key there), so this is a parallel mapping rather than shared
// code; keep the accepted spellings in step.
ImGuiKey imguiKeyFromName(std::string name) {
for (auto& ch : name) ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
if (name.size() == 1 && name[0] >= 'A' && name[0] <= 'Z') {
return static_cast<ImGuiKey>(ImGuiKey_A + (name[0] - 'A'));
}
if (name.size() == 1 && name[0] >= '0' && name[0] <= '9') {
return static_cast<ImGuiKey>(ImGuiKey_0 + (name[0] - '0'));
}
// Numpad: "KP8" / "NUM8" / "NUMPAD8" -> keypad 8, distinct from the top-row digit.
for (const std::string& prefix : {std::string("KP"), std::string("NUMPAD"), std::string("NUM")}) {
if (name.size() == prefix.size() + 1 && name.compare(0, prefix.size(), prefix) == 0 &&
name.back() >= '0' && name.back() <= '9') {
return static_cast<ImGuiKey>(ImGuiKey_Keypad0 + (name.back() - '0'));
}
}
if (name == "SPACE") return ImGuiKey_Space;
if (name == "UP") return ImGuiKey_UpArrow;
if (name == "DOWN") return ImGuiKey_DownArrow;
if (name == "LEFT") return ImGuiKey_LeftArrow;
if (name == "RIGHT") return ImGuiKey_RightArrow;
if (name == "ESCAPE" || name == "ESC") return ImGuiKey_Escape;
if (name == "ENTER") return ImGuiKey_Enter;
if (name == "TAB") return ImGuiKey_Tab;
if (name == "SHIFT") return ImGuiKey_LeftShift;
if (name == "CTRL" || name == "CONTROL") return ImGuiKey_LeftCtrl;
return ImGuiKey_None;
}
#endif
// Always names a backend. Handing createRenderer no preference makes it
// print a console menu and block on std::cin, which a windowed app must
// never do — it stalls the editor behind a prompt nobody sees and hangs
// any piped or scripted run.
GraphicsAPI requestedApi(bool vulkan) {
#ifdef THREEPP_WITH_VULKAN
if (vulkan) return GraphicsAPI::Vulkan;
#else
if (vulkan) {
std::cerr << "threepp editor: built without Vulkan support, using OpenGL\n";
}
#endif
return GraphicsAPI::OpenGL;
}
// Which way `object` is FACING, as an angle about world up: its forward axis
// projected onto the ground plane. False when there is nothing to project —
// a nose within a few degrees of straight up or down, where the projection
// is numerical noise and the caller must keep the heading it had, or a body
// tumbling through vertical whips the camera round with it.
//
// Forward is -Z. Not a convention picked for one scene: it is threepp's own,
// the direction lookAt() aims and the direction every camera in the engine
// looks, so an object modelled to face the way it moves faces -Z. Read off
// the WORLD quaternion, so a subject parented under something rotated heads
// where it actually points.
bool headingOf(Object3D& object, float& radians) {
Quaternion world;
object.getWorldQuaternion(world);
Vector3 forward(0.f, 0.f, -1.f);
forward.applyQuaternion(world);
// sin(4 degrees). Below it the ground-plane projection is shorter than
// the attitude noise of a hovering body.
constexpr float kFlat = 0.07f;
if (forward.x * forward.x + forward.z * forward.z < kFlat * kFlat) return false;
// Zero for an unrotated object, and +theta for a yaw of +theta about +Y,
// which is exactly what Vector3::applyAxisAngle(worldUp, theta) undoes.
radians = std::atan2(-forward.x, -forward.z);
return true;
}
// --bench turns vsync off, because a present-capped frame time measures the
// display rather than the renderer. THREEPP_BENCH_VSYNC=1 puts it back, for
// the one question the uncapped number cannot answer: does the editor AS
// SHIPPED hold the refresh rate.
bool benchWantsVsync(const EditorApp::Options& options) {
if (options.bench <= 0) return true;
const char* keep = std::getenv("THREEPP_BENCH_VSYNC");
return keep && *keep && *keep != '0';
}
bool isDescription(const std::filesystem::path& path) {
auto extension = path.extension().string();
std::transform(extension.begin(), extension.end(), extension.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return extension == ".urdf" || extension == ".xacro";
}
// What a queued file wants to be told before it can be expanded. Only a
// robot description is asked: scanArgs on a 200 MB .glb would parse the
// whole thing as XML, fail, and answer the same empty vector.
std::vector<xacro::ArgDecl> declaredXacroArgs(const std::filesystem::path& path) {
if (!isDescription(path)) return {};
return xacro::scanArgs(path);
}
// A SOG / SSOG scan: a directory of chunks, or the .zip / .sog archive of
// one. Decided by content, like the PLY path below it.
//
// It gets the SAME half-turn about X the .ply path applies, and the reason
// is worth writing down because the format documentation points the other
// way. SOG v2 declares itself right-handed with +Y up, which reads like a
// promise that no flip is needed — it is not. That line describes the
// CONTAINER's axis convention, not which way the scan inside it was
// reconstructed. splat-transform re-encodes an existing 3DGS .ply without
// reorienting it, and on the Sanctuaire scan the decoded means match that
// .ply's to 8e-13 with no negation on any axis. So a SOG made from a COLMAP
// capture is +Y DOWN exactly like its .ply, and skipping the flip lands the
// basilica on its roof. Measured, not reasoned: the first import without it
// came out upside down.
//
// A multi-level asset is read at level 0, its finest — "import my scan"
// means the scan, not a proxy — with the level recorded so a future
// serialization pass can reproduce the choice.
std::shared_ptr<Object3D> loadSplatSog(const std::filesystem::path& path, bool vulkanBackend) {
const auto info = SogLoader::describe(path);
// A multi-level asset imports for DYNAMIC LOD: every other level in one
// cloud (splats::loadSogWithLod says why every other), with the level
// table travelling on the cloud so the per-frame policy in render()
// finds it. A single-level asset imports exactly as before.
//
// VULKAN ONLY. The GL path ignores submission ranges, so a multi-level
// cloud there draws every resident level stacked — the scan two or
// three times over, fatter and slower, with no way to select. On a GL
// editor a multi-level asset imports at its finest level, exactly as it
// did before dynamic LOD existed. (The editor DEFAULTS to GL; --vulkan
// is the flag, and it is where all of the splat perf work lives.)
splats::SogLodResult loaded;
if (vulkanBackend) {
loaded = splats::loadSogWithLod(path);
} else {
loaded.data = SogLoader::load(path);
}
auto& data = loaded.data;
auto& lodTable = loaded.table;
editor::SplatImportConfig config;
const auto srcU8 = path.u8string();
config.source = std::string(srcU8.begin(), srcU8.end());
config.lod = info.lodLevels > 1 ? 0 : -1;
// The same cull the .ply path applies, and for the same reason: a scan
// is a scan whatever container it arrived in. NOT under dynamic LOD
// though: the cull reorders and removes splats, which would invalidate
// every offset in the level table. The outliers a coarse level carries
// are the price of the table staying true.
if (lodTable.empty()) {
config.culled = true;
config.removed = data.removeOutliers();
}
auto cloud = SplatCloud::create(std::move(data));
cloud->setLodTable(std::move(lodTable));
// On the NODE, not in the data, for the same reason the .ply path puts
// it there: which way is up belongs to the scene, and the gizmo can
// undo it.
cloud->rotation.x = math::PI;
config.flippedX = true;
config.write(*cloud);
return cloud;
}
// A .ply, decided by its header rather than its name. Runs on the import
// worker, so everything expensive here — the parse, the outlier cull, the
// covariance and data-texture build inside SplatCloud — is off the UI
// thread. Nothing touches GL: the cloud's DataTextures are plain CPU
// buffers until the renderer first draws them.
std::shared_ptr<Object3D> loadSplatPly(const std::filesystem::path& path) {
// isSplatPly answers false for a file it cannot OPEN, so keep
// "unreadable" and "not a splat" apart here — otherwise a filesystem
// problem (a path that did not survive an encoding trip, most of all)
// gets reported as a file-format verdict, which is exactly the wrong
// trail to send someone down.
if (std::ifstream probe(path, std::ios::binary); !probe) {
throw std::runtime_error("cannot open the file, so no header was read"
" - a path or permissions problem, not a format one");
}
if (!SplatLoader::isSplatPly(path)) {
// Not a splat scan, so it belongs to the mesh path — which is
// unchanged, and which is where it stops: threepp has no mesh PLY
// loader today, and ModelLoader refuses the extension. Saying so
// here beats letting "no importable content in the file" stand for
// both "your scan is malformed" and "we cannot read mesh PLYs".
ModelLoader loader;
if (auto group = loader.load(path)) return group;
throw std::runtime_error(
"no f_dc_0 property in the PLY header, so this is not a Gaussian splat scan"
" - and threepp has no mesh PLY loader");
}
auto data = SplatLoader::loadPly(path);
// The two defaults a user means by "import my scan", both of them the
// gaussian_splats example's, and both recorded so a future
// serialization pass can reproduce this import from the file alone.
editor::SplatImportConfig config;
// Stored as UTF-8; .string() narrows through the ANSI code page and
// would mangle the same paths the drop handler just went out of its
// way to decode correctly.
const auto srcU8 = path.u8string();
config.source = std::string(srcU8.begin(), srcU8.end());
// Photogrammetry output carries a long tail of enormous near-opaque
// splats that render as fog over the subject. The rule is
// percentile-based against the cloud's own distribution, so it is a
// no-op on a clean scan and carries no unit.
config.culled = true;
config.removed = data.removeOutliers();
auto cloud = SplatCloud::create(std::move(data));
// COLMAP — and the 3DGS pipelines built on it — put +Y down, so a scan
// arrives upside down in a +Y-up scene. The conventional half-turn
// about X is the fix, and it belongs on the NODE rather than in the
// data: which way is up is a property of the scene the cloud is being
// placed into, not of the file. The gizmo can undo it.
cloud->rotation.x = math::PI;
config.flippedX = true;
config.write(*cloud);
return cloud;
}
}// namespace
EditorApp::EditorApp(const Options& options)
: options_(options),
canvas_(Canvas::Parameters()
.title("threepp editor")
.size(kDefaultWidth, kDefaultHeight)
.antialiasing(4)
// A timed pass measures the RENDERER. With vsync on, the
// swapchain is FIFO and every frame time is quantized to
// the refresh interval, which measures the monitor.
.vsync(benchWantsVsync(options))
.exitOnKeyEscape(false)),
renderer_(createRenderer(canvas_, requestedApi(options.vulkan))),
camera_(55.f, canvas_.aspect(), 0.05f, 5000.f),
ortho_(-1.f, 1.f, 1.f, -1.f, 0.05f, 10000.f) {
contentScale_ = monitor::contentScale().first;
// The fonts already follow the window between monitors (ImguiContext has
// its own onMonitorChange subscription); this keeps the editor's layout
// math — panel widths, button sizes, marker pixels — on the same scale,
// so a HiDPI laptop screen and a 100% external monitor both look right.
canvas_.onMonitorChange([this](int idx) {
contentScale_ = monitor::contentScale(idx).first;
});
renderer_->shadowMap().enabled = true;
renderer_->shadowMap().type = ShadowMap::PFC;
renderer_->toneMapping = ToneMapping::ACESFilmic;
renderer_->toneMappingExposure = 1.0f;
#ifdef THREEPP_WITH_VULKAN
// The axis views are a 3D camera that happens to project in parallel, not a
// 2D overlay. Without this the Vulkan backend reads an OrthographicCamera as
// a HUD and draws the scene as flat unlit fills — no lights, no shadows, no
// fog — so Numpad 5 would change how the viewport SHADES, not just how it
// projects. Ignored by the OpenGL backend, which never had the ambiguity.
if (auto* vk = dynamic_cast<VulkanRenderer*>(renderer_.get())) {
vk->setOrthographicSceneRendering(true);
// The editor is an authoring tool running a deferred path-traced
// backend on whatever laptop it was opened on, and the shade is the
// frame's dominant cost — it scales with pixels. 0.8 is 64% of them for
// a difference TAA reconstructs most of the way back, which is the
// trade a viewport should default to; a final frame is what --screenshot
// and the Render scale slider are for. Deliberately editor-only: the
// renderer itself still defaults to 1.0 for every example and test.
vk->setRenderScale(0.8f);
}
#endif
// Arms the camera dock's exact-pixel path when (and only when) the backend
// can do it. On OpenGL this leaves the pane inert and the dock keeps its
// scissored second render.
dockPane_.attach(renderer_.get());
// After every renderer knob above: this is the baseline a document is
// opened against and saved as a difference from.
renderDefaults_ = RenderConfig::capture(*renderer_);
camera_.position.set(6, 5, 8);
// --- editor-only overlay ------------------------------------------------
// One node holds everything the editor draws but never saves. SceneDocument
// detaches it for every export, so no helper can leak into a document.
overlay_ = Group::create();
overlay_->name = "__editor_overlay";
document_.addEditorOnly(*overlay_);
grid_ = GridHelper::create(40, 40, 0x4a4a4a, 0x2c2c2c);
overlay_->add(grid_);
axes_ = AxesHelper::create(1.5f);
// Off until asked for: the grid already says where the ground is, and three
// coloured sticks at the origin are furniture in every scene that does not
// happen to be authored around it. View > Origin Axes switches them on.
axes_->visible = false;
overlay_->add(axes_);
markers_ = Group::create();
markers_->name = "__editor_markers";
overlay_->add(markers_);
splines_ = Group::create();
splines_->name = "__editor_splines";
overlay_->add(splines_);
conveyors_ = Group::create();
conveyors_->name = "__editor_conveyors";
overlay_->add(conveyors_);
// Editor-only like the overlay, but a SIBLING of it rather than a child: the
// overlay is hidden for the duration of every sensor scan (a depth camera
// pointed at the grid otherwise measures the grid), and a sensor must not be
// hidden from itself. See SensorPlaySession.
sensorRig_ = Group::create();
sensorRig_->name = "__editor_sensor_rig";
document_.addEditorOnly(*sensorRig_);
// Orbiting while dragging a handle fights the gizmo; and a drag is exactly
// the span an undo entry should cover.
gizmoDragHandler_ = [this](Event& event) {
const bool dragging = std::any_cast<bool>(event.target);
orbit_->enabled = !dragging;
auto* selected = selection_.get();
if (dragging) {
if (selected) {
gizmoBefore_ = SetTransformCommand::read(*selected);
gizmoDragging_ = true;
commands_.beginTransaction();
}
return;
}
if (gizmoDragging_ && selected) {
commands_.push(std::make_unique<SetTransformCommand>(
*selected, gizmoBefore_, SetTransformCommand::read(*selected),
gizmoMode_ == "translate" ? "Move" : (gizmoMode_ == "rotate" ? "Rotate" : "Scale")));
commands_.endTransaction();
document_.setDirty(true);
}
gizmoDragging_ = false;
};
// Builds orbit_ and gizmo_ against the perspective camera. Called again
// whenever the projection changes.
bindViewportControls();
orbit_->target.set(0, 0.5f, 0);
// --- ImGui --------------------------------------------------------------
ui_ = std::make_unique<ImguiFunctionalContext>(canvas_, *renderer_, [this] { drawUi(); });
ioCapture_.preventMouseEvent = [this] {
// The view gizmo draws on the background list, so ImGui's own capture
// knows nothing about it - while the pointer is on it, a drag must
// not orbit and a click must not pick.
return ImGui::GetIO().WantCaptureMouse || viewGizmoHovered_ || toolPaletteHovered_;
};
ioCapture_.preventScrollEvent = [] { return ImGui::GetIO().WantCaptureMouse; };
ioCapture_.preventKeyboardEvent = [] { return ImGui::GetIO().WantCaptureKeyboard; };
canvas_.setIOCapture(&ioCapture_);
canvas_.onWindowResize([this](WindowSize size) {
camera_.aspect = size.aspect();
camera_.updateProjectionMatrix();
// The ortho frustum keeps its height and re-derives its width, so a
// resize widens the view rather than rescaling what is in it.
setOrthoHeight((ortho_.top - ortho_.bottom) / std::max(ortho_.zoom, 1e-4f));
renderer_->setSize(size);
});
canvas_.onDrop([this](std::vector<std::string> paths) { handleFileDrop(paths); });
// A restored or reloaded scene is a different Scene object; everything that
// pointed into the old one has to be re-resolved.
document_.onSceneReplaced([this](Scene& scene) {
// The previewed nodes lived in the old scene; restoring would write
// through dangling pointers. Discard only.
stopAnimationPreview(false);
// Markers, spline curves and the frustum helper point into the outgoing
// graph too. Drop them before anything can dereference an owner that is
// gone.
clearViewportMarkers();
clearSplineOverlays();
clearConveyorOverlays();
clearTreeOverlays();
// The rings are keyed by the outgoing scene's uuid; the audition is
// playing a file for a node that is about to stop existing.
clearSoundRings();
// Keyed by uuid too, and placed off a node that is going away.
clearJointHelper();
clearVehicleHelper();
stopAudition();
// The collider lines are world-space and belong to a world that stop()
// has already destroyed; the node itself is parented to the surviving
// overlay, so it has to be taken down explicitly.
clearPhysicsDebug();
// Same for the sensor cloud: world-space points from sensors the play
// session has already dropped, hanging off an overlay that survives.
clearSensorOverlay();
// Thumbnails are keyed by texture uuid, and the restored scene rebuilds
// its textures — same uuid, different object. Nothing stale survives.
clearThumbnailCache();
if (cameraHelper_) {
cameraHelper_->removeFromParent();
cameraHelper_.reset();
cameraHelperFor_ = nullptr;
}
// Recorded commands point into the old scene too. Re-resolve their
// targets by uuid against the new graph; commands that cannot (raw
// captures in property setters) are dropped rather than left dangling.
// Everything below points into the outgoing graph, so note what has to
// come back before letting go of it.
const auto uuid = selection_.uuid();
selection_.set(nullptr);
gizmo_->detach();
// The overlay group survives the scene swap, so the outlines must be
// detached from it, not just dropped. The instance index goes with them:
// it indexed into a mesh that is about to be freed, and the reselect
// below re-derives whatever the restored graph actually has.
if (selectionBox_) {
selectionBox_->removeFromParent();
selectionBox_.reset();
}
if (instanceOutline_) {
instanceOutline_->removeFromParent();
instanceOutline_.reset();
}
selectedInstance_.reset();
instanceBox_.makeEmpty();
// Before rebinding: this replaces nodes, and the command stack should
// resolve its targets against the final graph.
rearticulateRobots(scene);
commands_.rebind(scene);
if (!uuid.empty()) {
Object3D* found = nullptr;
scene.traverse([&](Object3D& o) {
if (!found && o.uuid == uuid) found = &o;
});
if (found) selectObject(found);
}
});
// A dropped undo entry is a promise withdrawn, so say WHICH one out loud. The
// budget only ever bites on splat scans, where one deletion held in history is
// a couple of gigabytes of host memory.
commands_.onPrune([this](const std::vector<std::string>& dropped, std::size_t bytesFreed) {
constexpr double gib = 1024.0 * 1024.0 * 1024.0;
constexpr std::size_t named = 3;// enough to be specific, short enough to read
std::ostringstream message;
message << "undo history: dropped ";
for (std::size_t i = 0; i < std::min(named, dropped.size()); ++i) {
message << (i ? ", " : "") << '"' << dropped[i] << '"';
}
if (dropped.size() > named) message << " and " << (dropped.size() - named) << " more";
message << std::fixed << std::setprecision(2)
<< " to free " << static_cast<double>(bytesFreed) / gib << " GiB (budget "
<< static_cast<double>(commands_.byteLimit()) / gib << " GiB)";
log(message.str());
});
// Undoing an "Add" deletes the object it created, and undoing a paste or a
// reparent can move it out from under the selection. Anything still
// pointing at a node that left the scene has to let go — otherwise the
// gizmo drives a detached object and TransformControls rightly complains.
commands_.onChange([this] {
auto* selected = selection_.get();
if (!selected) return;
bool present = false;
document_.scene().traverse([&](Object3D& object) {
if (&object == selected) present = true;
});
if (!present) selectObject(nullptr);
});
#ifdef THREEPP_EDITOR_WITH_PHYSX
// Kept as a member too: the collider overlay reads the world it builds.
physics_ = std::make_shared<PhysicsPlaySession>();
// Soft bodies can decline to cook, and the GPU world can decline to come
// up; both are worth a line in the log rather than silence.
physics_->setLogger([this](const std::string& message) { log(message); });
play_.addSession(physics_);
// Right after physics: its start() borrows the world physics just built,
// and stopping in reverse order tears the belts down while that world is
// still alive.
conveyorSession_ = std::make_shared<ConveyorPlaySession>();
conveyorSession_->setPhysics(physics_.get());
play_.addSession(conveyorSession_);
#endif
play_.addSession(std::make_shared<AnimationPlaySession>());
#ifdef THREEPP_WITH_AUDIO
// Sounds. Kept as a member for the status readout and the selftest. Its
// listener rides the perspective viewport camera, which is the closest
// thing the editor has to "where the user is standing" — the ortho views
// are a drafting aid, not a vantage.
audio_ = std::make_shared<AudioPlaySession>();
audio_->setLogger([this](const std::string& message) { log(message); });
audio_->setListenerHost(&camera_);
play_.addSession(audio_);
#endif
// After physics (whose world the pushed sensors register with) and after the
// animation player, so a scan sees the pose the frame ended on. Before the
// script session, which stays last by rule — a script that moves a sensor's
// object is therefore read one frame later, which is the price of "scripts
// are the frame's final word".
#ifdef THREEPP_EDITOR_WITH_PHYSX
{
auto sensors = std::make_shared<PhysxSensorPlaySession>();
sensors->setPhysics(physics_.get());
sensors_ = std::move(sensors);
}
#else
// The base session runs the vision sensors: a depth or lidar scan needs a
// renderer, not a physics world. Body and joint sensors author, and say at
// Play which build they are waiting for.
sensors_ = std::make_shared<SensorPlaySession>();
#endif
sensors_->setRenderer(renderer_.get());
sensors_->setRig(sensorRig_.get());
sensors_->setHiddenDuringScan(overlay_.get());
sensors_->setLogger([this](const std::string& message) { log(message); });
play_.addSession(sensors_);
#ifdef THREEPP_EDITOR_WITH_PYTHON
// Last, so a script's transform edits are the final word for the frame —
// physics and the animation player have already had their say.
scripts_ = std::make_shared<ScriptPlaySession>();
scripts_->setLogger([this](const std::string& message) { log(message); });
play_.addSession(scripts_);
// threepp.editor.is_key_down: let a playing script be DRIVEN. Answered from ImGui's key
// state, not the canvas's — `ioCapture_.preventKeyboardEvent` gates on
// WantCaptureKeyboard, which stays true for as long as a panel keeps focus after a click,
// so the canvas's held-key set would be stale exactly when somebody is watching the
// viewport. ImGui's own state is fed by the backend regardless of who is capturing.
//
// Suppressed on the same rule handleShortcuts() uses (real text entry, an open popup, the
// file browser) rather than on WantCaptureKeyboard, for the same reason: gating on that
// made every shortcut dead until the viewport was clicked again.
scripting::keyStateProvider() = [this](const std::string& name) {
// Asking at all is the signal: a script that polls the keyboard takes the plain keys
// off the editor for the rest of the session (see handleShortcuts). Recorded on the
// first poll, which happens on the script's first update() — before anyone has had
// time to press anything.
if (isPlaying() && !scriptsPolledKeys_) {
scriptsPolledKeys_ = true;
log("a script is reading the keyboard - editor key shortcuts yield until Stop");
}
const ImGuiIO& io = ImGui::GetIO();
if (io.WantTextInput) return false;
if (ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel)) return false;
if (fileBrowser_.isOpen()) return false;
const ImGuiKey key = imguiKeyFromName(name);
return key != ImGuiKey_None && ImGui::IsKeyDown(key);
};
#endif
loadSettings();
assetDir_ = settings_.sceneDir.empty() ? std::filesystem::current_path()
: std::filesystem::path(settings_.sceneDir);
if (!options_.example.empty()) {
openExample(options_.example);
} else if (!options_.openOnStart.empty() && options_.openOnStart.extension() == ".json") {
openScene(options_.openOnStart);
} else {
buildTemplateScene();
// Any other startup path goes through the same dispatch as a file
// drop, so `threepp_editor model.glb` imports into the template scene.
// The self-test drives its own import instead (with assertions).
if (!options_.openOnStart.empty() && !options_.selfTest) {
// handleFileDrop expects UTF-8, because that is what GLFW drops
// deliver; .string() would narrow through the ANSI code page.
const auto u8 = options_.openOnStart.u8string();
handleFileDrop({std::string(u8.begin(), u8.end())});
}
}
// After the document, so it lights whatever ended up open — and before Play, so a
// --screenshot run is lit by the time it shoots.
if (!options_.environment.empty()) {
setEnvironment(options_.environment, /*alsoBackground*/ true);
}
log("threepp editor ready");
#ifndef THREEPP_EDITOR_WITH_PHYSX
log("built without PhysX - no physics session; vision sensors still scan");
#endif
#ifndef THREEPP_EDITOR_WITH_PYTHON
log("built without Python scripting - scripts are authored and saved, not run");
#endif
}
EditorApp::~EditorApp() {
canvas_.setIOCapture(nullptr);
// Before the renderer goes: the pane holds a view handle into it. (The pane
// is a member and would release itself, but member destruction order runs
// after this body and the renderer is declared above it.)
dockPane_.release();
// Stops the poll and takes the scratch .py with it. Whatever was saved is
// already in the document; what is left on disk is a copy nobody will read.
stopExternalEdit("the editor is closing");
// The sensor session parents nodes into sensorRig_, which is a member of this
// same object: member destruction order would take the rig down first and
// leave the session's destructor unlinking from freed memory. Drop the
// sessions here, while everything they point into is still alive.
play_.clearSessions();
sensors_.reset();
physics_.reset();
#ifdef THREEPP_WITH_AUDIO
// Same reasoning: its sounds are parented into the scene document_ owns.
audio_.reset();
// And the audition's, before the listener it was opened on goes.
stopAudition();
#endif
if (sensorRig_) {
sensorRig_->clear();
document_.removeEditorOnly(*sensorRig_);
}
// Tear the overlay down before the members it points at (the gizmo owns a
// pimpl that unregisters canvas listeners in its destructor).
if (gizmo_) {
gizmoDragSub_.unsubscribe();
gizmo_->detach();
gizmo_->removeFromParent();
}
if (overlay_) {
overlay_->clear();
document_.removeEditorOnly(*overlay_);
}
}
int EditorApp::run() {
Clock clock;
if (options_.selfTest) return runSelfTest();
if (options_.bench > 0) return runBench();
if (!options_.screenshot.empty()) return runScreenshot();
if (options_.play) startPlay();
if (options_.maxFrames > 0) {
for (int i = 0; i < options_.maxFrames; ++i) {
if (!canvas_.animateOnce([&] { frame(clock.getDelta()); })) break;
}
} else {
canvas_.animate([&] {
frame(clock.getDelta());
});
}
persistSettings();
return 0;
}
void EditorApp::frame(float dt) {
// Before the sessions step, so this frame's step drives on this frame's keys.
updateVehicleTeleop(dt);
play_.update(dt);
// Before anything reads the graph: the Generator section asked for this last
// frame, and it replaces a node the panel was drawing from.
const auto resolveCarrier = [this](const std::string& uuid) -> Object3D* {
if (document_.scene().uuid == uuid) return &document_.scene();
Object3D* found = nullptr;
document_.scene().traverse([&](Object3D& o) {
if (!found && o.uuid == uuid) found = &o;
});
return found;
};
if (!pendingRegenerate_.empty()) {
if (auto* carrier = resolveCarrier(std::exchange(pendingRegenerate_, {}))) {
regenerate(*carrier);
}
}
if (!pendingGeneratorClear_.empty()) {
if (auto* carrier = resolveCarrier(std::exchange(pendingGeneratorClear_, {}))) {
clearGenerator(*carrier);
}
}
pollImports(dt);
pollExternalEdit(dt);
if (animPreview_) animPreview_->mixer->update(dt);
// Before the orbit update, and a rigid translation of target AND camera, so
// the damping the orbit is carrying still resolves against the same offset.
updateFollow(dt);
// The gizmo's animated snap, before the orbit re-derives its spherical
// from wherever this leaves the camera.
updateViewTween(dt);
orbit_->update();
updateViewPreset();
// The nudge that keeps the grid off a coplanar ground is measured against
// the camera, so it is re-derived every frame rather than on view changes.
updateGridPlacement();
refreshSelectionHelpers();
// Dynamic splat LOD, before the render so this frame draws the choice.
// Only clouds imported with a multi-level table participate (lodTable()
// empty otherwise); the policy picks the coarsest level that still covers
// the cloud's projected footprint — so leaning in is always the finest
// level — and frustum-culls its chunks. Uses the same camera the frame
// renders with, which during Play is the play camera.
{
auto& cam = viewCamera();
const int viewH = canvas_.size().height();
document_.scene().traverse([&](Object3D& o) {
if (auto* sc = dynamic_cast<SplatCloud*>(&o); sc && !sc->lodTable().empty())
splats::selectLod(*sc, sc->lodTable(), cam, viewH);
});
}
// Before the render, not after: on Vulkan the camera dock is a secondary
// view that the renderer records INSIDE render(), and the camera it points
// at has to be this frame's camera. (Play and Stop replace the scene, and
// with it every camera object in it.)
syncCameraDockPane();
renderer_->render(document_.scene(), viewCamera());
dockPane_.endFrame();
renderCameraPreview();
if (!benchSkipUi_) ui_->render();
updateWindowTitle();
}
void EditorApp::updateWindowTitle() {
auto title = "threepp editor - " + document_.title();
if (title == lastWindowTitle_) return;
lastWindowTitle_ = title;
glfwSetWindowTitle(canvas_.windowPtr(), title.c_str());
}
void EditorApp::drawUi() {
theme::apply(contentScale_);
const ImGuiIO& io = ImGui::GetIO();
fps_ = io.Framerate;
// The side panels size themselves against the status bar, which is drawn
// after them. Seeding the height here (the status bar recomputes the same
// value) keeps the very first frame from being laid out against zero.
statusHeight_ = ImGui::GetFrameHeight() + 4 * contentScale_;
objectCount_ = 0;
document_.scene().traverse([&](Object3D& o) {
if (!document_.isEditorOnly(o) && &o != &document_.scene()) ++objectCount_;
});
// Rebuilt by drawInspector() below; anything left from last frame points at
// a layout that no longer exists.
frameTextureSlots_.clear();
drawMenuBar();
// Before the panels: the Scripts tab lives in the bottom panel, and which
// scripts are in it — if any — is decided here.
updateScriptEditors();
drawHierarchy();
drawInspector();
drawBottomPanel();
drawStatusBar();
drawViewGizmo();
drawToolPalette();
drawTransportBar();
drawViewpointPicker();
drawImportToast();
if (preview_.visible) {
// Background list, not foreground: the camera image is drawn by the
// renderer before any ImGui at all, so this layer sits over it while
// still passing under dialogs and menus.
auto* draw = ImGui::GetBackgroundDrawList();
const auto* viewport = ImGui::GetMainViewport();
const ImVec2 min(viewport->Pos.x + preview_.x, viewport->Pos.y + preview_.y);
const ImVec2 max(min.x + preview_.w, min.y + preview_.h);
if (!preview_.active) {
// Nothing rendered into it: paint the dock so the corner reads as
// panel rather than as a scrap of viewport nobody can reach.
draw->AddRectFilled(min, max, ImGui::GetColorU32(ImGuiCol_WindowBg));
// ...but only claim the dock is empty when it is. A Vulkan
// secondary view is allocated at a frame boundary, so for the frame
// or two before it first draws the dock holds a camera and no
// picture, and the hint would be wrong.
if (!preview_.pending) {
// Two different states, and telling them apart is the whole
// point: a scene with cameras and an empty dock is something
// the picker below can fix.
const char* hint = preview_.hasCameras ? "No camera in dock" : "No camera in scene";
const auto textSize = ImGui::CalcTextSize(hint);
draw->AddText({min.x + (preview_.w - textSize.x) * 0.5f,
min.y + (preview_.h - textSize.y) * 0.5f},
ImGui::GetColorU32(theme::muted()), hint);
}
}
draw->AddRect(min, max, ImGui::GetColorU32(ImGuiCol_Border));
// The label used to be painted here. It is a picker now — which camera
// the dock shows is a thing you set, not a readout of the selection.
drawCameraDockPicker();
}
// Dialogs and modals last so they sit above the panels.
if (fileBrowser_.draw(contentScale_)) {
const auto path = fileBrowser_.result();
switch (pendingDialog_) {
case PendingDialog::Open:
settings_.sceneDir = fileBrowser_.directory().string();
openScene(path);
break;
case PendingDialog::SaveAs:
settings_.sceneDir = fileBrowser_.directory().string();
saveSceneAs(path);
break;
case PendingDialog::ImportModel:
settings_.modelDir = fileBrowser_.directory().string();
importModel(path);
break;
case PendingDialog::Environment:
settings_.environmentDir = fileBrowser_.directory().string();
setEnvironment(path, environmentAsBackground_);
break;
case PendingDialog::Texture:
settings_.textureDir = fileBrowser_.directory().string();
assignTextureToSlot(path);
break;
case PendingDialog::Script:
settings_.scriptDir = fileBrowser_.directory().string();
// The dialog spans frames; the object it was opened for may be
// gone (deleted, or replaced by a play/stop) by now.
if (auto* target = findByUuid(document_.scene(), scriptTargetUuid_)) {
assignScript(*target, path);
} else {
log("script not attached - the object is no longer in the scene");
}
scriptTargetUuid_.clear();
break;
case PendingDialog::Sound:
settings_.soundDir = fileBrowser_.directory().string();
if (auto* target = findByUuid(document_.scene(), soundTargetUuid_)) {
assignSound(*target, path);
} else {
log("sound not attached - the object is no longer in the scene");
}
soundTargetUuid_.clear();
break;
case PendingDialog::RecordDir:
#ifdef THREEPP_EDITOR_WITH_PHYSX
// The dialog picks a FILE (it has no directory mode); what the
// recorder wants is the folder it sits in, because it writes one
// CSV per sensor named after the sensor.
if (sensors_) {
const auto dir = path.has_filename() ? path.parent_path() : path;
sensors_->setRecordDirectory(dir);
log("sensor recordings will go to " + dir.string());
}
#endif
break;
case PendingDialog::None:
break;
}
pendingDialog_ = PendingDialog::None;
}