-
Notifications
You must be signed in to change notification settings - Fork 232
Expand file tree
/
Copy pathpolyscope.cpp
More file actions
1449 lines (1155 loc) · 43.9 KB
/
polyscope.cpp
File metadata and controls
1449 lines (1155 loc) · 43.9 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 "imgui.h"
#include "implot.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;
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
float imguiStackMargin = 10;
float lastWindowHeightPolyscope = 200;
float lastWindowHeightUser = 200;
constexpr float INITIAL_LEFT_WINDOWS_WIDTH = 305;
constexpr float INITIAL_RIGHT_WINDOWS_WIDTH = 500;
float leftWindowsWidth = -1.;
float rightWindowsWidth = -1.;
auto lastMainLoopIterTime = std::chrono::steady_clock::now();
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() {
leftWindowsWidth = INITIAL_LEFT_WINDOWS_WIDTH * options::uiScale;
rightWindowsWidth = INITIAL_RIGHT_WINDOWS_WIDTH * options::uiScale;
}
void ensureWindowWidthsSet() {
if (leftWindowsWidth <= 0. || rightWindowsWidth <= 0.) {
setInitialWindowWidths();
}
}
// 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];
}
} // 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->initializeImGui();
// 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});
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
// Create a new context and push it on to the stack
ImGuiContext* newContext = ImGui::CreateContext();
ImPlotContext* newPlotContext = ImPlot::CreateContext();
ImGuiIO& oldIO = ImGui::GetIO(); // used to GLFW + OpenGL data to the new IO object
#ifdef IMGUI_HAS_DOCK
ImGuiPlatformIO& oldPlatformIO = ImGui::GetPlatformIO();
#endif
ImGui::SetCurrentContext(newContext);
ImPlot::SetCurrentContext(newPlotContext);
#ifdef IMGUI_HAS_DOCK
// Propagate GLFW window handle to new context
ImGui::GetMainViewport()->PlatformHandle = oldPlatformIO.Viewports[0]->PlatformHandle;
#endif
ImGui::GetIO().BackendPlatformUserData = oldIO.BackendPlatformUserData;
ImGui::GetIO().BackendRendererUserData = oldIO.BackendRendererUserData;
render::engine->configureImGui();
contextStack.push_back(ContextEntry{newContext, newPlotContext, callbackFunction, drawDefaultUI});
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();
while (contextStack.size() >= currentContextStackSize) {
// The windowing system will let the main loop busy-loop on some platforms. Make sure that doesn't happen.
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 - lastMainLoopIterTime).count() <
microsecPerLoop) {
std::this_thread::yield();
currTime = std::chrono::steady_clock::now();
}
}
lastMainLoopIterTime = std::chrono::steady_clock::now();
mainLoopIteration();
// auto-exit if the window is closed
if (render::engine->windowRequestsClose()) {
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
ImGui::SetCurrentContext(newContext);
ImPlot::SetCurrentContext(newPlotContext);
ImGui::GetIO().BackendPlatformUserData = nullptr;
ImGui::GetIO().BackendRendererUserData = nullptr;
ImPlot::DestroyContext(newPlotContext);
ImGui::DestroyContext(newContext);
// Restore the previous context, if there was one
if (!contextStack.empty()) {
ImGui::SetCurrentContext(contextStack.back().context);
ImPlot::SetCurrentContext(contextStack.back().plotContext);
}
}
void popContext() {
if (contextStack.empty()) {
exception("Called popContext() too many times");
return;
}
contextStack.pop_back();
}
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.");
}
frameTickStack++;
// Make sure we're visible
render::engine->showWindow();
// All-imporant main loop iteration
mainLoopIteration();
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;
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)
double xoffset = io.MouseWheelH;
double yoffset = io.MouseWheel;
if (xoffset != 0 || yoffset != 0) {
requestRedraw();
// On some setups, shift flips the scroll direction, so take the max
// scrolling in any direction
double maxScroll = xoffset;
if (std::abs(yoffset) > std::abs(xoffset)) {
maxScroll = yoffset;
}
// Pass camera commands to the camera
if (maxScroll != 0.0) {
bool scrollClipPlane = io.KeyShift && !io.KeyCtrl;
bool relativeZoom = io.KeyShift && io.KeyCtrl;
if (scrollClipPlane) {
view::processClipPlaneShift(maxScroll);
} else {
view::processZoom(maxScroll, relativeZoom);
}
}
}
}
{ // 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, true);
}
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
float dragIgnoreThreshold = 0.01;
bool anyModifierHeld = io.KeyShift || io.KeyCtrl || io.KeyAlt;
bool ctrlShiftHeld = io.KeyShift && io.KeyCtrl;
if (!anyModifierHeld && io.MouseReleased[0]) {
// 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);
setSelection(pickResult);
}
}
// Clear pick
if (!anyModifierHeld && io.MouseReleased[1]) {
if (dragDistSinceLastRelease < dragIgnoreThreshold) {
resetSelection();
}
dragDistSinceLastRelease = 0.0;
}
// Ctrl-shift left-click to set new center
if (ctrlShiftHeld && io.MouseReleased[0]) {
if (dragDistSinceLastRelease < dragIgnoreThreshold) {
glm::vec2 screenCoords{io.MousePos.x, io.MousePos.y};
view::processSetCenter(screenCoords);
}
}
}
}
}
// 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++) {
render::engine->bindSceneBuffer();
render::engine->clearSceneBuffer();
render::engine->applyTransparencySettings();
drawStructures();
// Draw ground plane, slicers, etc
bool isRedraw = iPass > 0;
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();
}
} else {
// Normal case: single render pass
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 - (rightWindowsWidth + imguiStackMargin), imguiStackMargin);
ImGui::SetNextWindowSize(ImVec2(rightWindowsWidth, 0.));
} else {
// left side
if (options::buildDefaultGuiPanels) {
userGuiLoc = ImVec2(leftWindowsWidth + 3 * imguiStackMargin, imguiStackMargin);
} else {
userGuiLoc = ImVec2(imguiStackMargin, imguiStackMargin);
}
}
ImGui::PushID("user_callback");
ImGui::SetNextWindowPos(userGuiLoc);
ImGui::Begin("##Command UI", nullptr);
}
void userGuiEnd() {
if (options::userGuiIsOnRightSide) {
rightWindowsWidth = INITIAL_RIGHT_WINDOWS_WIDTH * options::uiScale;
lastWindowHeightUser = imguiStackMargin + ImGui::GetWindowHeight();
} else {
lastWindowHeightUser = 0;
}
ImGui::End();
ImGui::PopID();
}
} // namespace
void buildPolyscopeGui() {
ensureWindowWidthsSet();
// Create window
static bool showPolyscopeWindow = true;
ImGui::SetNextWindowPos(ImVec2(imguiStackMargin, imguiStackMargin));
ImGui::SetNextWindowSize(ImVec2(leftWindowsWidth, 0.));
ImGui::Begin("Polyscope", &showPolyscopeWindow);
if (ImGui::Button("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);
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("Controls")) {
// do nothing, just want hover state
}
if (ImGui::IsItemHovered()) {
ImGui::SetNextWindowPos(ImVec2(2 * imguiStackMargin + leftWindowsWidth, 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(" Use [ctrl/cmd-c] and [ctrl/cmd-v] to save and restore camera poses");
ImGui::TextUnformatted(" via the clipboard.");
ImGui::TextUnformatted(" Hold [ctrl/cmd] + [shift] and [left click] in the scene to set the");
ImGui::TextUnformatted(" orbit center.");
ImGui::TextUnformatted(" Hold [ctrl/cmd] + [shift] and scroll to zoom towards the center.");
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
ImGui::Text("Rolling: %.1f ms/frame (%.1f fps)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("Last: %.1f ms/frame (%.1f fps)", ImGui::GetIO().DeltaTime * 1000.f, 1.f / ImGui::GetIO().DeltaTime);
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::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();
}
lastWindowHeightPolyscope = imguiStackMargin + ImGui::GetWindowHeight();
leftWindowsWidth = ImGui::GetWindowWidth();
ImGui::End();
}
void buildStructureGui() {
ensureWindowWidthsSet();
// Create window
static bool showStructureWindow = true;
ImGui::SetNextWindowPos(ImVec2(imguiStackMargin, lastWindowHeightPolyscope + 2 * imguiStackMargin));
ImGui::SetNextWindowSize(
ImVec2(leftWindowsWidth, view::windowHeight - lastWindowHeightPolyscope - 3 * imguiStackMargin));
ImGui::Begin("Structures", &showStructureWindow);
// 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();
}
leftWindowsWidth = ImGui::GetWindowWidth();
ImGui::End();
}
void buildPickGui() {
ensureWindowWidthsSet();
if (haveSelection()) {
ImGui::SetNextWindowPos(ImVec2(view::windowWidth - (rightWindowsWidth + imguiStackMargin),
2 * imguiStackMargin + lastWindowHeightUser));
ImGui::SetNextWindowSize(ImVec2(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();
ImGui::TextUnformatted((selection.structureType + ": " + selection.structureName).c_str());
ImGui::Separator();
if (selection.structureHandle.isValid()) {
selection.structureHandle.get().buildPickUI(selection);
} else {
// this is a paranoid check, it _should_ never happen since we
// clear the selection when a structure is deleted
ImGui::TextUnformatted("ERROR: INVALID STRUCTURE");
}
rightWindowsWidth = ImGui::GetWindowWidth();
ImGui::End();
}
}
void buildUserGuiAndInvokeCallback() {
if (!options::invokeUserCallbackForNestedShow && (contextStack.size() + frameTickStack) > 2) {
return;
}
if (state::userCallback) {
bool beganUserGUI = false;
if (options::buildGui && options::openImGuiWindowForUserCallback) {
userGuiBegin();
beganUserGUI = true;
}
state::userCallback();
if (beganUserGUI) {
userGuiEnd();
} else {
lastWindowHeightUser = imguiStackMargin;
}
} else {
lastWindowHeightUser = imguiStackMargin;
}
}
void draw(bool withUI, bool withContextCallback) {
processLazyProperties();
// Update buffer and context
render::engine->makeContextCurrent();
render::engine->bindDisplay();
render::engine->setBackgroundColor({0., 0., 0.});
render::engine->setBackgroundAlpha(0);
render::engine->clearDisplay();
if (withUI) {
render::engine->ImGuiNewFrame();
processInputEvents();
view::updateFlight();
showDelayedWarnings();
}
// Build the GUI components
if (withUI) {
if (contextStack.back().drawDefaultUI) {
// Note: It is important to build the user GUI first, because it is likely that callbacks there will modify
// polyscope data. If we do these modifications happen later in the render cycle, they might invalidate data which
// is necessary when ImGui::Render() happens below.
buildUserGuiAndInvokeCallback();
if (options::buildGui) {
if (options::buildDefaultGuiPanels) {
buildPolyscopeGui();
buildStructureGui();
buildPickGui();
}
for (WeakHandle<Widget> wHandle : state::widgets) {
if (wHandle.isValid()) {
Widget& w = wHandle.get();
w.buildGUI();
}
}
}
}
}
// Execute the context callback, if there is one.
// This callback is a Polyscope implementation detail, which is distinct from the userCallback (which gets called
// above)
if (withContextCallback && contextStack.back().callback) {
(contextStack.back().callback)();
}
processLazyProperties();
// Draw structures in the scene
if (redrawNextFrame || options::alwaysRedraw) {
renderScene();
redrawNextFrame = false;
}
renderSceneToScreen();
// Draw the GUI
if (withUI) {
// render widgets
render::engine->bindDisplay();
for (WeakHandle<Widget> wHandle : state::widgets) {
if (wHandle.isValid()) {
Widget& w = wHandle.get();
w.draw();
}
}
render::engine->bindDisplay();
render::engine->ImGuiRender();
}
}
void mainLoopIteration() {
processLazyProperties();
processLazyPropertiesOutsideOfImGui();
render::engine->makeContextCurrent();
render::engine->updateWindowSize();
// Process UI events
render::engine->pollEvents();
// Housekeeping
purgeWidgets();
// Rendering
draw();
render::engine->swapDisplayBuffers();
}
void show(size_t forFrames) {
if (!state::initialized) {
exception("must initialize Polyscope with polyscope::init() before calling polyscope::show().");
}
if (isHeadless() && forFrames == 0) {
info("You called show() while in headless mode. In headless mode there is no display to create windows on. By "
"default, the show() call will block indefinitely. If you did not mean to run in headless mode, check the "
"initialization settings. Otherwise, be sure to set a callback to make something happen while polyscope is "
"showing the UI, or use functions like screenshot() to render directly without calling show().");
}
unshowRequested = false;
// the popContext() doesn't quit until _after_ the last frame, so we need to decrement by 1 to get the count right
if (forFrames > 0) forFrames--;
auto checkFrames = [&]() {
if (forFrames == 0 || unshowRequested) {
popContext();
} else {
forFrames--;
}
};
if (options::giveFocusOnShow) {