Main.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include <windows.h>
  4. // Engine includes
  5. #include "BsApplication.h"
  6. #include "BsImporter.h"
  7. #include "BsResources.h"
  8. #include "BsTextureImportOptions.h"
  9. #include "BsMaterial.h"
  10. #include "BsShader.h"
  11. #include "BsVirtualInput.h"
  12. #include "BsCCamera.h"
  13. #include "BsCRenderable.h"
  14. #include "BsCGUIWidget.h"
  15. #include "BsGUILayoutX.h"
  16. #include "BsGUILayoutY.h"
  17. #include "BsGUIPanel.h"
  18. #include "BsGUISpace.h"
  19. #include "BsGUILabel.h"
  20. #include "BsGUIButton.h"
  21. #include "BsRenderAPI.h"
  22. #include "BsGUIListBox.h"
  23. #include "BsBuiltinResources.h"
  24. #include "BsRTTIType.h"
  25. #include "BsHString.h"
  26. #include "BsRenderWindow.h"
  27. #include "BsSceneObject.h"
  28. #include "BsCoreThread.h"
  29. #include "BsProfilerOverlay.h"
  30. // Example includes
  31. #include "CameraFlyer.h"
  32. namespace BansheeEngine
  33. {
  34. UINT32 windowResWidth = 1280;
  35. UINT32 windowResHeight = 720;
  36. /** Imports all of our assets and prepares GameObject that handle the example logic. */
  37. void setUpExample();
  38. /** Import mesh/texture/GPU programs used by the example. */
  39. void loadAssets(HMesh& model, HTexture& texture, HShader& shader);
  40. /** Create a material used by our example model. */
  41. HMaterial createMaterial(const HTexture& texture, const HShader& shader);
  42. /** Set up example scene objects. */
  43. void setUp3DScene(const HMesh& mesh, const HMaterial& material);
  44. /** Set up example GUI. */
  45. void setUpGUI();
  46. /** Set up input configuration and callbacks. */
  47. void setUpInput();
  48. /** Toggles the primary window between full-screen and windowed mode. */
  49. void toggleFullscreen();
  50. /** Called whenever the main render window is resized. */
  51. void renderWindowResized();
  52. /** Called when the selected video mode changes in the video mode list box. */
  53. void videoModeChanged(UINT32 idx, bool enabled);
  54. /** Triggered whenever a virtual button is released. */
  55. void buttonUp(const VirtualButton& button, UINT32 deviceIdx);
  56. }
  57. using namespace BansheeEngine;
  58. /** Main entry point into the application. */
  59. int CALLBACK WinMain(
  60. _In_ HINSTANCE hInstance,
  61. _In_ HINSTANCE hPrevInstance,
  62. _In_ LPSTR lpCmdLine,
  63. _In_ int nCmdShow
  64. )
  65. {
  66. // Descriptor used for initializing the engine
  67. START_UP_DESC startUpDesc;
  68. // Use default values as specified by the build system
  69. startUpDesc.renderAPI = BS_RENDER_API_MODULE;
  70. startUpDesc.renderer = BS_RENDERER_MODULE;
  71. startUpDesc.audio = BS_AUDIO_MODULE;
  72. startUpDesc.physics = BS_PHYSICS_MODULE;
  73. startUpDesc.input = BS_INPUT_MODULE;
  74. // Descriptor used for initializing the primary application window.
  75. startUpDesc.primaryWindowDesc.videoMode = VideoMode(windowResWidth, windowResHeight);
  76. startUpDesc.primaryWindowDesc.title = "Banshee Example App";
  77. startUpDesc.primaryWindowDesc.fullscreen = false;
  78. startUpDesc.primaryWindowDesc.depthBuffer = false;
  79. // List of importer plugins we plan on using for importing various resources
  80. startUpDesc.importers.push_back("BansheeFreeImgImporter"); // For importing textures
  81. startUpDesc.importers.push_back("BansheeFBXImporter"); // For importing meshes
  82. startUpDesc.importers.push_back("BansheeFontImporter"); // For importing fonts
  83. startUpDesc.importers.push_back("BansheeSL"); // For importing shaders
  84. // Initializes the application with systems and primary window as defined above
  85. Application::startUp(startUpDesc);
  86. // Imports all of ours assets and prepares GameObjects that handle the example logic.
  87. setUpExample();
  88. // Runs the main loop that does most of the work. This method will exit when user closes the main
  89. // window or exits in some other way.
  90. Application::instance().runMainLoop();
  91. Application::shutDown();
  92. return 0;
  93. }
  94. namespace BansheeEngine
  95. {
  96. Path dataPath = Paths::getRuntimeDataPath();
  97. Path exampleModelPath = dataPath + "Examples\\Dragon.fbx";
  98. Path exampleTexturePath = dataPath + "Examples\\Dragon.tga";
  99. Path exampleShaderPath = dataPath + "Examples\\Example.bsl";
  100. GUIButton* toggleFullscreenButton = nullptr;
  101. bool fullscreen = false;
  102. const VideoMode* selectedVideoMode = nullptr;
  103. Vector<const VideoMode*> videoModes;
  104. HCamera sceneCamera;
  105. HProfilerOverlay profilerOverlay;
  106. VirtualButton toggleCPUProfilerBtn;
  107. VirtualButton toggleGPUProfilerBtn;
  108. bool cpuProfilerActive = false;
  109. bool gpuProfilerActive = false;
  110. void setUpExample()
  111. {
  112. HMesh exampleModel;
  113. HTexture exampleTexture;
  114. HShader exampleShader;
  115. loadAssets(exampleModel, exampleTexture, exampleShader);
  116. HMaterial exampleMaterial = createMaterial(exampleTexture, exampleShader);
  117. setUp3DScene(exampleModel, exampleMaterial);
  118. setUpGUI();
  119. setUpInput();
  120. }
  121. /**
  122. * Load the required resources. First try to load a pre-processed version of the resources. If they don't exist import
  123. * resources from the source formats into engine format, and save them for next time.
  124. */
  125. void loadAssets(HMesh& model, HTexture& texture, HShader& shader)
  126. {
  127. // Set up paths to pre-processed versions of example resources.
  128. Path exampleModelAssetPath = exampleModelPath;
  129. Path exampleTextureAssetPath = exampleTexturePath;
  130. Path exampleShaderAssetPath = exampleShaderPath;
  131. exampleModelAssetPath.setExtension(exampleModelAssetPath.getExtension() + ".asset");
  132. exampleTextureAssetPath.setExtension(exampleTextureAssetPath.getExtension() + ".asset");
  133. exampleShaderAssetPath.setExtension(exampleShaderAssetPath.getExtension() + ".asset");
  134. // Load an FBX mesh.
  135. model = gResources().load<Mesh>(exampleModelAssetPath);
  136. if(model == nullptr) // Mesh file doesn't exist, import from the source file.
  137. {
  138. model = gImporter().import<Mesh>(exampleModelPath);
  139. // Save for later use, so we don't have to import on the next run.
  140. gResources().save(model, exampleModelAssetPath, true);
  141. }
  142. // Load an TGA texture.
  143. texture = gResources().load<Texture>(exampleTextureAssetPath);
  144. if (texture == nullptr) // Texture file doesn't exist, import from the source file.
  145. {
  146. // When importing you may specify optional import options that control how is the asset imported.
  147. SPtr<ImportOptions> textureImportOptions = Importer::instance().createImportOptions(exampleTexturePath);
  148. // rtti_is_of_type checks if the import options are of valid type, in case the provided path is pointing to a non-texture resource.
  149. // This is similar to dynamic_cast but uses Banshee internal RTTI system for type checking.
  150. if (rtti_is_of_type<TextureImportOptions>(textureImportOptions))
  151. {
  152. TextureImportOptions* importOptions = static_cast<TextureImportOptions*>(textureImportOptions.get());
  153. // We want maximum number of mipmaps to be generated
  154. importOptions->setGenerateMipmaps(true);
  155. // The texture is in sRGB space
  156. importOptions->setSRGB(true);
  157. }
  158. // Import texture with specified import options
  159. texture = gImporter().import<Texture>(exampleTexturePath, textureImportOptions);
  160. // Save for later use, so we don't have to import on the next run.
  161. gResources().save(texture, exampleTextureAssetPath, true);
  162. }
  163. // Load a shader.
  164. shader = gResources().load<Shader>(exampleShaderAssetPath);
  165. if (shader == nullptr) // Mesh file doesn't exist, import from the source file.
  166. {
  167. shader = gImporter().import<Shader>(exampleShaderPath);
  168. // Save for later use, so we don't have to import on the next run.
  169. gResources().save(shader, exampleShaderAssetPath, true);
  170. }
  171. }
  172. /** Create a material using the provided shader, and assign the provided texture to it. */
  173. HMaterial createMaterial(const HTexture& texture, const HShader& shader)
  174. {
  175. // Create a material with the provided shader.
  176. HMaterial exampleMaterial = Material::create(shader);
  177. // And set the texture to be used by the "tex" shader parameter. We leave the "samp"
  178. // parameter at its defaults. These parameters are defined in the shader (.bsl) file.
  179. exampleMaterial->setTexture("tex", texture);
  180. return exampleMaterial;
  181. }
  182. /** Set up the 3D object used by the example, and the camera to view the world through. */
  183. void setUp3DScene(const HMesh& mesh, const HMaterial& material)
  184. {
  185. /************************************************************************/
  186. /* SCENE OBJECT */
  187. /************************************************************************/
  188. // Now we create a scene object that has a position, orientation, scale and optionally
  189. // components to govern its logic. In this particular case we are creating a SceneObject
  190. // with a Renderable component which will render a mesh at the position of the scene object
  191. // with the provided material.
  192. // Create new scene object at (0, 0, 0)
  193. HSceneObject dragonSO = SceneObject::create("Dragon");
  194. // Attach the Renderable component and hook up the mesh we imported earlier,
  195. // and the material we created in the previous section.
  196. HRenderable renderable = dragonSO->addComponent<CRenderable>();
  197. renderable->setMesh(mesh);
  198. renderable->setMaterial(material);
  199. /************************************************************************/
  200. /* CAMERA */
  201. /************************************************************************/
  202. // In order something to render on screen we need at least one camera.
  203. // Like before, we create a new scene object at (0, 0, 0).
  204. HSceneObject sceneCameraSO = SceneObject::create("SceneCamera");
  205. // Get the primary render window we need for creating the camera. Additionally
  206. // hook up a callback so we are notified when user resizes the window.
  207. SPtr<RenderWindow> window = gApplication().getPrimaryWindow();
  208. window->onResized.connect(&renderWindowResized);
  209. // Add a Camera component that will output whatever it sees into that window
  210. // (You could also use a render texture or another window you created).
  211. sceneCamera = sceneCameraSO->addComponent<CCamera>(window);
  212. // Set up camera component properties
  213. // Priority determines in what order are cameras rendered in case multiple cameras render to the same render target.
  214. // We raise the priority slightly because later in code we have defined a GUI camera that we want to render second.
  215. sceneCamera->setPriority(1);
  216. // Set closest distance that is visible. Anything below that is clipped.
  217. sceneCamera->setNearClipDistance(5);
  218. // Set farthest distance that is visible. Anything above that is clipped.
  219. sceneCamera->setFarClipDistance(10000);
  220. // Set aspect ratio depending on the current resolution
  221. sceneCamera->setAspectRatio(windowResWidth / (float)windowResHeight);
  222. // Add a CameraFlyer component that allows us to move the camera. See CameraFlyer for more information.
  223. sceneCameraSO->addComponent<CameraFlyer>();
  224. // Position and orient the camera scene object
  225. sceneCameraSO->setPosition(Vector3(-130.0f, 140.0f, 650.0f));
  226. sceneCameraSO->lookAt(Vector3(0, 0, 0));
  227. }
  228. /** Register mouse and keyboard inputs that will be used for controlling the camera. */
  229. void setUpInput()
  230. {
  231. // Register input configuration
  232. // Banshee allows you to use VirtualInput system which will map input device buttons
  233. // and axes to arbitrary names, which allows you to change input buttons without affecting
  234. // the code that uses it, since the code is only aware of the virtual names.
  235. // If you want more direct input, see Input class.
  236. auto inputConfig = VirtualInput::instance().getConfiguration();
  237. // Camera controls for buttons (digital 0-1 input, e.g. keyboard or gamepad button)
  238. inputConfig->registerButton("Forward", BC_W);
  239. inputConfig->registerButton("Back", BC_S);
  240. inputConfig->registerButton("Left", BC_A);
  241. inputConfig->registerButton("Right", BC_D);
  242. inputConfig->registerButton("Forward", BC_UP);
  243. inputConfig->registerButton("Back", BC_BACK);
  244. inputConfig->registerButton("Left", BC_LEFT);
  245. inputConfig->registerButton("Right", BC_RIGHT);
  246. inputConfig->registerButton("FastMove", BC_LSHIFT);
  247. inputConfig->registerButton("RotateCam", BC_MOUSE_RIGHT);
  248. // Camera controls for axes (analog input, e.g. mouse or gamepad thumbstick)
  249. // These return values in [-1.0, 1.0] range.
  250. inputConfig->registerAxis("Horizontal", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseX));
  251. inputConfig->registerAxis("Vertical", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseY));
  252. // Controls that toggle the profiler overlays
  253. inputConfig->registerButton("CPUProfilerOverlay", BC_F1);
  254. inputConfig->registerButton("GPUProfilerOverlay", BC_F2);
  255. // Cache the profiler overlay buttons so when a button is pressed we can quickly
  256. // use these to determine its the one we want
  257. toggleCPUProfilerBtn = VirtualButton("CPUProfilerOverlay");
  258. toggleGPUProfilerBtn = VirtualButton("GPUProfilerOverlay");
  259. // Hook up a callback that gets triggered whenever a virtual button is released
  260. VirtualInput::instance().onButtonUp.connect(&buttonUp);
  261. }
  262. /** Set up graphical user interface used by the example. */
  263. void setUpGUI()
  264. {
  265. // Create a scene object that will contain GUI components
  266. HSceneObject guiSO = SceneObject::create("Example");
  267. // Get the primary render window we need for creating the camera.
  268. SPtr<RenderWindow> window = gApplication().getPrimaryWindow();
  269. // First we want another camera that is responsible for rendering GUI
  270. HCamera guiCamera = guiSO->addComponent<CCamera>(window);
  271. // Notify the renderer that the camera will only be used for overlays (e.g. GUI) so it can optimize its usage
  272. guiCamera->setFlag(CameraFlag::Overlay, true);
  273. // Set up GUI camera properties.
  274. // We don't care about aspect ratio for GUI camera.
  275. guiCamera->setAspectRatio(1.0f);
  276. // This camera should ignore any Renderable objects in the scene
  277. guiCamera->setLayers(0);
  278. // Don't clear this camera as that would clear anything the main camera has rendered.
  279. guiCamera->getViewport()->setRequiresClear(false, false, false);
  280. // Add a GUIWidget, the top-level GUI component, parent to all GUI elements. GUI widgets
  281. // require you to specify a viewport that they will output rendered GUI elements to.
  282. HGUIWidget gui = guiSO->addComponent<CGUIWidget>(guiCamera);
  283. // Depth allows you to control how is a GUI widget rendered in relation to other widgets
  284. // Lower depth means the widget will be rendered in front of those with higher. In this case we just
  285. // make the depth mid-range as there are no other widgets.
  286. gui->setDepth(128);
  287. // GUI skin defines how are all child elements of the GUI widget renderered. It contains all their styles
  288. // and default layout properties. We use the default skin that comes built into Banshee.
  289. gui->setSkin(BuiltinResources::instance().getGUISkin());
  290. // Get the primary GUI panel that stretches over the entire window and add to it a vertical layout
  291. // that will be using for vertically positioning messages about toggling profiler overlay.
  292. GUILayout* bottomLayout = gui->getPanel()->addNewElement<GUILayoutY>();
  293. // Add a flexible space that fills up any remaining area in the layout, making the two labels above be aligned
  294. // to the bottom of the GUI widget (and the screen).
  295. bottomLayout->addNewElement<GUIFlexibleSpace>();
  296. // Add a couple of labels to the layout with the needed messages. Labels expect a HString object that
  297. // maps into a string table and allows for easily localization.
  298. bottomLayout->addElement(GUILabel::create(HString(L"Press F1 to toggle CPU profiler overlay")));
  299. bottomLayout->addElement(GUILabel::create(HString(L"Press F2 to toggle GPU profiler overlay")));
  300. // Create a GUI panel that is used for displaying resolution and fullscreen options.
  301. GUILayout* rightLayout = gui->getPanel()->addNewElement<GUILayoutX>();
  302. // We want all the GUI elements be right aligned, so we add a flexible space first.
  303. rightLayout->addNewElement<GUIFlexibleSpace>();
  304. // And we want the elements to be vertically placed, top to bottom
  305. GUILayout* elemLayout = rightLayout->addNewElement<GUILayoutY>();
  306. // Leave 30 pixels to the right free
  307. rightLayout->addNewElement<GUIFixedSpace>(30);
  308. // Add a button that will trigger a callback when clicked
  309. toggleFullscreenButton = GUIButton::create(HString(L"Toggle fullscreen"));
  310. toggleFullscreenButton->onClick.connect(&toggleFullscreen);
  311. elemLayout->addElement(toggleFullscreenButton);
  312. // Add a profiler overlay object that is responsible for displaying CPU and GPU profiling GUI
  313. profilerOverlay = guiSO->addComponent<ProfilerOverlay>(guiCamera->_getCamera());
  314. // Set up video mode list box
  315. // First get a list of output devices
  316. const VideoModeInfo& videoModeInfo = RenderAPI::getVideoModeInfo();
  317. // Get video mode info for the primary monitor
  318. const VideoOutputInfo& primaryMonitorInfo = videoModeInfo.getOutputInfo(0);
  319. // Make the current desktop mode the default video mode
  320. selectedVideoMode = &primaryMonitorInfo.getDesktopVideoMode();
  321. // Create list box elements for each available video mode
  322. UINT32 numVideoModes = primaryMonitorInfo.getNumVideoModes();
  323. Vector<HString> videoModeLabels(numVideoModes);
  324. UINT32 selectedVideoModeIdx = 0;
  325. for (UINT32 i = 0; i < numVideoModes; i++)
  326. {
  327. const VideoMode& curVideoMode = primaryMonitorInfo.getVideoMode(i);
  328. HString videoModeLabel(L"{0} x {1} at {2}Hz");
  329. videoModeLabel.setParameter(0, toWString(curVideoMode.getWidth()));
  330. videoModeLabel.setParameter(1, toWString(curVideoMode.getHeight()));
  331. videoModeLabel.setParameter(2, toWString(Math::roundToInt(curVideoMode.getRefreshRate())));
  332. videoModeLabels[i] = videoModeLabel;
  333. videoModes.push_back(&curVideoMode);
  334. if (curVideoMode == *selectedVideoMode)
  335. selectedVideoModeIdx = i;
  336. }
  337. // Create the list box
  338. GUIListBox* videoModeListBox = GUIListBox::create(videoModeLabels);
  339. elemLayout->addElement(videoModeListBox);
  340. // Select the default (desktop) video mode
  341. videoModeListBox->selectElement(selectedVideoModeIdx);
  342. // Set up a callback to be notified when video mode changes
  343. videoModeListBox->onSelectionToggled.connect(&videoModeChanged);
  344. }
  345. /** Callback method that toggles between fullscreen and windowed modes. */
  346. void toggleFullscreen()
  347. {
  348. SPtr<RenderWindow> window = gApplication().getPrimaryWindow();
  349. // In order to toggle between full-screen and windowed mode we need to use a CoreAccessor.
  350. // Banshee is a multi-threaded engine and when you need to communicate between simulation and
  351. // core thread you will use a CoreAccessor. Calling a core accessor method will essentially
  352. // queue the method to be executed later. Since RenderWindow is a core object you need to use
  353. // CoreAccessor to modify and access it from simulation thread, except where noted otherwise.
  354. // Classes where it is not clear if they are to be used on the core or simulation thread have
  355. // it noted in their documentation. e.g. RenderWindow::setWindowed method is marked as "Core only".
  356. // Additional asserts are normally in place for debug builds which make it harder for you to accidentally
  357. // call something from the wrong thread.
  358. if (fullscreen)
  359. {
  360. window->setWindowed(gCoreAccessor(), windowResWidth, windowResHeight);
  361. }
  362. else
  363. {
  364. window->setFullscreen(gCoreAccessor(), *selectedVideoMode);
  365. }
  366. fullscreen = !fullscreen;
  367. }
  368. /** Callback triggered wheneve the user resizes the example window. */
  369. void renderWindowResized()
  370. {
  371. SPtr<RenderWindow> window = gApplication().getPrimaryWindow();
  372. const RenderWindowProperties& rwProps = window->getProperties();
  373. if (!fullscreen)
  374. {
  375. windowResWidth = rwProps.getWidth();
  376. windowResHeight = rwProps.getHeight();
  377. }
  378. sceneCamera->setAspectRatio(rwProps.getWidth() / (float)rwProps.getHeight());
  379. }
  380. /** Callback triggered when the user selects a new video mode from the GUI drop down element. */
  381. void videoModeChanged(UINT32 idx, bool enabled)
  382. {
  383. if (!enabled)
  384. return;
  385. selectedVideoMode = videoModes[idx];
  386. if (fullscreen)
  387. {
  388. SPtr<RenderWindow> window = gApplication().getPrimaryWindow();
  389. window->setFullscreen(gCoreAccessor(), *selectedVideoMode);
  390. }
  391. }
  392. /** Callback triggered when a user hits a button. */
  393. void buttonUp(const VirtualButton& button, UINT32 deviceIdx)
  394. {
  395. // Check if the pressed button is one of the either buttons we defined in "setUpExample", and toggle profiler
  396. // overlays accordingly. Device index is ignored for now, as it is assumed the user is using a single keyboard,
  397. // but if you wanted support for multiple gamepads you would check deviceIdx.
  398. if (button == toggleCPUProfilerBtn)
  399. {
  400. if (cpuProfilerActive)
  401. {
  402. profilerOverlay->hide();
  403. cpuProfilerActive = false;
  404. }
  405. else
  406. {
  407. profilerOverlay->show(ProfilerOverlayType::CPUSamples);
  408. cpuProfilerActive = true;
  409. gpuProfilerActive = false;
  410. }
  411. }
  412. else if (button == toggleGPUProfilerBtn)
  413. {
  414. if (gpuProfilerActive)
  415. {
  416. profilerOverlay->hide();
  417. gpuProfilerActive = false;
  418. }
  419. else
  420. {
  421. profilerOverlay->show(ProfilerOverlayType::GPUSamples);
  422. gpuProfilerActive = true;
  423. cpuProfilerActive = false;
  424. }
  425. }
  426. }
  427. }