-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathpolyscope.cpp
More file actions
1614 lines (1298 loc) · 52.3 KB
/
polyscope.cpp
File metadata and controls
1614 lines (1298 loc) · 52.3 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
// Copyright 2017-2023, Nicholas Sharp and the Polyscope contributors. https://polyscope.run
#include "polyscope/polyscope.h"
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
#include "ImGuizmo.h"
#include "imgui.h"
#include "implot.h"
#include "polyscope/imgui_config.h"
#include "polyscope/options.h"
#include "polyscope/pick.h"
#include "polyscope/render/engine.h"
#include "polyscope/utilities.h"
#include "polyscope/view.h"
#include "stb_image.h"
#include "nlohmann/json.hpp"
using json = nlohmann::json;
#include "IconFontCppHeaders/IconsLucide.h"
namespace polyscope {
// Note: Storage for global members lives in state.cpp and options.cpp
// Helpers
namespace {
// === Implement the context stack
// The context stack should _always_ have at least one context in it. The lowest context is the one created at
// initialization.
struct ContextEntry {
ImGuiContext* context;
ImPlotContext* plotContext;
std ::function<void()> callback;
bool drawDefaultUI;
};
std::vector<ContextEntry> contextStack;
int frameTickStack = 0;
bool redrawNextFrame = true;
bool unshowRequested = false;
// Some state about imgui windows to stack them
constexpr float INITIAL_LEFT_WINDOWS_WIDTH = 305;
auto prevMainLoopTime = std::chrono::steady_clock::now();
float rollingMainLoopDurationMicrosec = 0.;
float rollingMainLoopEMA = 0.05;
float lastMainLoopDurationMicrosec = 0.;
const std::string prefsFilename = ".polyscope.ini";
void readPrefsFile() {
try {
std::ifstream inStream(prefsFilename);
if (inStream) {
json prefsJSON;
inStream >> prefsJSON;
// Set values
// Do some basic validation on the sizes first to work around bugs with bogus values getting written to init file
if (view::windowWidth == -1 && prefsJSON.count("windowWidth") > 0) { // only load if not already set
int val = prefsJSON["windowWidth"];
if (val >= 64 && val < 10000) view::windowWidth = val;
}
if (view::windowHeight == -1 && prefsJSON.count("windowHeight") > 0) { // only load if not already set
int val = prefsJSON["windowHeight"];
if (val >= 64 && val < 10000) view::windowHeight = val;
}
if (prefsJSON.count("windowPosX") > 0) {
int val = prefsJSON["windowPosX"];
if (val >= 0 && val < 10000) view::initWindowPosX = val;
}
if (prefsJSON.count("windowPosY") > 0) {
int val = prefsJSON["windowPosY"];
if (val >= 0 && val < 10000) view::initWindowPosY = val;
}
if (prefsJSON.count("uiScale") > 0) {
float val = prefsJSON["uiScale"];
if (val >= 0.25 && val <= 4.0) options::uiScale = val;
}
}
}
// We never really care if something goes wrong while loading preferences, so eat all exceptions
catch (...) {
polyscope::warning("Parsing of prefs file .polyscope.ini failed");
}
}
void writePrefsFile() {
// Update values as needed
int posX, posY;
std::tie(posX, posY) = render::engine->getWindowPos();
int windowWidth = view::windowWidth;
int windowHeight = view::windowHeight;
float uiScale = options::uiScale;
// Validate values. Don't write the prefs file if any of these values are obviously bogus (this seems to happen at
// least on Windows when the application is minimzed)
bool valuesValid = true;
valuesValid &= posX >= 0 && posX < 10000;
valuesValid &= posY >= 0 && posY < 10000;
valuesValid &= windowWidth >= 64 && windowWidth < 10000;
valuesValid &= windowHeight >= 64 && windowHeight < 10000;
valuesValid &= uiScale >= 0.25 && uiScale <= 4.;
if (!valuesValid) return;
// Build json object
// clang-format off
json prefsJSON = {
{"windowWidth", windowWidth},
{"windowHeight", windowHeight},
{"windowPosX", posX},
{"windowPosY", posY},
{"uiScale", uiScale},
};
// clang-format on
// Write out json object
std::ofstream o(prefsFilename);
o << std::setw(4) << prefsJSON << std::endl;
}
void setInitialWindowWidths() {
internal::leftWindowsWidth = INITIAL_LEFT_WINDOWS_WIDTH * options::uiScale;
internal::rightWindowsWidth = options::rightGuiPaneWidth * options::uiScale;
}
void ensureWindowWidthsSet() {
if (internal::leftWindowsWidth <= 0. || internal::rightWindowsWidth <= 0.) {
setInitialWindowWidths();
}
internal::rightWindowsWidth = options::rightGuiPaneWidth * options::uiScale;
}
// Helper to get a structure map
std::map<std::string, std::unique_ptr<Structure>>& getStructureMapCreateIfNeeded(std::string typeName) {
if (state::structures.find(typeName) == state::structures.end()) {
state::structures[typeName] = std::map<std::string, std::unique_ptr<Structure>>();
}
return state::structures[typeName];
}
void sleepForFramerate() {
// If needed, block the program execution to hit the intended framerate
// (if not used, the render loop may busy-run maxed out at 1000+ fps and waste resources)
// WARNING: similar logic duplicated in this function and in shouldSkipFrameForFramerate()
if (options::maxFPS != -1) {
auto currTime = std::chrono::steady_clock::now();
long microsecPerLoop = 1000000 / options::maxFPS;
microsecPerLoop = (95 * microsecPerLoop) / 100; // give a little slack so we actually hit target fps
while (std::chrono::duration_cast<std::chrono::microseconds>(currTime - prevMainLoopTime).count() <
microsecPerLoop) {
std::this_thread::yield();
currTime = std::chrono::steady_clock::now();
}
}
}
bool shouldSkipFrameForFramerate() {
// Returns true if the current frame should be skipped to maintain the framerate
// NOTE: right now this logic is pretty simplistic, it just allows the frame to happen if 95% of the frametime has
// already passed. This might lead to choppiness in application loops which run at e.g. 150% of the target FPS, or
// miss opporunities for better timing if frameTick() is called in extremely tight loops.
//
// In the future we could write a fancier version of this function implementing smarter policies using
// rollingMainLoopDurationMicrosec
// WARNING: similar logic duplicated in this function and in sleepForFramerate()
if (options::maxFPS <= 0) return false;
auto currTime = std::chrono::steady_clock::now();
float microsecPerLoop = 1000000 / options::maxFPS;
microsecPerLoop = (95 * microsecPerLoop) / 100; // give a little slack so we actually hit target fps
// NOTE: we could incorporate rollingMainLoopDurationMicrosec here, but since the loop time is recorded at the
// beginning of each frame, the previous frame's time is _already_ incorporated into the timing.
auto nextLoopStartTimeToHitTarget =
prevMainLoopTime + std::chrono::microseconds(static_cast<int64_t>(std::round(microsecPerLoop)));
return currTime < nextLoopStartTimeToHitTarget;
}
void markLastFrameTime() {
auto currTime = std::chrono::steady_clock::now();
// update the prev & rolling average frame time
lastMainLoopDurationMicrosec =
std::chrono::duration_cast<std::chrono::microseconds>(currTime - prevMainLoopTime).count();
rollingMainLoopDurationMicrosec =
(1. - rollingMainLoopEMA) * rollingMainLoopDurationMicrosec + rollingMainLoopEMA * lastMainLoopDurationMicrosec;
// mark the time of this frame
prevMainLoopTime = currTime;
}
} // namespace
// === Core global functions
void init(std::string backend) {
if (isInitialized()) {
if (backend != state::backend) {
exception("re-initializing with different backend is not supported");
}
// otherwise silently allow multiple-init
return;
}
info(5, "Initializing Polyscope");
state::backend = backend;
if (options::usePrefsFile) {
readPrefsFile();
}
if (view::windowWidth == -1) view::windowWidth = view::defaultWindowWidth;
if (view::windowHeight == -1) view::windowHeight = view::defaultWindowHeight;
// Initialize the rendering engine
render::initializeRenderEngine(backend);
// Initialie ImGUI
IMGUI_CHECKVERSION();
render::engine->createNewImGuiContext();
// Create an initial context based context. Note that calling show() never actually uses this context, because it
// pushes a new one each time. But using frameTick() may use this context.
contextStack.push_back(ContextEntry{ImGui::GetCurrentContext(), ImPlot::GetCurrentContext(), nullptr, true});
internal::contextStackSize++;
view::invalidateView();
state::initialized = true;
state::doDefaultMouseInteraction = true;
}
void checkInitialized() {
if (!state::initialized) {
exception("Polyscope has not been initialized");
}
}
bool isInitialized() { return state::initialized; }
void pushContext(std::function<void()> callbackFunction, bool drawDefaultUI) {
// WARNING: code duplicated here and in screenshot.cpp
// Here, we create a new ImGui context sharing the same window and render
// with it, al in the midst of an existing ImGui frame. This is a fairly hacky
// thing to do within ImGui that only barely works, especially with v1.92 changes
// around contexts, dynamic fonts, and the GLFW ImGui backend. Currently, it requires
// some slight customization of the backend to even be possible.
//
// Useful resources:
// - https://github.com/ocornut/imgui/issues/8680 (and linked PR)
// Create a new context and push it on to the stack
ImGuiIO& oldIO = ImGui::GetIO(); // used to GLFW + OpenGL data to the new IO object
ImGuiContext* oldContext = ImGui::GetCurrentContext();
#ifdef IMGUI_HAS_DOCK
// WARNING this code may not currently work, recent versions of imgui have changed this functionality,
// and we do not regularly test with the docking branch.
ImGuiPlatformIO& oldPlatformIO = ImGui::GetPlatformIO();
#endif
render::engine->createNewImGuiContext();
ImGuiContext* newContext = ImGui::GetCurrentContext();
ImGuiIO& newIO = ImGui::GetIO();
ImPlotContext* newPlotContext = ImPlot::GetCurrentContext();
render::engine->updateImGuiContext(oldContext, &oldIO, newContext, &newIO);
#ifdef IMGUI_HAS_DOCK
// see warning above
ImGui::GetMainViewport()->PlatformHandle = oldPlatformIO.Viewports[0]->PlatformHandle;
#endif
ImGuizmo::PushContext();
contextStack.push_back(ContextEntry{newContext, newPlotContext, callbackFunction, drawDefaultUI});
internal::contextStackSize++;
if (contextStack.size() > 50) {
// Catch bugs with nested show()
exception("Uh oh, polyscope::show() was recusively MANY times (depth > 50), this is probably a bug. Perhaps "
"you are accidentally calling show() every time polyscope::userCallback executes?");
};
// Make sure the window is visible
render::engine->showWindow();
// Re-enter main loop until the context has been popped
size_t currentContextStackSize = contextStack.size();
// Helper lambda to perform cleanup of the context
auto cleanupContext = [&]() {
// Restore the previous context, if there was one
if (!contextStack.empty()) {
ImGui::SetCurrentContext(contextStack.back().context);
ImPlot::SetCurrentContext(contextStack.back().plotContext);
render::engine->updateImGuiContext(newContext, &newIO, oldContext, &oldIO);
ImGuizmo::PopContext();
}
// WARNING: code duplicated here and in screenshot.cpp
// Workaround overzealous ImGui assertion before destroying any inner context
// https://github.com/ocornut/imgui/pull/7175
newIO.BackendPlatformUserData = nullptr;
newIO.BackendRendererUserData = nullptr;
ImPlot::DestroyContext(newPlotContext);
ImGui::DestroyContext(newContext);
};
try {
while (contextStack.size() >= currentContextStackSize) {
sleepForFramerate();
mainLoopIteration();
// auto-exit if the window is closed
if (render::engine->windowRequestsClose()) {
popContext();
}
}
} catch (...) {
// Ensure cleanup happens even if an exception is thrown
// NOTE: we don't really guarantee exception safety in general, it's likely that things are broken if an excpetion
// was thrown. But this handles a few of the worst and most confusing cases.
popContext();
cleanupContext();
throw; // re-throw the exception after cleanup
}
cleanupContext();
}
void popContext() {
if (contextStack.empty()) {
exception("Called popContext() too many times");
return;
}
contextStack.pop_back();
internal::contextStackSize--;
}
ImGuiContext* getCurrentContext() { return contextStack.empty() ? nullptr : contextStack.back().context; }
void frameTick() {
checkInitialized();
// Do some sanity-checking around control flow and use of frameTick() / show()
if (contextStack.size() > 1) {
exception("Do not call frameTick() while show() is already looping the main loop.");
}
if (frameTickStack > 0) {
exception("You called frameTick() while a previous call was in the midst of executing. Do not re-enter frameTick() "
"or call it recursively.");
}
// == Logic for frame tick FPS limits
bool savedVsyncValue = false; // see below
bool needToRestoreVSyncValue = false; // need to save this, the setting could change during mainLoopIteration()
switch (options::frameTickLimitFPSMode) {
case LimitFPSMode::IgnoreLimits:
// Ugly workaround to preserve the API:
// We want vsync to be disabled if we're ignoring fps limits (otherwise the platform will potentially block on
// render swap to match the displays refresh rate). But it's currently a bool read in the render call and I don't
// want to change that API. So we temporarily set it to false and restore the value after. ONEDAY: when we have a
// major version update, change the API on the vsync setting to make this unecessary
savedVsyncValue = options::enableVSync;
options::enableVSync = false;
needToRestoreVSyncValue = true;
break;
case LimitFPSMode::BlockToHitTarget:
sleepForFramerate();
break;
case LimitFPSMode::SkipFramesToHitTarget:
if (shouldSkipFrameForFramerate()) {
return;
}
break;
}
frameTickStack++;
render::engine->showWindow();
mainLoopIteration();
if (needToRestoreVSyncValue) {
// restore saved value, see note above
options::enableVSync = savedVsyncValue;
}
frameTickStack--;
}
void requestRedraw() { redrawNextFrame = true; }
bool redrawRequested() { return redrawNextFrame; }
void drawStructures() {
// Draw all off the structures registered with polyscope
for (auto& catMap : state::structures) {
for (auto& s : catMap.second) {
s.second->draw();
}
}
// Also render any slice plane geometry
for (std::unique_ptr<SlicePlane>& s : state::slicePlanes) {
s->drawGeometry();
}
}
void drawStructuresDelayed() {
// "delayed" drawing allows structures to render things which should be rendered after most of the scene has been
// drawn
for (auto& catMap : state::structures) {
for (auto& s : catMap.second) {
s.second->drawDelayed();
}
}
}
namespace {
float dragDistSinceLastRelease = 0.0;
// State for delayed pick selection
bool pendingPickActive = false;
PickResult pendingPickResult;
float pendingPickTime = 0.0f;
void processInputEvents() {
ImGuiIO& io = ImGui::GetIO();
// RECALL: in ImGUI language, on MacOS "ctrl" == "cmd", so all the options
// below referring to ctrl really mean cmd on MacOS.
// If any mouse button is pressed, trigger a redraw
if (ImGui::IsAnyMouseDown()) {
requestRedraw();
}
bool widgetCapturedMouse = false;
// Handle scroll events for 3D view
if (state::doDefaultMouseInteraction) {
for (WeakHandle<Widget> wHandle : state::widgets) {
if (wHandle.isValid()) {
Widget& w = wHandle.get();
widgetCapturedMouse = w.interact();
if (widgetCapturedMouse) {
break;
}
}
}
// === Mouse inputs
if (!io.WantCaptureMouse && !widgetCapturedMouse) {
{ // Process scroll via "mouse wheel" (which might be a touchpad)
float xoffset = io.MouseWheelH;
float yoffset = io.MouseWheel;
float scrollOffset = yoffset;
float clipPlaneOffset = std::abs(xoffset) > std::abs(yoffset) ? xoffset : yoffset;
// NOTE: here we used to scroll according the to the larger of the two offsets (x or y)
// (there was a comment about 'shift swaps scroll on some platforms'). However, on many
// common machines (e.g. macs with touchpads), two finger scrolling produces both x and y
// offsets simultaneously, leading to jumpy zooms when an x was greater than a y.
// So now we just use the y offset always for zooming. (But still use either for clip plane shifting,
// which might involve intentionally holding shift)
bool scrollClipPlane = io.KeyShift && !io.KeyCtrl;
if (scrollClipPlane && clipPlaneOffset != 0.0f) {
view::processClipPlaneShift(clipPlaneOffset);
requestRedraw();
}
if (!scrollClipPlane && scrollOffset != 0.0f) {
view::processZoom(0.5 * scrollOffset);
requestRedraw();
}
}
{ // Process drags
bool dragLeft = ImGui::IsMouseDragging(0);
bool dragRight = !dragLeft && ImGui::IsMouseDragging(1); // left takes priority, so only one can be true
if (dragLeft || dragRight) {
glm::vec2 dragDelta{io.MouseDelta.x / view::windowWidth, -io.MouseDelta.y / view::windowHeight};
dragDistSinceLastRelease += std::abs(dragDelta.x);
dragDistSinceLastRelease += std::abs(dragDelta.y);
// exactly one of these will be true
bool isRotate = dragLeft && !io.KeyShift && !io.KeyCtrl;
bool isTranslate = (dragLeft && io.KeyShift && !io.KeyCtrl) || dragRight;
bool isDragZoom = dragLeft && io.KeyShift && io.KeyCtrl;
if (isDragZoom) {
view::processZoom(dragDelta.y * 5);
}
if (isRotate) {
glm::vec2 currPos{io.MousePos.x / view::windowWidth,
(view::windowHeight - io.MousePos.y) / view::windowHeight};
currPos = (currPos * 2.0f) - glm::vec2{1.0, 1.0};
if (std::abs(currPos.x) <= 1.0 && std::abs(currPos.y) <= 1.0) {
view::processRotate(currPos - 2.0f * dragDelta, currPos);
}
}
if (isTranslate) {
view::processTranslate(dragDelta);
}
}
}
{ // Click picks to select content onscreen
float dragIgnoreThreshold = 0.01;
bool anyModifierHeld = io.KeyShift || io.KeyCtrl || io.KeyAlt;
bool ctrlShiftHeld = io.KeyShift && io.KeyCtrl;
// NOTE: there is some extra 'pending' logic here, because we use double clicks to recenter the view, but we
// don't want a pick to trigger after the first click of a double click. To handle this, we delay applying
// picks until enough time has passed that a double click would have been registered.
// Check if enough time has passed for a pending pick to be applied
if (pendingPickActive) {
float elapsedSec = ImGui::GetTime() - pendingPickTime;
float pickDelaySec = ImGui::GetIO().MouseDoubleClickTime + 0.05f; // 50ms margin for safety
if (haveSelection() || elapsedSec >= pickDelaySec) {
// enough time has passed, apply the pending pick
setSelection(pendingPickResult);
pendingPickActive = false;
}
}
if (!anyModifierHeld && (io.MouseReleased[0] && io.MouseClickedLastCount[0] == 1)) {
// don't pick at the end of a long drag
if (dragDistSinceLastRelease < dragIgnoreThreshold) {
glm::vec2 screenCoords{io.MousePos.x, io.MousePos.y};
PickResult pickResult = pickAtScreenCoords(screenCoords);
// queue the pick for delayed application
pendingPickResult = pickResult;
pendingPickTime = ImGui::GetTime();
pendingPickActive = true;
}
}
// Clear pick
if (!anyModifierHeld && io.MouseReleased[1]) {
if (dragDistSinceLastRelease < dragIgnoreThreshold) {
resetSelection();
}
dragDistSinceLastRelease = 0.0;
pendingPickActive = false;
}
// Double-click or Ctrl-shift left-click to set new center
if ((io.MouseReleased[0] && io.MouseClickedLastCount[0] == 2) || (io.MouseReleased[0] && ctrlShiftHeld)) {
if (dragDistSinceLastRelease < dragIgnoreThreshold) {
glm::vec2 screenCoords{io.MousePos.x, io.MousePos.y};
view::processSetCenter(screenCoords);
pendingPickActive = false; // cancel any pending pick from the first click
}
}
}
}
}
// Reset the drag distance after any release
if (io.MouseReleased[0]) {
dragDistSinceLastRelease = 0.0;
}
// === Key-press inputs
if (!io.WantCaptureKeyboard) {
view::processKeyboardNavigation(io);
}
}
void renderSlicePlanes() {
for (std::unique_ptr<SlicePlane>& s : state::slicePlanes) {
s->draw();
}
}
void renderScene() {
render::engine->applyTransparencySettings();
render::engine->sceneBuffer->clearColor = {0., 0., 0.};
render::engine->sceneBuffer->clearAlpha = 0.;
render::engine->sceneBuffer->clear();
if (!render::engine->bindSceneBuffer()) return;
// If a view has never been set, this will set it to the home view
view::ensureViewValid();
if (!options::renderScene) return;
if (render::engine->getTransparencyMode() == TransparencyMode::Pretty) {
// Special depth peeling case: multiple render passes
// We will perform several "peeled" rounds of rendering in to the usual scene buffer. After each, we will manually
// composite in to the final scene buffer.
// Clear the final buffer explicitly since we will gradually composite in to it rather than just blitting directly
// as in normal rendering.
render::engine->sceneBufferFinal->clearColor = glm::vec3{0., 0., 0.};
render::engine->sceneBufferFinal->clearAlpha = 0;
render::engine->sceneBufferFinal->clear();
render::engine->setDepthMode(DepthMode::Less); // we need depth to be enabled for the clear below to do anything
render::engine->sceneDepthMinFrame->clear();
for (int iPass = 0; iPass < options::transparencyRenderPasses; iPass++) {
bool isRedraw = iPass > 0;
internal::renderPassIsRedraw = isRedraw;
render::engine->bindSceneBuffer();
render::engine->clearSceneBuffer();
render::engine->applyTransparencySettings();
drawStructures();
// Draw ground plane, slicers, etc
render::engine->groundPlane.draw(isRedraw);
if (!isRedraw) {
// Only on first pass (kinda weird, but works out, and doesn't really matter)
renderSlicePlanes();
}
render::engine->applyTransparencySettings();
drawStructuresDelayed();
// Composite the result of this pass in to the result buffer
render::engine->sceneBufferFinal->bind();
render::engine->setDepthMode(DepthMode::Disable);
render::engine->setBlendMode(BlendMode::AlphaUnder);
render::engine->compositePeel->draw();
// Update the minimum depth texture
render::engine->updateMinDepthTexture();
}
internal::renderPassIsRedraw = false; // reset to usual value
} else {
// Normal case: single render pass
internal::renderPassIsRedraw = false;
render::engine->applyTransparencySettings();
drawStructures();
render::engine->groundPlane.draw();
renderSlicePlanes();
render::engine->applyTransparencySettings();
drawStructuresDelayed();
render::engine->sceneBuffer->blitTo(render::engine->sceneBufferFinal.get());
}
}
void renderSceneToScreen() {
render::engine->bindDisplay();
if (options::debugDrawPickBuffer) {
// special debug draw
pick::evaluatePickQuery(-1, -1); // populate the buffer
render::engine->pickFramebuffer->blitTo(render::engine->displayBuffer.get());
} else {
render::engine->applyLightingTransform(render::engine->sceneColorFinal);
}
}
void purgeWidgets() {
// remove any widget objects which are no longer defined
state::widgets.erase(std::remove_if(state::widgets.begin(), state::widgets.end(),
[](const WeakHandle<Widget>& w) { return !w.isValid(); }),
state::widgets.end());
}
void userGuiBegin() {
ensureWindowWidthsSet();
ImVec2 userGuiLoc;
if (options::userGuiIsOnRightSide) {
// right side
userGuiLoc = ImVec2(view::windowWidth - (internal::rightWindowsWidth + internal::imguiStackMargin),
internal::imguiStackMargin);
ImGui::SetNextWindowSize(ImVec2(internal::rightWindowsWidth, 0.));
} else {
// left side
if (options::buildDefaultGuiPanels) {
userGuiLoc = ImVec2(internal::leftWindowsWidth + 2 * internal::imguiStackMargin, internal::imguiStackMargin);
} else {
userGuiLoc = ImVec2(internal::imguiStackMargin, internal::imguiStackMargin);
}
}
ImGui::PushID("user_callback");
ImGui::SetNextWindowPos(userGuiLoc);
ImGui::Begin("##Command UI", nullptr);
}
void userGuiEnd() {
if (options::userGuiIsOnRightSide) {
internal::lastWindowHeightUser =
internal::imguiStackMargin + ImGui::GetWindowHeight(); // TODO using deprecated function
internal::lastRightSideFreeX = view::windowWidth - internal::imguiStackMargin;
internal::lastRightSideFreeY = internal::lastWindowHeightUser;
} else {
internal::lastWindowHeightUser = 0;
internal::lastRightSideFreeX = view::windowWidth - internal::imguiStackMargin;
internal::lastRightSideFreeY = 0;
}
ImGui::End();
ImGui::PopID();
}
} // namespace
void buildPolyscopeGui() {
ensureWindowWidthsSet();
// Create window
ImGui::SetNextWindowPos(ImVec2(internal::imguiStackMargin, internal::imguiStackMargin));
ImGui::SetNextWindowSize(ImVec2(internal::leftWindowsWidth, 0.));
ImGui::Begin("Polyscope ", nullptr);
if (ImGui::Button(ICON_LC_HOUSE " Reset View")) {
view::flyToHomeView();
}
ImGui::SameLine();
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(1.0f, 0.0f));
if (ImGui::Button("Screenshot")) {
ScreenshotOptions options;
options.transparentBackground = options::screenshotTransparency;
options.includeUI = options::screenshotWithImGuiUI;
screenshot(options);
}
ImGui::SameLine();
if (ImGui::ArrowButton("##Option", ImGuiDir_Down)) {
ImGui::OpenPopup("ScreenshotOptionsPopup");
}
ImGui::PopStyleVar();
if (ImGui::BeginPopup("ScreenshotOptionsPopup")) {
ImGui::Checkbox("with transparency", &options::screenshotTransparency);
// ImGui::Checkbox("with UI", &options::screenshotWithImGuiUI); // temporarily disabled while broken
if (ImGui::BeginMenu("file format")) {
if (ImGui::MenuItem(".png", NULL, options::screenshotExtension == ".png")) options::screenshotExtension = ".png";
if (ImGui::MenuItem(".jpg", NULL, options::screenshotExtension == ".jpg")) options::screenshotExtension = ".jpg";
ImGui::EndMenu();
}
ImGui::EndPopup();
}
ImGui::SameLine();
if (ImGui::Button(ICON_LC_CIRCLE_QUESTION_MARK)) {
// do nothing, just want hover state
}
if (ImGui::IsItemHovered()) {
ImGui::SetNextWindowPos(
ImVec2(2 * internal::imguiStackMargin + internal::leftWindowsWidth, internal::imguiStackMargin));
ImGui::SetNextWindowSize(ImVec2(0., 0.));
// clang-format off
ImGui::Begin("Controls", NULL, ImGuiWindowFlags_NoTitleBar);
ImGui::TextUnformatted("View Navigation:");
ImGui::TextUnformatted(" Rotate: [left click drag]");
ImGui::TextUnformatted(" Translate: [shift] + [left click drag] OR [right click drag]");
ImGui::TextUnformatted(" Zoom: [scroll] OR [ctrl/cmd] + [shift] + [left click drag]");
ImGui::TextUnformatted(" To set the view orbit center, double-click OR hold");
ImGui::TextUnformatted(" [ctrl/cmd] + [shift] and [left click] in the scene.");
ImGui::TextUnformatted(" Save and restore camera poses via the system clipboard with");
ImGui::TextUnformatted(" [ctrl/cmd-c] and [ctrl/cmd-v].");
ImGui::TextUnformatted("\nMenu Navigation:");
ImGui::TextUnformatted(" Menu headers with a '>' can be clicked to collapse and expand.");
ImGui::TextUnformatted(" Use [ctrl/cmd] + [left click] to manually enter any numeric value");
ImGui::TextUnformatted(" via the keyboard.");
ImGui::TextUnformatted(" Press [space] to dismiss popup dialogs.");
ImGui::TextUnformatted("\nSelection:");
ImGui::TextUnformatted(" Select elements of a structure with [left click]. Data from");
ImGui::TextUnformatted(" that element will be shown on the right. Use [right click]");
ImGui::TextUnformatted(" to clear the selection.");
ImGui::End();
// clang-format on
}
// View options tree
view::buildViewGui();
// Appearance options tree
render::engine->buildEngineGui();
// Render options tree
ImGui::SetNextItemOpen(false, ImGuiCond_FirstUseEver);
if (ImGui::TreeNode("Render")) {
// fps display
ImGui::Text("Rolling: %.1f ms/frame (%.1f fps)", 1e-3f * rollingMainLoopDurationMicrosec,
1.e6f / rollingMainLoopDurationMicrosec);
ImGui::Text("Last: %.1f ms/frame (%.1f fps)", 1e-3f * lastMainLoopDurationMicrosec,
1.e6f / lastMainLoopDurationMicrosec);
bool isFrameTickShow = frameTickStack > 0;
if (isFrameTickShow) {
// build a little combo box to pick fps mode
constexpr std::array<LimitFPSMode, 3> limitFPSModeVals = {
LimitFPSMode::IgnoreLimits, LimitFPSMode::BlockToHitTarget, LimitFPSMode::SkipFramesToHitTarget};
auto to_string = [](LimitFPSMode x) -> std::string {
switch (x) {
case LimitFPSMode::IgnoreLimits:
return "ignore limits";
case LimitFPSMode::BlockToHitTarget:
return "block to hit target";
case LimitFPSMode::SkipFramesToHitTarget:
return "skip frames to hit target";
}
return ""; // unreachable
};
if (ImGui::BeginCombo("fps mode##frame tick limit fps mode", to_string(options::frameTickLimitFPSMode).c_str())) {
for (LimitFPSMode x : limitFPSModeVals) {
if (ImGui::Selectable(to_string(x).c_str(), options::frameTickLimitFPSMode == x)) {
options::frameTickLimitFPSMode = x;
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
}
ImGui::BeginDisabled(isFrameTickShow && options::frameTickLimitFPSMode == LimitFPSMode::IgnoreLimits);
ImGui::PushItemWidth(40 * options::uiScale);
if (ImGui::InputInt("max fps", &options::maxFPS, 0)) {
if (options::maxFPS < 1 && options::maxFPS != -1) {
options::maxFPS = -1;
}
}
ImGui::PopItemWidth();
ImGui::SameLine();
ImGui::Checkbox("vsync", &options::enableVSync);
ImGui::EndDisabled();
ImGui::TreePop();
}
ImGui::SetNextItemOpen(false, ImGuiCond_FirstUseEver);
if (ImGui::TreeNode("Debug")) {
if (ImGui::Button("Force refresh")) {
refresh();
}
ImGui::Checkbox("Show pick buffer", &options::debugDrawPickBuffer);
ImGui::Checkbox("Always redraw", &options::alwaysRedraw);
static bool showDebugTextures = false;
ImGui::Checkbox("Show debug textures", &showDebugTextures);
if (showDebugTextures) {
render::engine->showTextureInImGuiWindow("Scene", render::engine->sceneColor.get());
render::engine->showTextureInImGuiWindow("Scene Final", render::engine->sceneColorFinal.get());
}
ImGui::TreePop();
}
internal::lastWindowHeightPolyscope = ImGui::GetWindowHeight();
internal::leftWindowsWidth = ImGui::GetWindowWidth();
ImGui::End();
}
void buildStructureGui() {
ensureWindowWidthsSet();
// Create window
ImGui::SetNextWindowPos(
ImVec2(internal::imguiStackMargin, internal::lastWindowHeightPolyscope + 2 * internal::imguiStackMargin));
ImGui::SetNextWindowSize(ImVec2(internal::leftWindowsWidth, view::windowHeight - internal::lastWindowHeightPolyscope -
3 * internal::imguiStackMargin));
ImGui::Begin("Structures", nullptr);
// only show groups if there are any
if (state::groups.size() > 0) {
if (ImGui::CollapsingHeader("Groups", ImGuiTreeNodeFlags_DefaultOpen)) {
for (auto& x : state::groups) {
if (x.second->isRootGroup()) {
x.second->buildUI();
}
}
}
}
// groups have an option to hide structures from this list; assemble a list of structures to skip
std::unordered_set<Structure*> structuresToSkip;
for (auto& x : state::groups) {
x.second->appendStructuresToSkip(structuresToSkip);
}
for (auto& catMapEntry : state::structures) {
std::string catName = catMapEntry.first;
std::map<std::string, std::unique_ptr<Structure>>& structureMap = catMapEntry.second;
ImGui::PushID(catName.c_str()); // ensure there are no conflicts with
// identically-named labels
// Build the structure's UI
ImGui::SetNextItemOpen(structureMap.size() > 0, ImGuiCond_FirstUseEver);
if (ImGui::CollapsingHeader((catName + " (" + std::to_string(structureMap.size()) + ")").c_str())) {
// Draw shared GUI elements for all instances of the structure
if (structureMap.size() > 0) {
structureMap.begin()->second->buildSharedStructureUI();
}
int32_t skipCount = 0;
for (auto& x : structureMap) {
ImGui::SetNextItemOpen(structureMap.size() <= 8,
ImGuiCond_FirstUseEver); // closed by default if more than 8
if (structuresToSkip.find(x.second.get()) != structuresToSkip.end()) {
skipCount++;
continue;
}
x.second->buildUI();
}
if (skipCount > 0) {
ImGui::Text(" (skipped %d hidden structures)", skipCount);
}
}
ImGui::PopID();
}
internal::leftWindowsWidth = ImGui::GetWindowWidth();
ImGui::End();
}
void buildPickGui() {
ensureWindowWidthsSet();
if (haveSelection()) {
ImGui::SetNextWindowPos(ImVec2(view::windowWidth - (internal::rightWindowsWidth + internal::imguiStackMargin),
internal::lastRightSideFreeY + internal::imguiStackMargin));
ImGui::SetNextWindowSize(ImVec2(internal::rightWindowsWidth, 0.));
ImGui::Begin("Selection", nullptr);
PickResult selection = getSelection();
ImGui::Text("screen coordinates: (%.2f,%.2f) depth: %g", selection.screenCoords.x, selection.screenCoords.y,
selection.depth);
ImGui::Text("world position: <%g, %g, %g>", selection.position.x, selection.position.y, selection.position.z);
ImGui::NewLine();