Debian Codegraph @

libs/filamentapp/src/FilamentApp.cpp

raw symbols SCIP
1 #include <memory>
2
3 /*
4 * Copyright (C) 2015 The Android Open Source Project
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 #include <filamentapp/FilamentApp.h>
20
21 #if !defined(WIN32)
22 # include <unistd.h>
23 #else
24 # include <SDL_syswm.h>
25 # include <utils/unwindows.h>
26 #endif
27
28 #include <iostream>
29
30 #include <imgui.h>
31
32 #include <utils/EntityManager.h>
33 #include <utils/Panic.h>
34 #include <utils/Path.h>
35
36 #include <filament/Camera.h>
37 #include <filament/Material.h>
38 #include <filament/MaterialInstance.h>
39 #include <filament/Renderer.h>
40 #include <filament/RenderableManager.h>
41 #include <filament/Scene.h>
42 #include <filament/Skybox.h>
43 #include <filament/View.h>
44
45 #include <filagui/ImGuiHelper.h>
46
47 #include <filamentapp/Cube.h>
48 #include <filamentapp/NativeWindowHelper.h>
49
50 #include <stb_image.h>
51
52 #include "generated/resources/filamentapp.h"
53
54 using namespace filament;
55 using namespace filagui;
56 using namespace filament::math;
57 using namespace utils;
58
59 FilamentApp& FilamentApp::get() {
60 static FilamentApp filamentApp;
61 return filamentApp;
62 }
63
64 FilamentApp::FilamentApp() {
65 initSDL();
66 }
67
68 FilamentApp::~FilamentApp() {
69 SDL_Quit();
70 }
71
72 View* FilamentApp::getGuiView() const noexcept {
73 return mImGuiHelper->getView();
74 }
75
76 void FilamentApp::run(const Config& config, SetupCallback setupCallback,
77 CleanupCallback cleanupCallback, ImGuiCallback imguiCallback,
78 PreRenderCallback preRender, PostRenderCallback postRender,
79 size_t width, size_t height) {
80 mWindowTitle = config.title;
81 std::unique_ptr<FilamentApp::Window> window(
82 new FilamentApp::Window(this, config, config.title, width, height));
83
84 mDepthMaterial = Material::Builder()
85 .package(FILAMENTAPP_DEPTHVISUALIZER_DATA, FILAMENTAPP_DEPTHVISUALIZER_SIZE)
86 .build(*mEngine);
87
88 mDepthMI = mDepthMaterial->createInstance();
89
90 mDefaultMaterial = Material::Builder()
91 .package(FILAMENTAPP_AIDEFAULTMAT_DATA, FILAMENTAPP_AIDEFAULTMAT_SIZE)
92 .build(*mEngine);
93
94 mTransparentMaterial = Material::Builder()
95 .package(FILAMENTAPP_TRANSPARENTCOLOR_DATA, FILAMENTAPP_TRANSPARENTCOLOR_SIZE)
96 .build(*mEngine);
97
98 std::unique_ptr<Cube> cameraCube(new Cube(*mEngine, mTransparentMaterial, {1,0,0}));
99 // we can't cull the light-frustum because it's not applied a rigid transform
100 // and currently, filament assumes that for culling
101 std::unique_ptr<Cube> lightmapCube(new Cube(*mEngine, mTransparentMaterial, {0,1,0}, false));
102 mScene = mEngine->createScene();
103
104 window->mMainView->getView()->setVisibleLayers(0x4, 0x4);
105
106 if (config.splitView) {
107 auto& rcm = mEngine->getRenderableManager();
108
109 rcm.setLayerMask(rcm.getInstance(cameraCube->getSolidRenderable()), 0x3, 0x2);
110 rcm.setLayerMask(rcm.getInstance(cameraCube->getWireFrameRenderable()), 0x3, 0x2);
111
112 rcm.setLayerMask(rcm.getInstance(lightmapCube->getSolidRenderable()), 0x3, 0x2);
113 rcm.setLayerMask(rcm.getInstance(lightmapCube->getWireFrameRenderable()), 0x3, 0x2);
114
115 // Create the camera mesh
116 mScene->addEntity(cameraCube->getWireFrameRenderable());
117 mScene->addEntity(cameraCube->getSolidRenderable());
118
119 mScene->addEntity(lightmapCube->getWireFrameRenderable());
120 mScene->addEntity(lightmapCube->getSolidRenderable());
121
122 window->mDepthView->getView()->setVisibleLayers(0x4, 0x4);
123 window->mGodView->getView()->setVisibleLayers(0x6, 0x6);
124 window->mOrthoView->getView()->setVisibleLayers(0x6, 0x6);
125
126 // only preserve the color buffer for additional views; depth and stencil can be discarded.
127 window->mDepthView->getView()->setShadowingEnabled(false);
128 window->mGodView->getView()->setShadowingEnabled(false);
129 window->mOrthoView->getView()->setShadowingEnabled(false);
130 }
131
132 loadDirt(config);
133 loadIBL(config);
134 if (mIBL != nullptr) {
135 mIBL->getSkybox()->setLayerMask(0x7, 0x4);
136 mScene->setSkybox(mIBL->getSkybox());
137 mScene->setIndirectLight(mIBL->getIndirectLight());
138 }
139
140 for (auto& view : window->mViews) {
141 if (view.get() != window->mUiView) {
142 view->getView()->setScene(mScene);
143 }
144 }
145
146 setupCallback(mEngine, window->mMainView->getView(), mScene);
147
148 if (imguiCallback) {
149 mImGuiHelper = std::make_unique<ImGuiHelper>(mEngine, window->mUiView->getView(),
150 getRootAssetsPath() + "assets/fonts/Roboto-Medium.ttf");
151 ImGuiIO& io = ImGui::GetIO();
152 #ifdef WIN32
153 SDL_SysWMinfo wmInfo;
154 SDL_VERSION(&wmInfo.version);
155 SDL_GetWindowWMInfo(window->getSDLWindow(), &wmInfo);
156 io.ImeWindowHandle = wmInfo.info.win.window;
157 #endif
158 io.KeyMap[ImGuiKey_Tab] = SDL_SCANCODE_TAB;
159 io.KeyMap[ImGuiKey_LeftArrow] = SDL_SCANCODE_LEFT;
160 io.KeyMap[ImGuiKey_RightArrow] = SDL_SCANCODE_RIGHT;
161 io.KeyMap[ImGuiKey_UpArrow] = SDL_SCANCODE_UP;
162 io.KeyMap[ImGuiKey_DownArrow] = SDL_SCANCODE_DOWN;
163 io.KeyMap[ImGuiKey_PageUp] = SDL_SCANCODE_PAGEUP;
164 io.KeyMap[ImGuiKey_PageDown] = SDL_SCANCODE_PAGEDOWN;
165 io.KeyMap[ImGuiKey_Home] = SDL_SCANCODE_HOME;
166 io.KeyMap[ImGuiKey_End] = SDL_SCANCODE_END;
167 io.KeyMap[ImGuiKey_Insert] = SDL_SCANCODE_INSERT;
168 io.KeyMap[ImGuiKey_Delete] = SDL_SCANCODE_DELETE;
169 io.KeyMap[ImGuiKey_Backspace] = SDL_SCANCODE_BACKSPACE;
170 io.KeyMap[ImGuiKey_Space] = SDL_SCANCODE_SPACE;
171 io.KeyMap[ImGuiKey_Enter] = SDL_SCANCODE_RETURN;
172 io.KeyMap[ImGuiKey_Escape] = SDL_SCANCODE_ESCAPE;
173 io.KeyMap[ImGuiKey_A] = SDL_SCANCODE_A;
174 io.KeyMap[ImGuiKey_C] = SDL_SCANCODE_C;
175 io.KeyMap[ImGuiKey_V] = SDL_SCANCODE_V;
176 io.KeyMap[ImGuiKey_X] = SDL_SCANCODE_X;
177 io.KeyMap[ImGuiKey_Y] = SDL_SCANCODE_Y;
178 io.KeyMap[ImGuiKey_Z] = SDL_SCANCODE_Z;
179 io.SetClipboardTextFn = [](void*, const char* text) {
180 SDL_SetClipboardText(text);
181 };
182 io.GetClipboardTextFn = [](void*) -> const char* {
183 return SDL_GetClipboardText();
184 };
185 io.ClipboardUserData = nullptr;
186 }
187
188 bool mousePressed[3] = { false };
189
190 int sidebarWidth = mSidebarWidth;
191 float cameraFocalLength = mCameraFocalLength;
192
193 SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
194 SDL_Window* sdlWindow = window->getSDLWindow();
195
196 while (!mClosed) {
197 if (mWindowTitle != SDL_GetWindowTitle(sdlWindow)) {
198 SDL_SetWindowTitle(sdlWindow, mWindowTitle.c_str());
199 }
200
201 if (mSidebarWidth != sidebarWidth || mCameraFocalLength != cameraFocalLength) {
202 window->configureCamerasForWindow();
203 sidebarWidth = mSidebarWidth;
204 cameraFocalLength = mCameraFocalLength;
205 }
206
207 if (!UTILS_HAS_THREADING) {
208 mEngine->execute();
209 }
210
211 // Allow the app to animate the scene if desired.
212 if (mAnimation) {
213 double now = (double) SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency();
214 mAnimation(mEngine, window->mMainView->getView(), now);
215 }
216
217 // Loop over fresh events twice: first stash them and let ImGui process them, then allow
218 // the app to process the stashed events. This is done because ImGui might wish to block
219 // certain events from the app (e.g., when dragging the mouse over an obscuring window).
220 constexpr int kMaxEvents = 16;
221 SDL_Event events[kMaxEvents];
222 int nevents = 0;
223 while (nevents < kMaxEvents && SDL_PollEvent(&events[nevents]) != 0) {
224 if (mImGuiHelper) {
225 ImGuiIO& io = ImGui::GetIO();
226 SDL_Event* event = &events[nevents];
227 switch (event->type) {
228 case SDL_MOUSEWHEEL: {
229 if (event->wheel.x > 0) io.MouseWheelH += 1;
230 if (event->wheel.x < 0) io.MouseWheelH -= 1;
231 if (event->wheel.y > 0) io.MouseWheel += 1;
232 if (event->wheel.y < 0) io.MouseWheel -= 1;
233 break;
234 }
235 case SDL_MOUSEBUTTONDOWN: {
236 if (event->button.button == SDL_BUTTON_LEFT) mousePressed[0] = true;
237 if (event->button.button == SDL_BUTTON_RIGHT) mousePressed[1] = true;
238 if (event->button.button == SDL_BUTTON_MIDDLE) mousePressed[2] = true;
239 break;
240 }
241 case SDL_TEXTINPUT: {
242 io.AddInputCharactersUTF8(event->text.text);
243 break;
244 }
245 case SDL_KEYDOWN:
246 case SDL_KEYUP: {
247 int key = event->key.keysym.scancode;
248 IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown));
249 io.KeysDown[key] = (event->type == SDL_KEYDOWN);
250 io.KeyShift = ((SDL_GetModState() & KMOD_SHIFT) != 0);
251 io.KeyAlt = ((SDL_GetModState() & KMOD_ALT) != 0);
252 io.KeyCtrl = ((SDL_GetModState() & KMOD_CTRL) != 0);
253 io.KeySuper = ((SDL_GetModState() & KMOD_GUI) != 0);
254 break;
255 }
256 }
257 }
258 nevents++;
259 }
260
261 // Now, loop over the events a second time for app-side processing.
262 for (int i = 0; i < nevents; i++) {
263 const SDL_Event& event = events[i];
264 ImGuiIO* io = mImGuiHelper ? &ImGui::GetIO() : nullptr;
265 switch (event.type) {
266 case SDL_QUIT:
267 mClosed = true;
268 break;
269 case SDL_KEYDOWN:
270 if (event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) {
271 mClosed = true;
272 }
273 window->keyDown(event.key.keysym.scancode);
274 break;
275 case SDL_KEYUP:
276 window->keyUp(event.key.keysym.scancode);
277 break;
278 case SDL_MOUSEWHEEL:
279 if (!io || !io->WantCaptureMouse)
280 window->mouseWheel(event.wheel.y);
281 break;
282 case SDL_MOUSEBUTTONDOWN:
283 if (!io || !io->WantCaptureMouse)
284 window->mouseDown(event.button.button, event.button.x, event.button.y);
285 break;
286 case SDL_MOUSEBUTTONUP:
287 if (!io || !io->WantCaptureMouse)
288 window->mouseUp(event.button.x, event.button.y);
289 break;
290 case SDL_MOUSEMOTION:
291 if (!io || !io->WantCaptureMouse)
292 window->mouseMoved(event.motion.x, event.motion.y);
293 break;
294 case SDL_DROPFILE:
295 if (mDropHandler) {
296 mDropHandler(event.drop.file);
297 }
298 SDL_free(event.drop.file);
299 break;
300 case SDL_WINDOWEVENT:
301 switch (event.window.event) {
302 case SDL_WINDOWEVENT_RESIZED:
303 window->resize();
304 break;
305 default:
306 break;
307 }
308 break;
309 default:
310 break;
311 }
312 }
313
314 // Calculate the time step.
315 static Uint64 frequency = SDL_GetPerformanceFrequency();
316 Uint64 now = SDL_GetPerformanceCounter();
317 const float timeStep = mTime > 0 ? (float)((double)(now - mTime) / frequency) :
318 (float)(1.0f / 60.0f);
319 mTime = now;
320
321 // Populate the UI scene, regardless of whether Filament wants to a skip frame. We should
322 // always let ImGui generate a command list; if it skips a frame it'll destroy its widgets.
323 if (mImGuiHelper) {
324
325 // Inform ImGui of the current window size in case it was resized.
326 if (config.headless) {
327 mImGuiHelper->setDisplaySize(window->mWidth, window->mHeight);
328 } else {
329 int windowWidth, windowHeight;
330 int displayWidth, displayHeight;
331 SDL_GetWindowSize(window->mWindow, &windowWidth, &windowHeight);
332 SDL_GL_GetDrawableSize(window->mWindow, &displayWidth, &displayHeight);
333 mImGuiHelper->setDisplaySize(windowWidth, windowHeight,
334 windowWidth > 0 ? ((float)displayWidth / windowWidth) : 0,
335 displayHeight > 0 ? ((float)displayHeight / windowHeight) : 0);
336 }
337
338 // Setup mouse inputs (we already got mouse wheel, keyboard keys & characters
339 // from our event handler)
340 ImGuiIO& io = ImGui::GetIO();
341 int mx, my;
342 Uint32 buttons = SDL_GetMouseState(&mx, &my);
343 io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
344 io.MouseDown[0] = mousePressed[0] || (buttons & SDL_BUTTON(SDL_BUTTON_LEFT)) != 0;
345 io.MouseDown[1] = mousePressed[1] || (buttons & SDL_BUTTON(SDL_BUTTON_RIGHT)) != 0;
346 io.MouseDown[2] = mousePressed[2] || (buttons & SDL_BUTTON(SDL_BUTTON_MIDDLE)) != 0;
347 mousePressed[0] = mousePressed[1] = mousePressed[2] = false;
348
349 // TODO: Update to a newer SDL and use SDL_CaptureMouse() to retrieve mouse coordinates
350 // outside of the client area; see the imgui SDL example.
351 if ((SDL_GetWindowFlags(window->mWindow) & SDL_WINDOW_INPUT_FOCUS) != 0) {
352 io.MousePos = ImVec2((float)mx, (float)my);
353 }
354
355 // Populate the UI Scene.
356 mImGuiHelper->render(timeStep, imguiCallback);
357 }
358
359 // Update the camera manipulators for each view.
360 for (auto const& view : window->mViews) {
361 auto* cm = view->getCameraManipulator();
362 if (cm) {
363 cm->update(timeStep);
364 }
365 }
366
367 // Update the position and orientation of the two cameras.
368 filament::math::float3 eye, center, up;
369 window->mMainCameraMan->getLookAt(&eye, &center, &up);
370 window->mMainCamera->lookAt(eye, center, up);
371 window->mDebugCameraMan->getLookAt(&eye, &center, &up);
372 window->mDebugCamera->lookAt(eye, center, up);
373
374 // Update the cube distortion matrix used for frustum visualization.
375 const Camera* lightmapCamera = window->mMainView->getView()->getDirectionalLightCamera();
376 lightmapCube->mapFrustum(*mEngine, lightmapCamera);
377 cameraCube->mapFrustum(*mEngine, window->mMainCamera);
378
379 // TODO: we need better timing or use SDL_GL_SetSwapInterval
380 SDL_Delay(16);
381
382 Renderer* renderer = window->getRenderer();
383
384 if (preRender) {
385 for (auto const& view : window->mViews) {
386 if (view.get() != window->mUiView) {
387 preRender(mEngine, view->getView(), mScene, renderer);
388 }
389 }
390 }
391
392 if (renderer->beginFrame(window->getSwapChain())) {
393 for (filament::View* offscreenView : mOffscreenViews) {
394 renderer->render(offscreenView);
395 }
396 for (auto const& view : window->mViews) {
397 renderer->render(view->getView());
398 }
399 renderer->endFrame();
400
401 // We call PostRender only when the frame has not been skipped. It might be used
402 // for taking screenshots under the assumption that a state change has taken effect.
403 if (postRender) {
404 for (auto const& view : window->mViews) {
405 if (view.get() != window->mUiView) {
406 postRender(mEngine, view->getView(), mScene, renderer);
407 }
408 }
409 }
410
411 } else {
412 ++mSkippedFrames;
413 }
414 }
415
416 if (mImGuiHelper) {
417 mImGuiHelper.reset();
418 }
419
420 cleanupCallback(mEngine, window->mMainView->getView(), mScene);
421
422 cameraCube.reset();
423 lightmapCube.reset();
424 window.reset();
425
426 mIBL.reset();
427 mEngine->destroy(mDepthMI);
428 mEngine->destroy(mDepthMaterial);
429 mEngine->destroy(mDefaultMaterial);
430 mEngine->destroy(mTransparentMaterial);
431 mEngine->destroy(mScene);
432 Engine::destroy(&mEngine);
433 mEngine = nullptr;
434 }
435
436 // RELATIVE_ASSET_PATH is set inside samples/CMakeLists.txt and used to support multi-configuration
437 // generators, like Visual Studio or Xcode.
438 #ifndef RELATIVE_ASSET_PATH
439 #define RELATIVE_ASSET_PATH "."
440 #endif
441
442 const utils::Path& FilamentApp::getRootAssetsPath() {
443 static const utils::Path root = utils::Path::getCurrentExecutable().getParent() + RELATIVE_ASSET_PATH;
444 return root;
445 }
446
447 void FilamentApp::loadIBL(const Config& config) {
448 if (!config.iblDirectory.empty()) {
449 Path iblPath(config.iblDirectory);
450
451 if (!iblPath.exists()) {
452 std::cerr << "The specified IBL path does not exist: " << iblPath << std::endl;
453 return;
454 }
455
456 mIBL = std::make_unique<IBL>(*mEngine);
457
458 if (!iblPath.isDirectory()) {
459 if (!mIBL->loadFromEquirect(iblPath)) {
460 std::cerr << "Could not load the specified IBL: " << iblPath << std::endl;
461 mIBL.reset(nullptr);
462 return;
463 }
464 } else {
465 if (!mIBL->loadFromDirectory(iblPath)) {
466 std::cerr << "Could not load the specified IBL: " << iblPath << std::endl;
467 mIBL.reset(nullptr);
468 return;
469 }
470 }
471 }
472 }
473
474 void FilamentApp::loadDirt(const Config& config) {
475 if (!config.dirt.empty()) {
476 Path dirtPath(config.dirt);
477
478 if (!dirtPath.exists()) {
479 std::cerr << "The specified dirt file does not exist: " << dirtPath << std::endl;
480 return;
481 }
482
483 if (!dirtPath.isFile()) {
484 std::cerr << "The specified dirt path is not a file: " << dirtPath << std::endl;
485 return;
486 }
487
488 int w, h, n;
489
490 unsigned char* data = stbi_load(dirtPath.getAbsolutePath().c_str(), &w, &h, &n, 3);
491 assert(n == 3);
492
493 mDirt = Texture::Builder()
494 .width(w)
495 .height(h)
496 .format(Texture::InternalFormat::RGB8)
497 .build(*mEngine);
498
499 mDirt->setImage(*mEngine, 0, { data, size_t(w * h * 3),
500 Texture::Format::RGB, Texture::Type::UBYTE,
501 (Texture::PixelBufferDescriptor::Callback)&stbi_image_free });
502 }
503 }
504
505 void FilamentApp::initSDL() {
506 ASSERT_POSTCONDITION(SDL_Init(SDL_INIT_EVENTS) == 0, "SDL_Init Failure");
507 }
508
509 // ------------------------------------------------------------------------------------------------
510
511 FilamentApp::Window::Window(FilamentApp* filamentApp,
512 const Config& config, std::string title, size_t w, size_t h)
513 : mFilamentApp(filamentApp) {
514 const int x = SDL_WINDOWPOS_CENTERED;
515 const int y = SDL_WINDOWPOS_CENTERED;
516 uint32_t windowFlags = SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI;
517 if (config.resizeable) {
518 windowFlags |= SDL_WINDOW_RESIZABLE;
519 }
520
521 if (config.headless) {
522 windowFlags |= SDL_WINDOW_HIDDEN;
523 }
524
525 mBackend = config.backend;
526
527 // Even if we're in headless mode, we still need to create a window, otherwise SDL will not poll
528 // events.
529 mWindow = SDL_CreateWindow(title.c_str(), x, y, (int) w, (int) h, windowFlags);
530
531 if (config.headless) {
532 mFilamentApp->mEngine = Engine::create(config.backend);
533 mSwapChain = mFilamentApp->mEngine->createSwapChain((uint32_t) w, (uint32_t) h);
534 mWidth = w;
535 mHeight = h;
536 } else {
537 // Create the Engine after the window in case this happens to be a single-threaded platform.
538 // For single-threaded platforms, we need to ensure that Filament's OpenGL context is
539 // current, rather than the one created by SDL.
540 mFilamentApp->mEngine = Engine::create(config.backend);
541
542 void* nativeWindow = ::getNativeWindow(mWindow);
543 void* nativeSwapChain = nativeWindow;
544
545 #if defined(__APPLE__)
546
547 void* metalLayer = nullptr;
548 if (config.backend == filament::Engine::Backend::METAL) {
549 metalLayer = setUpMetalLayer(nativeWindow);
550 // The swap chain on Metal is a CAMetalLayer.
551 nativeSwapChain = metalLayer;
552 }
553
554 #if defined(FILAMENT_DRIVER_SUPPORTS_VULKAN)
555 if (config.backend == filament::Engine::Backend::VULKAN) {
556 // We request a Metal layer for rendering via MoltenVK.
557 setUpMetalLayer(nativeWindow);
558 }
559 #endif
560
561 #endif
562
563 mSwapChain = mFilamentApp->mEngine->createSwapChain(nativeSwapChain);
564 }
565 mRenderer = mFilamentApp->mEngine->createRenderer();
566
567 // create cameras
568 utils::EntityManager& em = utils::EntityManager::get();
569 em.create(3, mCameraEntities);
570 mCameras[0] = mMainCamera = mFilamentApp->mEngine->createCamera(mCameraEntities[0]);
571 mCameras[1] = mDebugCamera = mFilamentApp->mEngine->createCamera(mCameraEntities[1]);
572 mCameras[2] = mOrthoCamera = mFilamentApp->mEngine->createCamera(mCameraEntities[2]);
573
574 // set exposure
575 for (auto camera : mCameras) {
576 camera->setExposure(16.0f, 1 / 125.0f, 100.0f);
577 }
578
579 // create views
580 mViews.emplace_back(mMainView = new CView(*mRenderer, "Main View"));
581 if (config.splitView) {
582 mViews.emplace_back(mDepthView = new CView(*mRenderer, "Depth View"));
583 mViews.emplace_back(mGodView = new GodView(*mRenderer, "God View"));
584 mViews.emplace_back(mOrthoView = new CView(*mRenderer, "Ortho View"));
585 }
586 mViews.emplace_back(mUiView = new CView(*mRenderer, "UI View"));
587
588 // set-up the camera manipulators
589 mMainCameraMan = CameraManipulator::Builder()
590 .targetPosition(0, 0, -4)
591 .flightMoveDamping(15.0)
592 .build(config.cameraMode);
593 mDebugCameraMan = CameraManipulator::Builder()
594 .targetPosition(0, 0, -4)
595 .build(camutils::Mode::ORBIT);
596
597 mMainView->setCamera(mMainCamera);
598 mMainView->setCameraManipulator(mMainCameraMan);
599 if (config.splitView) {
600 // Depth view always uses the main camera
601 mDepthView->setCamera(mMainCamera);
602
603 // The god view uses the main camera for culling, but the debug camera for viewing
604 mGodView->setCamera(mMainCamera);
605 mGodView->setGodCamera(mDebugCamera);
606
607 // Ortho view obviously uses an ortho camera
608 mOrthoView->setCamera( (Camera *)mMainView->getView()->getDirectionalLightCamera() );
609
610 mDepthView->setCameraManipulator(mMainCameraMan);
611 mGodView->setCameraManipulator(mDebugCameraMan);
612 }
613
614 // configure the cameras
615 configureCamerasForWindow();
616
617 mMainCamera->lookAt({4, 0, -4}, {0, 0, -4}, {0, 1, 0});
618 }
619
620 FilamentApp::Window::~Window() {
621 mViews.clear();
622 utils::EntityManager& em = utils::EntityManager::get();
623 for (auto e : mCameraEntities) {
624 mFilamentApp->mEngine->destroyCameraComponent(e);
625 em.destroy(e);
626 }
627 mFilamentApp->mEngine->destroy(mRenderer);
628 mFilamentApp->mEngine->destroy(mSwapChain);
629 SDL_DestroyWindow(mWindow);
630 delete mMainCameraMan;
631 delete mDebugCameraMan;
632 }
633
634 void FilamentApp::Window::mouseDown(int button, ssize_t x, ssize_t y) {
635 fixupMouseCoordinatesForHdpi(x, y);
636 y = mHeight - y;
637 for (auto const& view : mViews) {
638 if (view->intersects(x, y)) {
639 mMouseEventTarget = view.get();
640 view->mouseDown(button, x, y);
641 break;
642 }
643 }
644 }
645
646 void FilamentApp::Window::mouseWheel(ssize_t x) {
647 if (mMouseEventTarget) {
648 mMouseEventTarget->mouseWheel(x);
649 } else {
650 for (auto const& view : mViews) {
651 if (view->intersects(mLastX, mLastY)) {
652 view->mouseWheel(x);
653 break;
654 }
655 }
656 }
657 }
658
659 void FilamentApp::Window::mouseUp(ssize_t x, ssize_t y) {
660 fixupMouseCoordinatesForHdpi(x, y);
661 if (mMouseEventTarget) {
662 y = mHeight - y;
663 mMouseEventTarget->mouseUp(x, y);
664 mMouseEventTarget = nullptr;
665 }
666 }
667
668 void FilamentApp::Window::mouseMoved(ssize_t x, ssize_t y) {
669 fixupMouseCoordinatesForHdpi(x, y);
670 y = mHeight - y;
671 if (mMouseEventTarget) {
672 mMouseEventTarget->mouseMoved(x, y);
673 }
674 mLastX = x;
675 mLastY = y;
676 }
677
678 void FilamentApp::Window::keyDown(SDL_Scancode key) {
679 auto& eventTarget = mKeyEventTarget[key];
680
681 // keyDown events can be sent multiple times per key (for key repeat)
682 // If this key is already down, do nothing.
683 if (eventTarget) {
684 return;
685 }
686
687 // Decide which view will get this key's corresponding keyUp event.
688 // If we're currently in a mouse grap session, it should be the mouse grab's target view.
689 // Otherwise, it should be whichever view we're currently hovering over.
690 CView* targetView = nullptr;
691 if (mMouseEventTarget) {
692 targetView = mMouseEventTarget;
693 } else {
694 for (auto const& view : mViews) {
695 if (view->intersects(mLastX, mLastY)) {
696 targetView = view.get();
697 break;
698 }
699 }
700 }
701
702 if (targetView) {
703 targetView->keyDown(key);
704 eventTarget = targetView;
705 }
706 }
707
708 void FilamentApp::Window::keyUp(SDL_Scancode key) {
709 auto& eventTarget = mKeyEventTarget[key];
710 if (!eventTarget) {
711 return;
712 }
713 eventTarget->keyUp(key);
714 eventTarget = nullptr;
715 }
716
717 void FilamentApp::Window::fixupMouseCoordinatesForHdpi(ssize_t& x, ssize_t& y) const {
718 int dw, dh, ww, wh;
719 SDL_GL_GetDrawableSize(mWindow, &dw, &dh);
720 SDL_GetWindowSize(mWindow, &ww, &wh);
721 x = x * dw / ww;
722 y = y * dh / wh;
723 }
724
725 void FilamentApp::Window::resize() {
726 void* nativeWindow = ::getNativeWindow(mWindow);
727
728 #if defined(__APPLE__)
729
730 if (mBackend == filament::Engine::Backend::METAL) {
731 resizeMetalLayer(nativeWindow);
732 }
733
734 #if defined(FILAMENT_DRIVER_SUPPORTS_VULKAN)
735 if (mBackend == filament::Engine::Backend::VULKAN) {
736 resizeMetalLayer(nativeWindow);
737 }
738 #endif
739
740 #endif
741
742 configureCamerasForWindow();
743
744 // Call the resize callback, if this FilamentApp has one. This must be done after
745 // configureCamerasForWindow, so the viewports are correct.
746 if (mFilamentApp->mResize) {
747 mFilamentApp->mResize(mFilamentApp->mEngine, mMainView->getView());
748 }
749 }
750
751 void FilamentApp::Window::configureCamerasForWindow() {
752 float dpiScaleX = 1.0f;
753 float dpiScaleY = 1.0f;
754
755 // If the app is not headless, query the window for its physical & virtual sizes.
756 if (mWindow) {
757 uint32_t width, height;
758 SDL_GL_GetDrawableSize(mWindow, (int*) &width, (int*) &height);
759 mWidth = (size_t) width;
760 mHeight = (size_t) height;
761
762 int virtualWidth, virtualHeight;
763 SDL_GetWindowSize(mWindow, &virtualWidth, &virtualHeight);
764 dpiScaleX = (float) width / virtualWidth;
765 dpiScaleY = (float) height / virtualHeight;
766 }
767
768 const uint32_t width = mWidth;
769 const uint32_t height = mHeight;
770
771 const float3 at(0, 0, -4);
772 const double ratio = double(height) / double(width);
773 const int sidebar = mFilamentApp->mSidebarWidth * dpiScaleX;
774
775 const bool splitview = mViews.size() > 2;
776
777 // To trigger a floating-point exception, users could shrink the window to be smaller than
778 // the sidebar. To prevent this we simply clamp the width of the main viewport.
779 const uint32_t mainWidth = splitview ? width : std::max(1, (int) width - sidebar);
780
781 double near = 0.1;
782 double far = 100;
783 mMainCamera->setLensProjection(mFilamentApp->mCameraFocalLength, double(mainWidth) / height, near, far);
784 mDebugCamera->setProjection(45.0, double(width) / height, 0.0625, 4096, Camera::Fov::VERTICAL);
785 mOrthoCamera->setProjection(Camera::Projection::ORTHO, -3, 3, -3 * ratio, 3 * ratio, near, far);
786 mOrthoCamera->lookAt({ 0, 0, 0 }, {0, 0, -4});
787
788 // We're in split view when there are more views than just the Main and UI views.
789 if (splitview) {
790 uint32_t vpw = width / 2;
791 uint32_t vph = height / 2;
792 mMainView->setViewport ({ 0, 0, vpw, vph });
793 mDepthView->setViewport({ int32_t(vpw), 0, width - vpw, vph });
794 mGodView->setViewport ({ int32_t(vpw), int32_t(vph), width - vpw, height - vph });
795 mOrthoView->setViewport({ 0, int32_t(vph), vpw, height - vph });
796 } else {
797 mMainView->setViewport({ sidebar, 0, mainWidth, height });
798 }
799 mUiView->setViewport({ 0, 0, width, height });
800 }
801
802 // ------------------------------------------------------------------------------------------------
803
804 FilamentApp::CView::CView(Renderer& renderer, std::string name)
805 : engine(*renderer.getEngine()), mName(name) {
806 view = engine.createView();
807 view->setName(name.c_str());
808 }
809
810 FilamentApp::CView::~CView() {
811 engine.destroy(view);
812 }
813
814 void FilamentApp::CView::setViewport(Viewport const& viewport) {
815 mViewport = viewport;
816 view->setViewport(viewport);
817 if (mCameraManipulator) {
818 mCameraManipulator->setViewport(viewport.width, viewport.height);
819 }
820 }
821
822 void FilamentApp::CView::mouseDown(int button, ssize_t x, ssize_t y) {
823 if (mCameraManipulator) {
824 mCameraManipulator->grabBegin(x, y, button == 3);
825 }
826 }
827
828 void FilamentApp::CView::mouseUp(ssize_t x, ssize_t y) {
829 if (mCameraManipulator) {
830 mCameraManipulator->grabEnd();
831 }
832 }
833
834 void FilamentApp::CView::mouseMoved(ssize_t x, ssize_t y) {
835 if (mCameraManipulator) {
836 mCameraManipulator->grabUpdate(x, y);
837 }
838 }
839
840 void FilamentApp::CView::mouseWheel(ssize_t x) {
841 if (mCameraManipulator) {
842 mCameraManipulator->scroll(0, 0, x);
843 }
844 }
845
846 bool FilamentApp::manipulatorKeyFromKeycode(SDL_Scancode scancode, CameraManipulator::Key& key) {
847 switch (scancode) {
848 case SDL_SCANCODE_W:
849 key = CameraManipulator::Key::FORWARD;
850 return true;
851 case SDL_SCANCODE_A:
852 key = CameraManipulator::Key::LEFT;
853 return true;
854 case SDL_SCANCODE_S:
855 key = CameraManipulator::Key::BACKWARD;
856 return true;
857 case SDL_SCANCODE_D:
858 key = CameraManipulator::Key::RIGHT;
859 return true;
860 case SDL_SCANCODE_E:
861 key = CameraManipulator::Key::UP;
862 return true;
863 case SDL_SCANCODE_Q:
864 key = CameraManipulator::Key::DOWN;
865 return true;
866 default:
867 return false;
868 }
869 }
870
871 void FilamentApp::CView::keyUp(SDL_Scancode scancode) {
872 if (mCameraManipulator) {
873 CameraManipulator::Key key;
874 if (manipulatorKeyFromKeycode(scancode, key)) {
875 mCameraManipulator->keyUp(key);
876 }
877 }
878 }
879
880 void FilamentApp::CView::keyDown(SDL_Scancode scancode) {
881 if (mCameraManipulator) {
882 CameraManipulator::Key key;
883 if (manipulatorKeyFromKeycode(scancode, key)) {
884 mCameraManipulator->keyDown(key);
885 }
886 }
887 }
888
889 bool FilamentApp::CView::intersects(ssize_t x, ssize_t y) {
890 if (x >= mViewport.left && x < mViewport.left + mViewport.width)
891 if (y >= mViewport.bottom && y < mViewport.bottom + mViewport.height)
892 return true;
893
894 return false;
895 }
896
897 void FilamentApp::CView::setCameraManipulator(CameraManipulator* cm) {
898 mCameraManipulator = cm;
899 }
900
901 void FilamentApp::CView::setCamera(Camera* camera) {
902 view->setCamera(camera);
903 }
904
905 void FilamentApp::GodView::setGodCamera(Camera* camera) {
906 getView()->setDebugCamera(camera);
907 }