Main.cpp 18 KB

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