-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathcamera.cpp
More file actions
803 lines (695 loc) · 25.5 KB
/
camera.cpp
File metadata and controls
803 lines (695 loc) · 25.5 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
/*
* Copyright (c) 2023-2026, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-FileCopyrightText: Copyright (c) 2023-2026, NVIDIA CORPORATION.
* SPDX-License-Identifier: Apache-2.0
*/
#include <fstream>
#include <sstream>
#include <fmt/format.h>
#include <imgui/imgui.h>
#include <tinygltf/json.hpp>
#include <nvutils/camera_manipulator.hpp>
#include <nvutils/logger.hpp>
#include <nvutils/file_operations.hpp>
#include <nvgui/property_editor.hpp>
#include <nvgui/tooltip.hpp>
#include <nvgui/fonts.hpp>
#include "camera.hpp"
#ifdef _MSC_VER
#define SAFE_SSCANF sscanf_s
#else
#define SAFE_SSCANF sscanf
#endif
using nlohmann::json;
namespace PE = nvgui::PropertyEditor;
//--------------------------------------------------------------------------------------------------
// Holds all saved cameras in a vector of Cameras
// - The first camera in the list is the HOME camera, the one that was set before this is called.
// - The update function will check if something has changed and will save the JSON to disk, only
// once in a while.
// - Adding a camera will be added only if it is different from all other saved cameras
// - load/save Setting will load next to the executable, the "jsonFilename" + ".json"
//
struct CameraPresetManager
{
CameraPresetManager() {}
~CameraPresetManager() {};
static CameraPresetManager& getInstance()
{
static CameraPresetManager instance;
return instance;
}
// update setting, load or save
void update(std::shared_ptr<nvutils::CameraManipulator> cameraManip)
{
// Push the HOME camera and load default setting
if(m_cameras.empty())
{
m_cameras.emplace_back(cameraManip->getCamera());
}
if(m_doLoadSetting)
loadSetting(cameraManip);
// Save settings (with a delay after the last modification, so we don't spam disk too much)
auto& IO = ImGui::GetIO();
if(m_settingsDirtyTimer > 0.0f)
{
m_settingsDirtyTimer -= IO.DeltaTime;
if(m_settingsDirtyTimer <= 0.0f)
{
saveSetting(cameraManip);
m_settingsDirtyTimer = 0.0f;
}
}
}
// Clear all cameras except the HOME
void removedSavedCameras()
{
if(m_cameras.size() > 1)
m_cameras.erase(m_cameras.begin() + 1, m_cameras.end());
}
void setCameraJsonFile(const std::filesystem::path& filename)
{
std::filesystem::path jsonFile = nvutils::getExecutablePath().parent_path() / filename.filename();
jsonFile.replace_extension(".json");
m_jsonFilename = std::move(jsonFile);
m_doLoadSetting = true;
removedSavedCameras();
}
void setHomeCamera(const nvutils::CameraManipulator::Camera& camera)
{
if(m_cameras.empty())
m_cameras.resize(1);
m_cameras[0] = camera;
}
// Adding a camera only if it different from all the saved ones
void addCamera(const nvutils::CameraManipulator::Camera& camera)
{
bool unique = true;
for(const nvutils::CameraManipulator::Camera& c : m_cameras)
{
if(c == camera)
{
unique = false;
break;
}
}
if(unique)
{
m_cameras.emplace_back(camera);
markJsonSettingsDirty();
}
}
// Removing a camera
void removeCamera(int delete_item)
{
m_cameras.erase(m_cameras.begin() + delete_item);
markJsonSettingsDirty();
}
void markJsonSettingsDirty()
{
if(m_settingsDirtyTimer <= 0.0f)
m_settingsDirtyTimer = 0.1f;
}
template <typename T>
bool getJsonValue(const json& j, const std::string& name, T& value)
{
auto fieldIt = j.find(name);
if(fieldIt != j.end())
{
value = (*fieldIt);
return true;
}
LOGW("Could not find JSON field %s", name.c_str());
return false;
}
template <typename T>
bool getJsonArray(const json& j, const std::string& name, T& value)
{
auto fieldIt = j.find(name);
if(fieldIt != j.end())
{
value = T((*fieldIt).begin(), (*fieldIt).end());
return true;
}
LOGW("Could not find JSON field %s", name.c_str());
return false;
}
void loadSetting(std::shared_ptr<nvutils::CameraManipulator> cameraM)
{
if(m_jsonFilename.empty())
{
// Default name
m_jsonFilename = nvutils::getExecutablePath().replace_extension(".json");
}
if(m_cameras.empty() || m_doLoadSetting == false)
return;
const glm::vec2& currentClipPlanes = cameraM->getClipPlanes();
try
{
m_doLoadSetting = false;
std::ifstream i(m_jsonFilename);
if(!i.is_open())
return;
// Parsing the file
json j;
i >> j;
// Temp
int iVal;
float fVal;
std::vector<float> vfVal;
// Settings
if(getJsonValue(j, "mode", iVal))
cameraM->setMode(static_cast<nvutils::CameraManipulator::Modes>(iVal));
if(getJsonValue(j, "speed", fVal))
cameraM->setSpeed(fVal);
if(getJsonValue(j, "anim_duration", fVal))
cameraM->setAnimationDuration(fVal);
// All cameras
std::vector<json> cc;
getJsonArray(j, "cameras", cc);
for(auto& c : cc)
{
nvutils::CameraManipulator::Camera camera;
if(getJsonArray(c, "eye", vfVal))
camera.eye = {vfVal[0], vfVal[1], vfVal[2]};
if(getJsonArray(c, "ctr", vfVal))
camera.ctr = {vfVal[0], vfVal[1], vfVal[2]};
if(getJsonArray(c, "up", vfVal))
camera.up = {vfVal[0], vfVal[1], vfVal[2]};
if(getJsonValue(c, "fov", fVal))
camera.fov = fVal;
if(getJsonArray(c, "clip", vfVal))
camera.nearFar = {vfVal[0], vfVal[1]};
else
camera.nearFar = currentClipPlanes; // For old JSON files that didn't have clip planes saved
if(getJsonArray(c, "orthMag", vfVal))
camera.orthMag = {vfVal[0], vfVal[1]};
if(getJsonValue(c, "projectionType", iVal))
camera.projectionType = static_cast<nvutils::CameraManipulator::ProjectionType>(iVal);
addCamera(camera);
}
i.close();
}
catch(...)
{
return;
}
}
void saveSetting(std::shared_ptr<nvutils::CameraManipulator>& cameraManip)
{
if(m_jsonFilename.empty())
return;
try
{
json j;
j["mode"] = cameraManip->getMode();
j["speed"] = cameraManip->getSpeed();
j["anim_duration"] = cameraManip->getAnimationDuration();
// Save all extra cameras
json cc = json::array();
for(size_t n = 1; n < m_cameras.size(); n++)
{
auto& c = m_cameras[n];
json jo = json::object();
jo["eye"] = std::vector<float>{c.eye.x, c.eye.y, c.eye.z};
jo["up"] = std::vector<float>{c.up.x, c.up.y, c.up.z};
jo["ctr"] = std::vector<float>{c.ctr.x, c.ctr.y, c.ctr.z};
jo["fov"] = c.fov;
jo["clip"] = std::vector<float>{c.nearFar.x, c.nearFar.y};
jo["orthMag"] = std::vector<float>{c.orthMag.x, c.orthMag.y};
jo["projectionType"] = static_cast<int>(c.projectionType);
cc.push_back(jo);
}
j["cameras"] = cc;
std::ofstream o(m_jsonFilename);
if(o.is_open())
{
o << j.dump(2) << std::endl;
o.close();
}
}
catch(const std::exception& e)
{
LOGE("Could not save camera settings to %s: %s\n", nvutils::utf8FromPath(m_jsonFilename).c_str(), e.what());
}
}
// Holds all cameras. [0] == HOME
std::vector<nvutils::CameraManipulator::Camera> m_cameras{};
float m_settingsDirtyTimer{0};
std::filesystem::path m_jsonFilename{};
bool m_doLoadSetting{true};
};
// Create a more compact button bar with better spacing
static float s_buttonSpacing = 4.0f;
// Calls PropertyEditor::begin() and sets the second column to auto-stretch.
static bool PeBeginAutostretch(const char* label)
{
if(!PE::begin(label, ImGuiTableFlags_SizingFixedFit))
return false;
ImGui::TableSetupColumn("Property");
ImGui::TableSetupColumn("Value", ImGuiTableColumnFlags_WidthStretch);
return true;
}
//--------------------------------------------------------------------------------------------------
// Quick Actions Bar with icon buttons
//
static bool QuickActionsBar(std::shared_ptr<nvutils::CameraManipulator> cameraM, nvutils::CameraManipulator::Camera& camera)
{
bool changed = false;
// We make the default button color match the background here so that it
// looks the same as in NavigationSettingsSection.
ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyle().Colors[ImGuiCol_ChildBg]);
// Home button
if(ImGui::Button(ICON_MS_HOME))
{
camera = CameraPresetManager::getInstance().m_cameras[0];
changed = true;
}
nvgui::tooltip("Reset to home camera position");
// Add/Save camera button
ImGui::SameLine(0, s_buttonSpacing);
if(ImGui::Button(ICON_MS_ADD_A_PHOTO))
{
CameraPresetManager::getInstance().addCamera(cameraM->getCamera());
}
nvgui::tooltip("Save current camera position");
// Copy button
ImGui::SameLine(0, s_buttonSpacing);
if(ImGui::Button(ICON_MS_CONTENT_COPY))
{
std::string text = camera.getString();
ImGui::SetClipboardText(text.c_str());
}
nvgui::tooltip("Copy camera state to clipboard");
// Paste button
const char* pPastedString;
ImGui::SameLine(0, s_buttonSpacing);
if(ImGui::Button(ICON_MS_CONTENT_PASTE) && (pPastedString = ImGui::GetClipboardText()))
{
std::string text(pPastedString);
changed = camera.setFromString(text);
}
nvgui::tooltip("Paste camera state from clipboard");
// Help button, right-aligned
const float button_size = ImGui::CalcTextSize(ICON_MS_HELP).x + ImGui::GetStyle().FramePadding.x * 2.f;
ImGui::SameLine(ImGui::GetContentRegionMax().x - button_size, 0.0f);
if(ImGui::Button(ICON_MS_HELP))
{
ImGui::OpenPopup("Camera Help");
}
nvgui::tooltip("Show camera controls help");
ImGui::PopStyleColor();
// Help popup
if(ImGui::BeginPopupModal("Camera Help", nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("Camera Controls:");
ImGui::BulletText("Left Mouse: Orbit/Pan/Dolly (depends on mode)");
ImGui::BulletText("Right Mouse: Look around");
ImGui::BulletText("Middle Mouse: Pan");
ImGui::BulletText("Mouse Wheel: Dolly / Shift+Wheel: Zoom");
ImGui::Indent();
ImGui::TextColored(ImVec4(0.7f, 0.7f, 0.7f, 1.0f), "Perspective: Changes FOV");
ImGui::TextColored(ImVec4(0.7f, 0.7f, 0.7f, 1.0f), "Orthographic: Changes viewport size");
ImGui::Unindent();
ImGui::BulletText("WASD: Move camera");
ImGui::BulletText("Q/E: Roll camera");
ImGui::Spacing();
ImGui::Text("Navigation Modes:");
ImGui::BulletText("Examine: Orbit around center point");
ImGui::BulletText("Fly: Free movement in 3D space");
ImGui::BulletText("Walk: Movement constrained to horizontal plane");
ImGui::Spacing();
ImGui::Text("Projection Types:");
ImGui::BulletText("Perspective: Objects get smaller with distance");
ImGui::BulletText("Orthographic: Parallel projection, no size change");
if(ImGui::Button("Close", ImVec2(120, 0)))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
return changed;
}
//--------------------------------------------------------------------------------------------------
// Camera Presets Grid with icons
//
static bool PresetsSection(std::shared_ptr<nvutils::CameraManipulator> cameraM, nvutils::CameraManipulator::Camera& camera)
{
bool changed = false;
auto& presetManager = CameraPresetManager::getInstance();
int buttonsCount = (int)presetManager.m_cameras.size();
float windowVisibleX2 = ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x;
if(buttonsCount == 1)
ImGui::TextDisabled(" - No saved cameras");
// Display saved cameras
int delete_item = -1;
std::string thisLabel = "#1";
std::string nextLabel;
for(int n = 1; n < buttonsCount; n++)
{
nextLabel = fmt::format("#{}", n + 1);
ImGui::PushID(n);
if(ImGui::Button(thisLabel.c_str()))
{
camera = presetManager.m_cameras[n];
changed = true;
}
// Middle click to delete
if(ImGui::IsItemHovered() && ImGui::GetIO().MouseClicked[ImGuiMouseButton_Middle])
delete_item = n;
// Hover tooltip with position info and deletion instruction
const auto& cam = presetManager.m_cameras[n];
std::string tooltip =
fmt::format("Camera #{}\n({:.1f}, {:.1f}, {:.1f})\nMiddle click to delete", n, cam.eye.x, cam.eye.y, cam.eye.z);
nvgui::tooltip(tooltip.c_str());
// Auto-wrap buttons
float last_button_x2 = ImGui::GetItemRectMax().x;
float next_button_x2 =
last_button_x2 + s_buttonSpacing + ImGui::CalcTextSize(nextLabel.c_str()).x + ImGui::GetStyle().FramePadding.x * 2.f;
if(n + 1 < buttonsCount && next_button_x2 < windowVisibleX2)
ImGui::SameLine(0, s_buttonSpacing);
thisLabel = std::move(nextLabel);
ImGui::PopID();
}
// Delete camera if requested
if(delete_item > 0)
{
presetManager.removeCamera(delete_item);
}
return changed;
}
//--------------------------------------------------------------------------------------------------
// Navigation Settings Section: Mode (examine, fly, walk), Speed
//
static bool NavigationSettingsSection(std::shared_ptr<nvutils::CameraManipulator> cameraM)
{
bool changed = false;
ImGui::Separator();
// Dear ImGui in v1.92 has a FIXME where it doesn't add 1px of spacing after separators
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 1.f);
auto mode = cameraM->getMode();
auto speed = cameraM->getSpeed();
auto duration = static_cast<float>(cameraM->getAnimationDuration());
// Change the button color to show the one that's currently active, and to
// make the other ones match the color of the background.
ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyle().Colors[ImGuiCol_Button]);
auto setColor = [&](bool selected) {
ImGui::GetStyle().Colors[ImGuiCol_Button] =
selected ? ImGui::GetStyle().Colors[ImGuiCol_ButtonActive] : ImGui::GetStyle().Colors[ImGuiCol_ChildBg];
};
// Left-aligned navigation buttons
setColor(mode == nvutils::CameraManipulator::Modes::Examine);
if(ImGui::Button(ICON_MS_ORBIT))
{
cameraM->setMode(nvutils::CameraManipulator::Modes::Examine);
changed = true;
}
nvgui::tooltip("Orbit around a point of interest");
ImGui::SameLine(0, s_buttonSpacing);
setColor(mode == nvutils::CameraManipulator::Modes::Fly);
if(ImGui::Button(ICON_MS_FLIGHT))
{
cameraM->setMode(nvutils::CameraManipulator::Modes::Fly);
changed = true;
}
nvgui::tooltip("Fly: Free camera movement");
ImGui::SameLine(0, s_buttonSpacing);
setColor(mode == nvutils::CameraManipulator::Modes::Walk);
if(ImGui::Button(ICON_MS_DIRECTIONS_WALK))
{
cameraM->setMode(nvutils::CameraManipulator::Modes::Walk);
changed = true;
}
nvgui::tooltip("Walk: Stay on a horizontal plane");
ImGui::PopStyleColor();
const bool showSettings = (mode == nvutils::CameraManipulator::Modes::Fly || mode == nvutils::CameraManipulator::Modes::Walk);
// Speed and transition controls (only shown when fly or walk is selected)
if(showSettings)
{
if(PeBeginAutostretch("##Speed"))
{
// ImGuiSliderFlags_Logarithmic requires a value range for its scaling to work.
const float speedMin = 1e-3f;
const float speedMax = 1e+3f;
changed |= PE::DragFloat("Speed", &speed, 2e-4f * (speedMax - speedMin), speedMin, speedMax, "%.2f",
ImGuiSliderFlags_Logarithmic, "Speed of camera movement");
cameraM->setSpeed(speed);
PE::end();
}
}
return false;
}
//--------------------------------------------------------------------------------------------------
// Camera Position Section : Eye, Center, Up vectors
//
static bool PositionSection(std::shared_ptr<nvutils::CameraManipulator> cameraM,
nvutils::CameraManipulator::Camera& camera,
ImGuiTreeNodeFlags flag = ImGuiTreeNodeFlags_None)
{
bool changed = false;
// We'll ignore changes during animation (but don't want to ignore other
// changes), so we track changes locally and decide whether to commit them
// at the end:
bool myChanged = false;
if(ImGui::TreeNodeEx("Position", flag))
{
if(PeBeginAutostretch("##Position"))
{
myChanged |= PE::InputFloat3("Eye", &camera.eye.x);
myChanged |= PE::InputFloat3("Center", &camera.ctr.x);
myChanged |= PE::InputFloat3("Up", &camera.up.x);
PE::end();
}
ImGui::TreePop();
}
if(!cameraM->isAnimated()) // Ignore changes during animation
{
changed |= myChanged;
}
return changed;
}
//--------------------------------------------------------------------------------------------------
// Projection Settings Section: projection type, field of view, orthographic size, Z-clip planes
//
static bool ProjectionSettingsSection(std::shared_ptr<nvutils::CameraManipulator> cameraManip,
nvutils::CameraManipulator::Camera& camera,
ImGuiTreeNodeFlags flag = ImGuiTreeNodeFlags_None)
{
bool changed = false;
if(ImGui::TreeNodeEx("Projection", flag))
{
if(PeBeginAutostretch("##Projection"))
{
// Projection type selector
changed |= PE::entry("Type", [&] {
const bool isPerspective = (camera.projectionType == nvutils::CameraManipulator::ProjectionType::Perspective);
if(ImGui::RadioButton("Perspective", isPerspective))
{
if(!isPerspective)
{
// Apply the camera changes first, then convert
cameraManip->setCamera(camera, true);
cameraManip->convertToPerspective();
camera = cameraManip->getCamera();
return true;
}
}
ImGui::SameLine();
if(ImGui::RadioButton("Orthographic", !isPerspective))
{
if(isPerspective)
{
// Apply the camera changes first, then convert
cameraManip->setCamera(camera, true);
cameraManip->convertToOrthographic();
camera = cameraManip->getCamera();
return true;
}
}
return false;
});
// Show FOV for perspective cameras
if(camera.projectionType == nvutils::CameraManipulator::ProjectionType::Perspective)
{
changed |= PE::SliderFloat("FOV", &camera.fov, 1.F, 179.F, "%.1f°", ImGuiSliderFlags_Logarithmic,
"Field of view of the camera (degrees)");
}
else // Show orthographic size for orthographic cameras
{
// Quick axis-aligned orthographic view buttons
{
const float distance = glm::length(camera.eye - camera.ctr);
const glm::vec3 center = camera.ctr;
struct AxisView
{
const char* label;
glm::vec3 direction;
glm::vec3 up;
const char* tooltip;
};
const AxisView views[] = {
{"+X", {1, 0, 0}, {0, 1, 0}, "Right view"}, {"-X", {-1, 0, 0}, {0, 1, 0}, "Left view"},
{"+Y", {0, 1, 0}, {0, 0, -1}, "Top view"}, {"-Y", {0, -1, 0}, {0, 0, 1}, "Bottom view"},
{"+Z", {0, 0, 1}, {0, 1, 0}, "Front view"}, {"-Z", {0, 0, -1}, {0, 1, 0}, "Back view"},
};
for(size_t i = 0; i < 6; i++)
{
if(i > 0)
ImGui::SameLine();
if(ImGui::Button(views[i].label))
{
camera.eye = center + views[i].direction * distance;
camera.up = views[i].up;
changed = true;
}
nvgui::tooltip(views[i].tooltip);
}
}
// Orthographic magnitude slider
{
float magValues[2] = {camera.orthMag.x, camera.orthMag.y};
if(PE::DragFloat2("Mag", magValues, 0.1f, 0.01f, 10000.0f, "%.3f", ImGuiSliderFlags_None,
"Orthographic half-width/height (glTF xmag/ymag)"))
{
// Detect which value changed and update the other to maintain aspect ratio
if(magValues[0] != camera.orthMag.x)
{
camera.orthMag.x = magValues[0];
camera.orthMag.y = camera.orthMag.x / cameraManip->getAspectRatio();
}
else if(magValues[1] != camera.orthMag.y)
{
camera.orthMag.y = magValues[1];
camera.orthMag.x = camera.orthMag.y * cameraManip->getAspectRatio();
}
changed |= true;
}
}
}
// ImGuiSliderFlags_Logarithmic requires a value range for its scaling to work.
const float minClip = 1e-5f;
const float maxClip = 1e+9f;
changed |= PE::DragFloat2("Z-Clip", &camera.nearFar.x, 2e-5f * (maxClip - minClip), minClip, maxClip, "%.6f",
ImGuiSliderFlags_Logarithmic, "Near/Far clip planes for depth buffer");
PE::end();
}
ImGui::TreePop();
}
return changed;
}
//--------------------------------------------------------------------------------------------------
// Advanced Settings Section : Up vector (Y-up, Z-up), animation transition time
//
static bool OtherSettingsSection(std::shared_ptr<nvutils::CameraManipulator> cameraM,
nvutils::CameraManipulator::Camera& camera,
ImGuiTreeNodeFlags flag = ImGuiTreeNodeFlags_None)
{
bool changed = false;
if(ImGui::TreeNodeEx("Other", flag))
{
if(PeBeginAutostretch("##Other"))
{
PE::entry("Up vector", [&] {
const bool yIsUp = camera.up.y == 1;
if(ImGui::RadioButton("Y-up", yIsUp))
{
camera.up = glm::vec3(0, 1, 0);
changed = true;
}
ImGui::SameLine();
if(ImGui::RadioButton("Z-up", !yIsUp))
{
camera.up = glm::vec3(0, 0, 1);
changed = true;
}
if(glm::length(camera.up) < 0.0001f)
{
camera.up = yIsUp ? glm::vec3(0, 1, 0) : glm::vec3(0, 0, 1);
changed = true;
}
return changed;
});
auto duration = static_cast<float>(cameraM->getAnimationDuration());
changed |= PE::SliderFloat("Transition", &duration, 0.0F, 2.0F, "%.2fs", ImGuiSliderFlags_None,
"Transition duration of camera movement");
cameraM->setAnimationDuration(duration);
PE::end();
}
ImGui::TreePop();
}
return changed;
}
//--------------------------------------------------------------------------------------------------
// Unified camera widget: position, presets, navigation settings
//
bool nvgui::CameraWidget(std::shared_ptr<nvutils::CameraManipulator> cameraManip, bool embed, CameraWidgetSections openSections)
{
assert(cameraManip && "CameraManipulator is not set");
bool changed{false};
bool instantChanged{false};
nvutils::CameraManipulator::Camera camera = cameraManip->getCamera();
// Updating the camera manager
CameraPresetManager::getInstance().update(cameraManip);
if(embed)
{
ImGui::Text("Camera Settings");
if(!ImGui::BeginChild("CameraPanel", ImVec2(0, 0), ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeY))
{
return false;
}
}
// Main camera panel with modern design
{
changed |= QuickActionsBar(cameraManip, camera);
changed |= PresetsSection(cameraManip, camera);
changed |= NavigationSettingsSection(cameraManip);
ImGui::Separator();
// Clip planes / FOV section
instantChanged |= ProjectionSettingsSection(cameraManip, camera,
(openSections & CameraSection_Projection) ? ImGuiTreeNodeFlags_DefaultOpen :
ImGuiTreeNodeFlags_None);
changed |= PositionSection(cameraManip, camera,
(openSections & CameraSection_Position) ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None);
// Up vector / Animation duration section
changed |= OtherSettingsSection(cameraManip, camera,
(openSections & CameraSection_Other) ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None);
if(embed)
{
ImGui::EndChild();
}
}
// Apply the change back to the camera
if(changed || instantChanged)
{
CameraPresetManager::getInstance().markJsonSettingsDirty();
cameraManip->setCamera(camera, instantChanged);
}
return changed || instantChanged;
}
void nvgui::SetCameraJsonFile(const std::filesystem::path& filename)
{
CameraPresetManager::getInstance().setCameraJsonFile(filename);
}
void nvgui::SetHomeCamera(const nvutils::CameraManipulator::Camera& camera)
{
CameraPresetManager::getInstance().setHomeCamera(camera);
}
void nvgui::AddCamera(const nvutils::CameraManipulator::Camera& camera)
{
CameraPresetManager::getInstance().addCamera(camera);
}
std::vector<nvutils::CameraManipulator::Camera> nvgui::GetCameras()
{
return CameraPresetManager::getInstance().m_cameras;
}