forked from markaren/threepp
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathEditorSelfTest.cpp
More file actions
7784 lines (7031 loc) · 374 KB
/
Copy pathEditorSelfTest.cpp
File metadata and controls
7784 lines (7031 loc) · 374 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
// The editor driving itself: `--selftest` walks every seam the app has (play,
// undo across a scene swap, splines, sensors, scripts, the play-mode lock) and
// prints a PASS/FAIL line per assertion; `--screenshot` builds the spline-tube
// scenario, plays it and writes PNGs to look at. Both run on whichever backend
// the binary was started with, so `--selftest --vulkan` is a second full pass.
//
// Its own translation unit because it is half the code EditorApp used to be and
// none of the behaviour: the app and its acceptance harness now recompile
// independently, and a change to one cannot conflict with a change to the
// other. It is still built unconditionally and on purpose — an acceptance suite
// behind an off-by-default flag is one nobody runs, and this one has caught
// every regression in the editor so far.
#include "EditorApp.hpp"
#include "ImportFormats.hpp"
#include "threepp/extras/editor/AnimationConfig.hpp"
#include "threepp/extras/editor/ArticulationConfig.hpp"
#include "threepp/extras/editor/JointConfig.hpp"
#include "threepp/extras/editor/PhysicsConfig.hpp"
#include "threepp/extras/editor/RobotConfig.hpp"
#include "threepp/extras/editor/ScriptConfig.hpp"
#include "threepp/extras/editor/ScriptWorkspace.hpp"
#include "threepp/extras/editor/SensorConfig.hpp"
#include "threepp/extras/editor/SoundConfig.hpp"
#include "threepp/extras/editor/SplatImportConfig.hpp"
#include "threepp/extras/editor/SplineConfig.hpp"
#include "threepp/extras/editor/TextConfig.hpp"
#include "threepp/extras/editor/TreeConfig.hpp"
#include "threepp/extras/editor/VehicleConfig.hpp"
#include "threepp/extras/imgui/ImguiContext.hpp"
#ifdef THREEPP_WITH_AUDIO
#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/extras/editor/ConveyorConfig.hpp"
#include "threepp/core/Clock.hpp"
#include "threepp/extras/curves/CatmullRomCurve3.hpp"
#include "threepp/extras/editor/GeneratorConfig.hpp"
#include "threepp/geometries/BoxGeometry.hpp"
#include "threepp/helpers/CameraHelper.hpp"
#include "threepp/lights/Light.hpp"
#include "threepp/loaders/AssetSource.hpp"
#include "threepp/materials/MeshBasicMaterial.hpp"
#include "threepp/materials/MeshStandardMaterial.hpp"
#include "threepp/materials/interfaces.hpp"
#include "threepp/math/Box3.hpp"
#include "threepp/objects/Group.hpp"
#include "threepp/objects/LineSegments.hpp"
#include "threepp/objects/Mesh.hpp"
#include "threepp/objects/ObjectWithMaterials.hpp"
#include "threepp/objects/ObjectWithMorphTargetInfluences.hpp"
#include "threepp/objects/Points.hpp"
#include "threepp/objects/Robot.hpp"
#include "threepp/objects/SplatCloud.hpp"
#include "threepp/splats/SplatData.hpp"
#include "threepp/scenes/Scene.hpp"
#ifdef THREEPP_WITH_VULKAN
// The screenshot passes ask the renderer which way up its pixels come back.
#include "threepp/renderers/VulkanRenderer.hpp"
#endif
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdint>
#include <cstdlib>// std::getenv (THREEPP_BENCH_DISABLE)
#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <string>
#include <thread>
#include <vector>
using namespace threepp;
using namespace threepp::editor;
namespace {
// The radius a generated tube actually came out at: the FARTHEST any of its
// vertices sits from the curve it was swept along. A tube is a ring of
// vertices per sample, so the maximum is the radius wherever the sweep is
// honest and larger wherever it is not. Zero when there is nothing to
// measure. Selftest only.
float tubeRadius(const Mesh& mesh, const Object3D& spline) {
const auto geometry = mesh.geometry();
if (!geometry) return 0.f;
const auto* position = geometry->getAttribute<float>("position");
if (!position || position->count() < 4) return 0.f;
const auto config = editor::SplineConfig::read(spline);
const auto curve = config ? config->curve(spline) : nullptr;
if (!curve) return 0.f;
const auto spine = curve->getPoints(256);
float farthest = 0.f;
for (int i = 0; i < position->count(); ++i) {
const Vector3 vertex(position->getX(i), position->getY(i), position->getZ(i));
float nearest = std::numeric_limits<float>::max();
for (const auto& on : spine) nearest = std::min(nearest, vertex.distanceTo(on));
farthest = std::max(farthest, nearest);
}
return farthest;
}
// A short 16-bit mono PCM WAV, written from scratch.
//
// The audio block needs a file miniaudio can actually decode, and generating
// one is better than reaching for threepp-data: it makes the block run on a
// machine that never fetched the assets, and WAV is the one format the
// vendored miniaudio decodes with no third-party code at all. A quiet sine,
// long enough that a handful of frames cannot run it out.
bool writeTestWav(const std::filesystem::path& path, float seconds = 2.f) {
constexpr int rate = 22050;
constexpr int bits = 16;
constexpr int channels = 1;
const auto frames = static_cast<std::uint32_t>(static_cast<float>(rate) * seconds);
const std::uint32_t dataBytes = frames * channels * (bits / 8);
std::ofstream out(path, std::ios::binary);
if (!out) return false;
const auto u32 = [&out](std::uint32_t v) {
const unsigned char bytes[4]{static_cast<unsigned char>(v & 0xff),
static_cast<unsigned char>((v >> 8) & 0xff),
static_cast<unsigned char>((v >> 16) & 0xff),
static_cast<unsigned char>((v >> 24) & 0xff)};
out.write(reinterpret_cast<const char*>(bytes), 4);
};
const auto u16 = [&out](std::uint16_t v) {
const unsigned char bytes[2]{static_cast<unsigned char>(v & 0xff),
static_cast<unsigned char>((v >> 8) & 0xff)};
out.write(reinterpret_cast<const char*>(bytes), 2);
};
out.write("RIFF", 4);
u32(36 + dataBytes);
out.write("WAVE", 4);
out.write("fmt ", 4);
u32(16);
u16(1);// PCM
u16(channels);
u32(rate);
u32(rate * channels * (bits / 8));
u16(static_cast<std::uint16_t>(channels * (bits / 8)));
u16(bits);
out.write("data", 4);
u32(dataBytes);
for (std::uint32_t i = 0; i < frames; ++i) {
const auto t = static_cast<float>(i) / rate;
const auto sample = static_cast<std::int16_t>(
6000.f * std::sin(math::TWO_PI * 440.f * t));
u16(static_cast<std::uint16_t>(sample));
}
return out.good();
}
}// namespace
// stb_image_write is already compiled into threepp (utils/StbImageWrite.cpp);
// these mirror its two entry points rather than adding an include path for the
// one function this file wants.
extern "C" {
int stbi_write_png(char const* filename, int w, int h, int comp, const void* data, int stride_in_bytes);
void stbi_flip_vertically_on_write(int flag);
}
// The pixels the renderer just produced, written as a PNG. Shared by both
// screenshot passes; the row order is the BACKEND's, not a constant (GL hands
// back a bottom-up framebuffer and needs the flip, the Vulkan swapchain
// readback is already top-down).
bool EditorApp::shootTo(const std::filesystem::path& path) {
const auto size = canvas_.size();
bool bottomUpPixels = true;
#ifdef THREEPP_WITH_VULKAN
if (dynamic_cast<VulkanRenderer*>(renderer_.get())) bottomUpPixels = false;
#endif
stbi_flip_vertically_on_write(bottomUpPixels ? 1 : 0);
const auto pixels = renderer_->readRGBPixels();
const bool wrote =
pixels.size() >= static_cast<std::size_t>(size.width()) * size.height() * 3 &&
stbi_write_png(path.string().c_str(), size.width(), size.height(), 3,
pixels.data(), size.width() * 3) != 0;
std::cout << "[screenshot] " << (wrote ? "wrote " : "FAILED to write ") << path.string()
<< std::endl;
return wrote;
}
// --screenshot over WHATEVER IS OPEN: a scene file, or one of the shipped
// examples. The pass below it builds a fixed spline scenario and is what
// `--screenshot` alone still means; this one exists because a scene you cannot
// photograph is a scene nobody will look at, and adding a bespoke code path per
// scene is how a review harness stops being used.
//
// Everything about it is the command line's: --play decides whether it plays,
// --seconds how long it settles, --shot where the camera stands. With no shots
// it frames the document, which is at least an honest establishing view.
int EditorApp::runSceneScreenshot() {
Clock clock;
const auto playFor = [&](float seconds) {
float elapsed = 0.f;
for (int i = 0; i < 20000 && elapsed < seconds; ++i) {
const float dt = clock.getDelta();
elapsed += std::max(dt, 0.f);
canvas_.animateOnce([&] { frame(dt); });
}
};
sensorCloudVisible_ = true;
// Editor furniture off: the grid and the origin axes are drawn ON the
// scene's own floor, and a shot meant to answer "does this arena read" must
// not be answered through a wireframe lying across it.
if (grid_) grid_->visible = false;
if (axes_) axes_->visible = false;
// And the whole authoring layer with them — the marker icons, the selection
// outline, the frustum helper, the handles. A hemisphere light and an
// ambient light both sit at the origin, so their billboards hang in mid-air
// in the middle of the arena; a document that opens with something selected
// (userData["editorFollow"]) would be photographed through a yellow box.
// Useful when you are authoring, noise when you are judging a picture.
//
// Through the same flag Play reads (authoringVisible), so this pass hides
// what a play session hides and cannot drift from it — and unlike the four
// hand-hidden nodes it replaces, it also covers whatever the pass selects
// later. The point cloud stays: it is what the scene is DOING, not
// furniture.
hideAuthoring_ = true;
// One frame before Play so the scene's own materials and shadow maps exist.
playFor(0.05f);
if (options_.play) startPlay();
#ifdef THREEPP_EDITOR_WITH_PYTHON
// Hold the requested keys for the settle, then let go. The provider the app
// installed reads ImGui, and nothing is going to press a key here.
if (!options_.keys.empty()) {
const auto held = options_.keys;
scripting::keyStateProvider() = [held](const std::string& key) {
return std::find(held.begin(), held.end(), key) != held.end();
};
}
#endif
playFor(std::max(options_.settle, 0.05f));
#ifdef THREEPP_EDITOR_WITH_PYTHON
if (!options_.keys.empty() && !options_.holdKeys) {
scripting::keyStateProvider() = [](const std::string&) { return false; };
// Long enough for whatever was commanded to settle back to a hover.
playFor(1.2f);
}
#endif
auto shots = options_.shots;
if (shots.empty()) {
// Nothing asked for, so take what the session already has: a document
// that authored its own editorView has ANSWERED the framing question,
// and with Follow on the camera has been chasing the subject through
// the settle and IS the shot. Framing the document would throw both
// away. Anything else has nothing to keep, and gets the automatic view.
if (!documentView_ && !followSelection_) frameDocument();
shots.push_back({camera_.position, orbit_->target, ""});
}
const auto sibling = [&](const std::string& suffix) {
if (suffix.empty()) return options_.screenshot;
auto path = options_.screenshot;
path.replace_filename(options_.screenshot.stem().string() + "_" + suffix +
options_.screenshot.extension().string());
return path;
};
bool wrote = true;
for (const auto& shot : shots) {
camera_.position.copy(shot.position);
orbit_->target.copy(shot.target);
// Long enough for the point cloud to refill from the new pose and for
// any script-driven emissive to reach its current value.
playFor(0.35f);
wrote = shootTo(sibling(shot.label)) && wrote;
}
if (sensorCloud_ && sensorCloud_->geometry()) {
std::cout << "[screenshot] sensor cloud: "
<< sensorCloud_->geometry()->drawRange.count << " points" << std::endl;
}
if (isPlaying()) stopPlay();
return wrote ? 0 : 1;
}
// --bench: how long a frame of whatever is open actually takes.
//
// Exists because the numbers a person can read off the running editor are both
// wrong for the question. The status bar's fps is ImGui's smoothed average over
// a moving window, and the window is FIFO-presented, so a renderer that needs
// 12 ms and one that needs 16 both read "60". The constructor turns vsync off
// for this pass (see the Canvas parameters) so what is timed is the renderer.
//
// CPU frame time is the wall clock around one animateOnce — everything the
// editor does in a frame, present included. On Vulkan the per-pass GPU medians
// come from the backend's timestamp queries (VulkanRenderer::lastFrameTimings),
// which is the only way to say WHICH pass a frame is spent in; those are GPU
// time for that pass, so they do not sum to the CPU frame time and are not
// meant to.
//
// THREEPP_BENCH_DISABLE=a,b,c strips pieces of the frame for attribution. It is
// a bench-only ablation switch, deliberately an environment variable rather
// than a command line flag: it exists to answer "what costs what" in a session,
// not to be a supported way to run the editor.
int EditorApp::runBench() {
// --- ablations ---------------------------------------------------------
bool noCloud = false, noSensors = false, noUi = false, noOverlay = false, noPlay = false;
if (const char* raw = std::getenv("THREEPP_BENCH_DISABLE"); raw && *raw) {
std::string list(raw);
std::cout << "[bench] disabled: " << list << std::endl;
const auto has = [&](const char* token) { return list.find(token) != std::string::npos; };
noCloud = has("cloud");
noSensors = has("sensors");
noUi = has("ui");
noOverlay = has("overlay");
noPlay = has("play");
if (has("follow")) followSelection_ = false;
#ifdef THREEPP_WITH_VULKAN
// The deferred pipeline's own knobs, so "what is the floor" can be
// answered per stage instead of guessed at.
if (auto* vulkan = dynamic_cast<VulkanRenderer*>(renderer_.get())) {
if (has("ao")) vulkan->setDeferredAO(false);
if (has("probegi")) vulkan->setProbeGI(false);
if (has("restir")) vulkan->setRestirDIEnabled(false);
if (has("denoise")) vulkan->setDenoise(false);
// Compute vs bandwidth: half the pixels. A cost that halves is
// per-pixel work; one that does not is fixed or bandwidth-bound.
if (has("halfres")) vulkan->setRenderScale(0.5f);
}
#endif
}
if (noSensors) {
// Strip the authoring, not the objects: the scene keeps its geometry and
// its mass, and Play simply builds no sensors from it.
int stripped = 0;
document_.scene().traverse([&](Object3D& object) {
if (const auto config = SensorConfig::read(object); config && config->enabled) {
object.userData.erase("sensor");
++stripped;
}
});
std::cout << "[bench] stripped " << stripped << " sensor(s)" << std::endl;
}
if (noCloud) sensorCloudVisible_ = false;
if (noOverlay && overlay_) overlay_->visible = false;
benchSkipUi_ = noUi;
if (options_.play && !noPlay) startPlay();
#ifdef THREEPP_EDITOR_WITH_PYTHON
if (!options_.keys.empty()) {
const auto held = options_.keys;
scripting::keyStateProvider() = [held](const std::string& key) {
return std::find(held.begin(), held.end(), key) != held.end();
};
}
#endif
Clock clock;
const auto playFor = [&](float seconds) {
float elapsed = 0.f;
for (int i = 0; i < 100000 && elapsed < seconds; ++i) {
const float dt = clock.getDelta();
elapsed += std::max(dt, 0.f);
if (!canvas_.animateOnce([&] { frame(dt); })) break;
}
};
// Warm up: shader/pipeline compiles, the first BLAS builds, TAA history,
// the probe grid's first round-robin sweep and — for a played scene — the
// controller settling into its hover all land in here rather than in the
// measurement.
playFor(std::max(options_.settle, 0.5f));
#ifdef THREEPP_WITH_VULKAN
auto* vk = dynamic_cast<VulkanRenderer*>(renderer_.get());
std::vector<VulkanRenderer::FrameTimings> gpu;
if (vk) gpu.reserve(static_cast<std::size_t>(options_.bench));
#endif
std::vector<double> cpuMs;
cpuMs.reserve(static_cast<std::size_t>(options_.bench));
for (int i = 0; i < options_.bench; ++i) {
const auto begin = std::chrono::high_resolution_clock::now();
const float dt = clock.getDelta();
if (!canvas_.animateOnce([&] { frame(dt); })) break;
const auto end = std::chrono::high_resolution_clock::now();
cpuMs.push_back(std::chrono::duration<double, std::milli>(end - begin).count());
#ifdef THREEPP_WITH_VULKAN
if (vk) gpu.push_back(vk->lastFrameTimings());
#endif
}
if (cpuMs.empty()) {
std::cout << "[bench] no frames measured" << std::endl;
return 1;
}
// Median and p95 rather than a mean: one 40 ms hitch (a pipeline compile
// that escaped the warmup, the OS taking the core away) moves a mean over
// 600 frames by enough to hide a real regression, and the p95 is where a
// periodic stall shows up as itself instead of smearing into the average.
const auto pct = [](std::vector<double> v, double q) {
std::sort(v.begin(), v.end());
const auto at = static_cast<std::size_t>(q * static_cast<double>(v.size() - 1) + 0.5);
return v[at];
};
const double median = pct(cpuMs, 0.5);
const double p95 = pct(cpuMs, 0.95);
double sum = 0.;
for (const double ms : cpuMs) sum += ms;
std::cout << "[bench] frames=" << cpuMs.size()
<< " cpu_median=" << median << " ms"
<< " cpu_p95=" << p95 << " ms"
<< " cpu_max=" << *std::max_element(cpuMs.begin(), cpuMs.end()) << " ms"
<< " mean_fps=" << (1000. * static_cast<double>(cpuMs.size()) / sum)
<< " median_fps=" << (1000. / median) << std::endl;
#ifdef THREEPP_WITH_VULKAN
if (vk && !gpu.empty()) {
const auto medianOf = [&](float VulkanRenderer::FrameTimings::* field) {
std::vector<double> v;
v.reserve(gpu.size());
for (const auto& t : gpu) v.push_back(static_cast<double>(t.*field));
return pct(std::move(v), 0.5);
};
std::cout << "[bench] gpu medians (ms):"
<< " raster=" << medianOf(&VulkanRenderer::FrameTimings::rasterGbufMs)
<< " shade=" << medianOf(&VulkanRenderer::FrameTimings::pathTraceMs)
<< " denoise=" << medianOf(&VulkanRenderer::FrameTimings::denoiseMs)
<< " taa=" << medianOf(&VulkanRenderer::FrameTimings::taaMs)
<< " overlay=" << medianOf(&VulkanRenderer::FrameTimings::overlayMs)
<< " froxel=" << medianOf(&VulkanRenderer::FrameTimings::froxelMs)
<< " dof=" << medianOf(&VulkanRenderer::FrameTimings::dofMs)
<< " gbufResolve=" << medianOf(&VulkanRenderer::FrameTimings::gbufResolveMs)
<< " shadeB=" << medianOf(&VulkanRenderer::FrameTimings::shadeBMs)
<< std::endl;
std::cout << "[bench] cpu medians (ms):"
<< " ensureScene=" << medianOf(&VulkanRenderer::FrameTimings::cpuEnsureSceneMs)
<< " record=" << medianOf(&VulkanRenderer::FrameTimings::cpuRecordMs)
<< " render=" << medianOf(&VulkanRenderer::FrameTimings::cpuFrameMs)
<< std::endl;
}
#endif
if (isPlaying()) stopPlay();
return 0;
}
int EditorApp::runScreenshot() {
// A document of its own to photograph beats the built-in scenario. The
// scenario is the DEFAULT, not the contract: `--screenshot=x.png` with
// nothing else on the line still builds the tubes and writes every sibling
// view, which is what the road/spline acceptance passes ask for.
//
// ANY file on the command line counts, not only a .json. The startup path
// sends everything else through the import dispatch, so `threepp_editor
// scan.ply --screenshot=x.png` has a scene to photograph too — and
// photographing the spline tubes instead, because the file was a model
// rather than a document, is not a distinction anyone typing that meant to
// draw. The settle (--seconds) is what the async import finishes in.
if (!options_.example.empty() || !options_.openOnStart.empty()) {
return runSceneScreenshot();
}
Clock clock;
const auto playFor = [&](float seconds) {
float elapsed = 0.f;
// Wall-clock, not frame-count: with vsync off a frame's dt is tiny and
// a fixed frame budget would capture the balls still in the air.
for (int i = 0; i < 20000 && elapsed < seconds; ++i) {
const float dt = clock.getDelta();
elapsed += std::max(dt, 0.f);
canvas_.animateOnce([&] { frame(dt); });
}
};
auto& scene = document_.scene();
// The tubes this feature is judged on: the factory default, an S-curve, and
// a GRADED one that climbs into a crest inside a bend — a tube's closed
// cross-section has to survive all three.
auto plain = ObjectFactory::createSpline(scene);
{
auto config = SplineConfig::read(*plain).value_or(SplineConfig{});
config.mesh = SplineConfig::MeshKind::Tube;
config.radius = 0.5f;
config.write(*plain);
}
plain->position.z = -6.f;
addObject(plain, scene, "Screenshot Tube");
auto s = ObjectFactory::createSpline(scene);
{
static constexpr float points[][3] = {
{-9.f, 0.5f, -3.f}, {-3.f, 0.5f, 3.f}, {3.f, 0.5f, -3.f}, {9.f, 0.5f, 3.f}};
const auto nodes = SplineConfig::controlPointNodes(*s);
for (std::size_t i = 0; i < nodes.size() && i < 4; ++i) {
nodes[i]->position.set(points[i][0], points[i][1], points[i][2]);
}
auto config = SplineConfig::read(*s).value_or(SplineConfig{});
config.mesh = SplineConfig::MeshKind::Tube;
config.radius = 0.6f;
config.write(*s);
}
s->position.z = 4.f;
addObject(s, scene, "Screenshot S Tube");
auto hill = ObjectFactory::createSpline(scene);
{
static constexpr float points[][3] = {
{-11.f, 0.f, 0.f}, {-4.f, 1.5f, 3.f}, {1.f, 3.f, 0.f}, {6.f, 1.5f, -3.f}, {12.f, 0.f, 0.f}};
auto config = SplineConfig::read(*hill).value_or(SplineConfig{});
for (std::size_t i = SplineConfig::controlPointNodes(*hill).size(); i < 5; ++i) {
hill->add(ObjectFactory::createSplinePoint(*hill));
}
const auto nodes = SplineConfig::controlPointNodes(*hill);
for (std::size_t i = 0; i < nodes.size() && i < 5; ++i) {
nodes[i]->position.set(points[i][0], points[i][1], points[i][2]);
}
config.mesh = SplineConfig::MeshKind::Tube;
config.radius = 0.4f;
config.write(*hill);
}
hill->position.z = 12.f;
addObject(hill, scene, "Screenshot Hill Tube");
playFor(0.1f);// the sync pass derives the tube meshes
for (auto* spline : {plain.get(), s.get(), hill.get()}) {
if (auto* mesh = SplineConfig::derivedMesh(*spline)) {
PhysicsConfig config;
config.enabled = true;
config.body = PhysicsConfig::Body::Static;
config.write(*mesh);
}
}
// Returns the body it dropped, so a caller can instrument it. `label` is the
// undo label AND the name, which makes the hierarchy in these shots readable.
const auto drop = [&](Primitive kind, const Vector3& from, const char* label) {
auto object = ObjectFactory::createPrimitive(kind, scene);
object->name = label;
object->position.copy(from);
PhysicsConfig config;
config.enabled = true;
config.body = PhysicsConfig::Body::Dynamic;
config.friction = 0.8f;
config.write(*object);
addObject(object, scene, label);
};
drop(Primitive::Sphere, {-6.f, 3.f, 4.f}, "Ball on S");
drop(Primitive::Sphere, {0.f, 3.f, -7.f}, "Ball on default");
// An IMU on one of the falling bodies, so the Sensors tab has a signal with
// shape in it: free fall reads ~0, the landing impact spikes, and rest
// settles on +g. A flat trace proves the plot draws; that one proves it is
// plotting physics.
if (auto* ball = document_.scene().getObjectByName("Ball on S")) {
SensorConfig imu;
imu.enabled = true;
imu.type = SensorConfig::Type::Imu;
imu.rateHz = 60.f;
imu.write(*ball);
}
// A box, not a ball: a sphere on a hill rolls off it, and what wants
// showing here is a body sitting still on a graded surface — the case a
// trimmed offset broke, since it invented a height at every corner it cut
// and left a step to catch on.
drop(Primitive::Box, {-1.f, 4.5f, 13.5f}, "Box near the crest");
// A LIDAR on a mast, authored exactly as the inspector authors one. Added
// BEFORE play, because the pre-play snapshot is what Stop restores — an
// object added while playing is not in the document at all.
//
// This is the shot the sensor feature is judged on. A count in a panel says
// a scan happened; only the cloud says the beams, the sensor pose and the
// unprojection agree, and only a picture shows a cloud hugging the geometry
// rather than floating beside it.
{
auto mast = ObjectFactory::createPrimitive(Primitive::Box, scene);
mast->name = "Lidar Mast";
mast->position.set(0.f, 2.2f, 6.f);
mast->scale.set(0.3f, 0.3f, 0.3f);
SensorConfig sensor;
sensor.enabled = true;
sensor.type = SensorConfig::Type::Lidar;
sensor.beams = SensorConfig::Beams::OS1_64;
sensor.faceSize = 192;
sensor.rateHz = 8.f;
sensor.nearPlane = 0.4f;
sensor.farPlane = 40.f;
sensor.rangeStddev = 0.01f;
sensor.write(*mast);
addObject(mast, scene, "Add Lidar Mast");
}
// The text feature's own acceptance: solid type standing over the tubes.
// Judged the way the tubes are — by looking. Outlines that fail to
// triangulate, holes that fill in (the counters of e and p), or a centring
// bug all show here and in no vertex count.
{
auto title = ObjectFactory::createText(scene);
auto config = TextConfig::read(*title).value_or(TextConfig{});
config.text = "threepp";
config.size = 1.4f;
config.depth = 0.35f;
config.apply(*title);
title->name = "Screenshot Title";
title->position.set(0.f, 4.5f, -2.f);
addObject(title, scene, "Add Screenshot Title");
}
sensorCloudVisible_ = true;
startPlay();
playFor(2.5f);// balls settle, the collider overlay's line buffer fills
camera_.position.set(-1.f, 27.f, 27.f);
orbit_->target.set(0.f, 0.f, 5.f);
playFor(0.2f);
const auto shoot = [&](const std::filesystem::path& path) { return shootTo(path); };
// Two shots, because one cannot answer both questions. A road drawn under
// its own collider overlay is a wall of lines — good for asking whether the
// shapes hug the surface, useless for asking whether the surface is faceted.
const auto sibling = [&](const char* suffix) {
auto path = options_.screenshot;
path.replace_filename(options_.screenshot.stem().string() + suffix +
options_.screenshot.extension().string());
return path;
};
bool wrote = shoot(options_.screenshot);
// And a third, low and near, along the graded road. A crease in a grade is
// invisible from overhead — it is a shading break, and shading breaks want
// a glancing angle and the surface filling the frame.
camera_.position.set(1.f, 3.2f, 34.f);
orbit_->target.set(0.f, 1.f, 12.f);
playFor(0.2f);
wrote = shoot(sibling("_graded")) && wrote;
camera_.position.set(-1.f, 27.f, 27.f);
orbit_->target.set(0.f, 0.f, 5.f);
physicsDebug_ = true;
playFor(0.4f);// the overlay's line buffer fills
wrote = shoot(sibling("_colliders")) && wrote;
// And the sensor cloud, still inside the same play. Collider lines off:
// a cloud read through a wall of them says nothing about either.
physicsDebug_ = false;
{
const auto cloudPoints = [this] {
const auto geometry = sensorCloud_ ? sensorCloud_->geometry() : nullptr;
return geometry ? geometry->drawRange.count : 0;
};
// Wall-clock, and waiting on the CLOUD rather than on a frame count: a
// scan is rate-gated off the physics accumulator, so how many frames it
// takes depends on the machine. Vision sensors scan in every build —
// the session no longer needs PhysX — so the wait is unconditional.
for (int i = 0; i < 400 && sensors_ && cloudPoints() == 0; ++i) playFor(0.05f);
camera_.position.set(-11.f, 9.f, 20.f);
orbit_->target.set(0.f, 1.5f, 6.f);
playFor(0.4f);
std::cout << "[screenshot] sensor cloud: " << cloudPoints() << " points" << std::endl;
wrote = shoot(sibling("_sensor_cloud")) && wrote;
// Low and close, along the beams: a cloud that looks fine from above can
// still be sitting a metre off the surface it is meant to be measuring,
// and only a grazing angle shows that.
camera_.position.set(-2.f, 3.2f, 15.f);
orbit_->target.set(0.f, 1.2f, 6.f);
playFor(0.4f);
wrote = shoot(sibling("_sensor_cloud_near")) && wrote;
// And the readout, with the Sensors tab brought forward. The plots are
// the other half of "see them live", and a plot nobody has looked at is
// a plot nobody knows is drawing the right thing.
selectSensorsTab_ = true;
playFor(0.4f);
wrote = shoot(sibling("_sensor_panel")) && wrote;
}
camera_.position.set(-1.f, 27.f, 27.f);
orbit_->target.set(0.f, 0.f, 5.f);
// And the axis views, for the same reason the rest of this function exists:
// a projection is a claim about what the image does to parallel lines, and
// the only way to check it is to look. Top wants the grid flat under the
// road; Front wants it stood up behind it.
physicsDebug_ = false;
// Stopped and with something selected: the gizmo is rebuilt against the
// ortho camera when the projection changes, and a gizmo that draws at the
// wrong size or points the wrong way is the failure mode to look for.
stopPlay();
playFor(0.2f);
if (auto* subject = document_.scene().getObjectByName("Spline 3")) selectObject(subject);
setOrthographic(true);
setViewPreset(ViewPreset::Top);
playFor(0.2f);
wrote = shoot(sibling("_ortho_top")) && wrote;
setViewPreset(ViewPreset::Front);
playFor(0.2f);
wrote = shoot(sibling("_ortho_front")) && wrote;
// And the pair that answers the OTHER question about a projection toggle:
// does the scene still SHADE the same. The axis views above can't — nothing
// to compare them against — so shoot one user viewpoint twice, perspective
// then orthographic, and let the toggle's own framing preservation line them
// up. Lights, shadows, ambient occlusion and fog should read the same in
// both; only the perspective convergence should differ. This is the shot
// that caught the Vulkan backend routing an ortho camera into the flat
// unlit HUD path (see setOrthographicSceneRendering).
setOrthographic(false);
camera_.position.set(-1.f, 14.f, 22.f);
orbit_->target.set(0.f, 0.f, 8.f);
playFor(0.3f);
wrote = shoot(sibling("_persp_user")) && wrote;
setOrthographic(true);
playFor(0.3f);
wrote = shoot(sibling("_ortho_user")) && wrote;
// And the camera-preview dock. A scene camera, selected, renders through
// the renderer's secondary-pane path — the one that drew flat unlit fills
// over the editor view on Vulkan. The shot is what says the dock now shows
// a cleared background and lit, depth-tested geometry.
setOrthographic(false);
{
auto previewCamera = ObjectFactory::createCamera(document_.scene());
previewCamera->position.set(-8.f, 6.f, 4.f);
previewCamera->lookAt(Vector3(0.f, 1.f, 6.f));
addObject(previewCamera, document_.scene(), "Add Camera");
selectObject(previewCamera.get());
}
playFor(0.3f);
wrote = shoot(sibling("_campreview")) && wrote;
// And the dock as SENSOR preview: a camera-hosted colour sensor, selected,
// still in edit mode — no Play anywhere near. This is the shot the sensor
// authoring flow is judged on now: aiming a sensor IS aiming a camera, so
// the frustum helper and the sensor glyph stand on the same node in the
// viewport while the dock shows what the sensor will record, before the
// first Play ever runs.
{
auto eye = ObjectFactory::createCamera(document_.scene());
eye->name = "Sensor Cam";
eye->position.set(-2.2f, 3.4f, 8.5f);
// -Z is the viewing direction; pitched down the slope the tubes run on.
eye->rotation.set(-0.55f, 0.35f, 0.f);
eye->fov = 62.f;
eye->nearPlane = 0.1f;
eye->farPlane = 60.f;
eye->updateProjectionMatrix();
SensorConfig colour;
colour.enabled = true;
colour.type = SensorConfig::Type::Camera;
colour.width = 192;
colour.height = 128;
colour.rateHz = 8.f;
colour.write(*eye);
addObject(eye, document_.scene(), "Add Sensor Cam");
// Framed so the sensor camera, its frustum and the slope it looks at
// are all in shot together with the dock.
camera_.position.set(-6.f, 8.f, 18.f);
orbit_->target.set(-1.f, 2.f, 6.f);
}
playFor(0.3f);
wrote = shoot(sibling("_sensor_dock")) && wrote;
// And instancing. The question a screenshot answers here is the one the
// assertions cannot: a grid of instances drawn from one object, with the
// outline sitting around ONE of them. A box around the whole cloud and a box
// around the right instance both satisfy "an outline exists" — only the
// picture distinguishes them.
{
constexpr int kCols = 6;
constexpr int kRows = 4;
auto instanced = InstancedMesh::create(
BoxGeometry::create(0.8f, 0.8f, 0.8f),
MeshStandardMaterial::create({{"color", Color(0x66aaff)}}),
kCols * kRows);
instanced->name = "Instanced Grid";
for (int r = 0; r < kRows; ++r) {
for (int c = 0; c < kCols; ++c) {
Matrix4 m;
// A little height variation, so the shot reads as many objects
// rather than as one flat wall that could be a single mesh.
const float y = 0.6f + 0.35f * static_cast<float>((r + c) % 3);
m.setPosition(-5.f + 2.f * static_cast<float>(c), y,
-4.f + 2.f * static_cast<float>(r));
instanced->setMatrixAt(static_cast<std::size_t>(r * kCols + c), m);
}
}
instanced->instanceMatrix()->needsUpdate();
addObject(instanced, document_.scene(), "Add Instanced Grid");
playFor(0.2f);
// A middle instance, so the outline has neighbours on every side: an
// outline one cell off is obvious here and invisible at a corner.
const int picked = 2 * kCols + 3;
selectObject(instanced.get(), picked);
camera_.position.set(-2.f, 7.f, 11.f);
orbit_->target.set(0.f, 1.f, -1.f);
playFor(0.3f);
std::cout << "[screenshot] instanced grid: " << instanced->count()
<< " instances, outlining " << picked << std::endl;
wrote = shoot(sibling("_instancing")) && wrote;
}
// And the conveyors. What the picture answers that the assertions cannot:
// does a generated conveyor read as a MACHINE — frame, legs, drums, belt
// texture, roller bed, cleat bars, a true circular bend — and does the
// playing one carry its cargo mid-belt. Everything in the shot is
// first-party procedural geometry.
{
selectObject(nullptr);
// A long straight belt on the frame, cargo dropped at its upstream end.
auto straight = ObjectFactory::createConveyor(document_.scene());
straight->name = "Conveyor Straight";
straight->position.set(30.f, 0.f, -6.f);
{
const auto nodes = ConveyorConfig::waypointNodes(*straight);
nodes[0]->position.set(-3.5f, 0.75f, 0.f);
nodes[1]->position.set(0.f, 0.75f, 0.f);
nodes[2]->position.set(3.5f, 0.75f, 0.f);
auto config = ConveyorConfig::read(*straight).value_or(ConveyorConfig{});
config.speed = 1.f;
config.width = 0.9f;
config.write(*straight);
// A diverter plowed across the belt: by the play shot the cargo is
// being fed toward the edge — the picture that says walls WORK.
auto wall = ObjectFactory::createConveyorWall(*straight);
const auto wallPoints = ConveyorWallConfig::pointNodes(*wall);
if (wallPoints.size() >= 2) {
wallPoints[0]->position.set(-0.9f, 0.75f, 0.5f);
wallPoints[1]->position.set(0.7f, 0.75f, -0.2f);
}
straight->add(wall);
}
addObject(straight, document_.scene(), "Add Conveyor");
// A guide wall riding beside it — the separator form.
auto rail = ObjectFactory::createConveyor(document_.scene());
rail->name = "Conveyor Rail";
rail->position.set(30.f, 0.75f, -5.35f);
{
const auto nodes = ConveyorConfig::waypointNodes(*rail);
nodes[0]->position.set(-3.5f, 0.f, 0.f);
nodes[1]->position.set(0.f, 0.f, 0.f);
nodes[2]->position.set(3.5f, 0.f, 0.f);
auto config = ConveyorConfig::read(*rail).value_or(ConveyorConfig{});
config.separator = true;
config.wallHeight = 0.35f;
config.write(*rail);
}
addObject(rail, document_.scene(), "Add Conveyor Rail");
// A roller bed running into an exact right-angle bend (a rounded
// corner waypoint) — the two per-segment surfaces the flat shot can't
// show, and the tangent fillet the corner model guarantees.
auto bend = ObjectFactory::createConveyor(document_.scene());
bend->name = "Conveyor Bend";
bend->position.set(28.f, 0.f, 2.f);
{
const auto nodes = ConveyorConfig::waypointNodes(*bend);
nodes[0]->position.set(-3.f, 0.75f, 0.f);
nodes[1]->position.set(0.f, 0.75f, 0.f);
nodes[2]->position.set(0.f, 0.75f, 3.f);
ConveyorWaypointConfig rollers;
rollers.segKind = conveyor::SegKind::Rollers;
rollers.write(*nodes[0]);
ConveyorWaypointConfig corner;
corner.cornerRadius = 2.f;
corner.write(*nodes[1]);
auto config = ConveyorConfig::read(*bend).value_or(ConveyorConfig{});
config.speed = 0.8f;
config.smooth = false;
config.width = 0.9f;
config.write(*bend);
}
addObject(bend, document_.scene(), "Add Conveyor Bend");
// A climb with cleats: the flight bars are why cargo does not slide
// back down the incline.
auto climb = ObjectFactory::createConveyor(document_.scene());
climb->name = "Conveyor Climb";
climb->position.set(24.f, 0.f, 8.f);
{
const auto nodes = ConveyorConfig::waypointNodes(*climb);
nodes[0]->position.set(-3.f, 0.5f, 0.f);
nodes[1]->position.set(-0.5f, 0.55f, 0.f);
nodes[2]->position.set(3.f, 2.f, 0.f);
ConveyorWaypointConfig cleats;
cleats.segKind = conveyor::SegKind::Cleats;
cleats.write(*nodes[1]);
auto config = ConveyorConfig::read(*climb).value_or(ConveyorConfig{});
config.speed = 0.7f;
config.width = 0.9f;
config.cleatHeight = 0.2f;
config.write(*climb);
}
addObject(climb, document_.scene(), "Add Conveyor Climb");
playFor(0.2f);// the sync pass derives the parts
{
std::size_t parts = 0;
for (auto* owner : {straight.get(), rail.get(), bend.get(), climb.get()}) {
if (auto* group = ConveyorConfig::derivedGroup(*owner)) {
parts += group->children.size();
}
}
std::cout << "[screenshot] conveyors: 4 authored, " << parts
<< " generated parts" << std::endl;
}
// NOT the `drop` lambda from the tube section: it closed over a Scene
// reference the play/stop cycles since then have replaced twice.
const auto cargo = [&](const Vector3& from, const char* label) {
auto object = ObjectFactory::createPrimitive(Primitive::Box, document_.scene());
object->name = label;
object->position.copy(from);
PhysicsConfig config;
config.enabled = true;
config.friction = 0.8f;
config.write(*object);
addObject(object, document_.scene(), label);
};
cargo({26.8f, 1.4f, -6.f}, "Cargo on straight");
cargo({25.3f, 1.3f, 2.f}, "Cargo on rollers");
cargo({21.5f, 1.2f, 8.f}, "Cargo on climb");
playFor(0.2f);
// The bend's rounded corner, selected: the still shot then carries the
// design aids — the derived arc centre, its tangent spokes and the
// flow chevrons — exactly as an author sees them.
if (auto* liveBend = document_.scene().getObjectByName("Conveyor Bend")) {
const auto nodes = ConveyorConfig::waypointNodes(*liveBend);
if (nodes.size() >= 2) selectObject(nodes[1]);
}
camera_.position.set(38.f, 8.f, 15.f);
orbit_->target.set(26.5f, 0.8f, 2.5f);
playFor(0.3f);
wrote = shoot(sibling("_conveyors")) && wrote;
// Plan view: the one projection that shows whether the bend is the
// exact quarter circle its arc-centre waypoint asked for, and whether
// the rails run parallel along it.
setOrthographic(true);
setViewPreset(ViewPreset::Top);
playFor(0.2f);
wrote = shoot(sibling("_conveyors_top")) && wrote;
setOrthographic(false);
camera_.position.set(38.f, 8.f, 15.f);
orbit_->target.set(26.5f, 0.8f, 2.5f);
playFor(0.2f);
// The same machines running: cargo mid-belt, cleat bars risen with it.
startPlay();
{
Clock beltClock;
float elapsed = 0.f;
for (int i = 0; i < 20000 && elapsed < 2.2f; ++i) {
const float dt = beltClock.getDelta();
elapsed += std::max(dt, 0.f);
canvas_.animateOnce([&] { frame(dt); });
}