2
0

Main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 "Resources/BsResources.h"
  7. #include "Resources/BsBuiltinResources.h"
  8. #include "Importer/BsImporter.h"
  9. #include "Importer/BsTextureImportOptions.h"
  10. #include "Importer/BsMeshImportOptions.h"
  11. #include "Material/BsMaterial.h"
  12. #include "Input/BsVirtualInput.h"
  13. #include "Components/BsCCamera.h"
  14. #include "Components/BsCRenderable.h"
  15. #include "Components/BsCLight.h"
  16. #include "Components/BsCSkybox.h"
  17. #include "RenderAPI/BsRenderAPI.h"
  18. #include "RenderAPI/BsRenderWindow.h"
  19. #include "Scene/BsSceneObject.h"
  20. #include "BsEngineConfig.h"
  21. // Example includes
  22. #include "CameraFlyer.h"
  23. #include "ObjectRotator.h"
  24. namespace bs
  25. {
  26. struct Assets;
  27. UINT32 windowResWidth = 1280;
  28. UINT32 windowResHeight = 720;
  29. /** Imports all of our assets and prepares GameObject that handle the example logic. */
  30. void setUpExample();
  31. /** Import mesh & textures used by the example. */
  32. void loadAssets(Assets& assets);
  33. /** Imports a mesh at the provided path and optionally scales it. */
  34. HMesh loadMesh(const Path& path, float scale = 1.0f);
  35. /**
  36. * Imports a texture at the provided path. Textures not in sRGB space (e.g. normal maps) need to be specially marked by
  37. * setting 'isSRGB' to false. Also allows for conversion of texture to cubemap by setting the 'isCubemap' parameter.
  38. * If the data should be imported in a floating point format, specify 'isHDR' to true.
  39. */
  40. HTexture loadTexture(const Path& path, bool isSRGB = true, bool isCubemap = false, bool isHDR = false);
  41. /** Create a material used by our example model. */
  42. void createMaterial(Assets& assets);
  43. /** Set up example scene objects. */
  44. void setUp3DScene(const Assets& assets);
  45. /** Set up input configuration and callbacks. */
  46. void setUpInput();
  47. /** Toggles the primary window between full-screen and windowed mode. */
  48. void toggleFullscreen();
  49. /** Called whenever the main render window is resized. */
  50. void renderWindowResized();
  51. /** Called when the selected video mode changes in the video mode list box. */
  52. void videoModeChanged(UINT32 idx, bool enabled);
  53. /** Triggered whenever a virtual button is released. */
  54. void buttonUp(const VirtualButton& button, UINT32 deviceIdx);
  55. }
  56. using namespace bs;
  57. /** Main entry point into the application. */
  58. int CALLBACK WinMain(
  59. _In_ HINSTANCE hInstance,
  60. _In_ HINSTANCE hPrevInstance,
  61. _In_ LPSTR lpCmdLine,
  62. _In_ int nCmdShow
  63. )
  64. {
  65. // Ensure all errors are reported properly
  66. CrashHandler::startUp();
  67. // Descriptor used for initializing the engine
  68. START_UP_DESC startUpDesc;
  69. // Use default values as specified by the build system
  70. startUpDesc.renderAPI = BS_RENDER_API_MODULE;
  71. startUpDesc.renderer = BS_RENDERER_MODULE;
  72. startUpDesc.audio = BS_AUDIO_MODULE;
  73. startUpDesc.physics = BS_PHYSICS_MODULE;
  74. startUpDesc.input = BS_INPUT_MODULE;
  75. // Descriptor used for initializing the primary application window.
  76. startUpDesc.primaryWindowDesc.videoMode = VideoMode(windowResWidth, windowResHeight);
  77. startUpDesc.primaryWindowDesc.title = "Banshee Example App";
  78. startUpDesc.primaryWindowDesc.fullscreen = false;
  79. startUpDesc.primaryWindowDesc.depthBuffer = false;
  80. // List of importer plugins we plan on using for importing various resources
  81. startUpDesc.importers.push_back("BansheeFreeImgImporter"); // For importing textures
  82. startUpDesc.importers.push_back("BansheeFBXImporter"); // For importing meshes
  83. startUpDesc.importers.push_back("BansheeFontImporter"); // For importing fonts
  84. startUpDesc.importers.push_back("BansheeSL"); // For importing shaders
  85. // Initializes the application with systems and primary window as defined above
  86. Application::startUp(startUpDesc);
  87. // Imports all of ours assets and prepares GameObjects that handle the example logic.
  88. setUpExample();
  89. // Runs the main loop that does most of the work. This method will exit when user closes the main
  90. // window or exits in some other way.
  91. Application::instance().runMainLoop();
  92. Application::shutDown();
  93. CrashHandler::shutDown();
  94. return 0;
  95. }
  96. namespace bs
  97. {
  98. Path dataPath = Paths::getRuntimeDataPath();
  99. Path exampleModelPath = dataPath + "Examples\\Pistol\\Pistol01.fbx";
  100. Path exampleAlbedoTexPath = dataPath + "Examples\\Pistol\\Pistol_DFS.png";
  101. Path exampleNormalsTexPath = dataPath + "Examples\\Pistol\\Pistol_NM.png";
  102. Path exampleRoughnessTexPath = dataPath + "Examples\\Pistol\\Pistol_RGH.png";
  103. Path exampleMetalnessTexPath = dataPath + "Examples\\Pistol\\Pistol_MTL.png";
  104. Path exampleSkyCubemapPath = dataPath + "Examples\\Environments\\PaperMill_E_3k.hdr";
  105. HCamera sceneCamera;
  106. /** Container for all resources used by the example. */
  107. struct Assets
  108. {
  109. HMesh exampleModel;
  110. HTexture exampleAlbedoTex;
  111. HTexture exampleNormalsTex;
  112. HTexture exampleRoughnessTex;
  113. HTexture exampleMetalnessTex;
  114. HTexture exampleSkyCubemap;
  115. HShader exampleShader;
  116. HMaterial exampleMaterial;
  117. };
  118. void setUpExample()
  119. {
  120. Assets assets;
  121. loadAssets(assets);
  122. createMaterial(assets);
  123. setUp3DScene(assets);
  124. setUpInput();
  125. }
  126. /**
  127. * Load the required resources. First try to load a pre-processed version of the resources. If they don't exist import
  128. * resources from the source formats into engine format, and save them for next time.
  129. */
  130. void loadAssets(Assets& assets)
  131. {
  132. // Load an FBX mesh.
  133. assets.exampleModel = loadMesh(exampleModelPath, 10.0f);
  134. // Load textures
  135. assets.exampleAlbedoTex = loadTexture(exampleAlbedoTexPath);
  136. assets.exampleNormalsTex = loadTexture(exampleNormalsTexPath, false);
  137. assets.exampleRoughnessTex = loadTexture(exampleRoughnessTexPath, false);
  138. assets.exampleMetalnessTex = loadTexture(exampleMetalnessTexPath, false);
  139. assets.exampleSkyCubemap = loadTexture(exampleSkyCubemapPath, false, true, true);
  140. // Load the default physically based shader for rendering opaque objects
  141. assets.exampleShader = BuiltinResources::instance().getBuiltinShader(BuiltinShader::Standard);
  142. }
  143. HMesh loadMesh(const Path& path, float scale)
  144. {
  145. Path assetPath = path;
  146. assetPath.setExtension(path.getExtension() + ".asset");
  147. HMesh model = gResources().load<Mesh>(assetPath);
  148. if (model == nullptr) // Mesh file doesn't exist, import from the source file.
  149. {
  150. // When importing you may specify optional import options that control how is the asset imported.
  151. SPtr<ImportOptions> meshImportOptions = Importer::instance().createImportOptions(path);
  152. // rtti_is_of_type checks if the import options are of valid type, in case the provided path is pointing to a
  153. // non-mesh resource. This is similar to dynamic_cast but uses Banshee internal RTTI system for type checking.
  154. if (rtti_is_of_type<MeshImportOptions>(meshImportOptions))
  155. {
  156. MeshImportOptions* importOptions = static_cast<MeshImportOptions*>(meshImportOptions.get());
  157. importOptions->setImportScale(scale);
  158. }
  159. model = gImporter().import<Mesh>(path, meshImportOptions);
  160. // Save for later use, so we don't have to import on the next run.
  161. gResources().save(model, assetPath, true);
  162. }
  163. return model;
  164. }
  165. HTexture loadTexture(const Path& path, bool isSRGB, bool isCubemap, bool isHDR)
  166. {
  167. Path assetPath = path;
  168. assetPath.setExtension(path.getExtension() + ".asset");
  169. HTexture texture = gResources().load<Texture>(assetPath);
  170. if (texture == nullptr) // Texture file doesn't exist, import from the source file.
  171. {
  172. // When importing you may specify optional import options that control how is the asset imported.
  173. SPtr<ImportOptions> textureImportOptions = Importer::instance().createImportOptions(path);
  174. // rtti_is_of_type checks if the import options are of valid type, in case the provided path is pointing to a
  175. // non-texture resource. This is similar to dynamic_cast but uses Banshee internal RTTI system for type checking.
  176. if (rtti_is_of_type<TextureImportOptions>(textureImportOptions))
  177. {
  178. TextureImportOptions* importOptions = static_cast<TextureImportOptions*>(textureImportOptions.get());
  179. // We want maximum number of mipmaps to be generated
  180. importOptions->setGenerateMipmaps(true);
  181. // If the texture is in sRGB space the system needs to know about it
  182. importOptions->setSRGB(isSRGB);
  183. // Ensures we can save the texture contents
  184. importOptions->setCPUCached(true);
  185. // Import as cubemap if needed
  186. importOptions->setIsCubemap(isCubemap);
  187. // If importing as cubemap, assume source is a panorama
  188. importOptions->setCubemapSourceType(CubemapSourceType::Cylindrical);
  189. // Importing using a HDR format if requested
  190. if (isHDR)
  191. importOptions->setFormat(PF_RG11B10F);
  192. }
  193. // Import texture with specified import options
  194. texture = gImporter().import<Texture>(path, textureImportOptions);
  195. // Save for later use, so we don't have to import on the next run.
  196. gResources().save(texture, assetPath, true);
  197. }
  198. return texture;
  199. }
  200. /** Create a material using the active shader, and assign the relevant textures to it. */
  201. void createMaterial(Assets& assets)
  202. {
  203. // Create a material with the active shader.
  204. HMaterial exampleMaterial = Material::create(assets.exampleShader);
  205. // Assign the four textures requires by the PBS shader
  206. exampleMaterial->setTexture("gAlbedoTex", assets.exampleAlbedoTex);
  207. exampleMaterial->setTexture("gNormalTex", assets.exampleNormalsTex);
  208. exampleMaterial->setTexture("gRoughnessTex", assets.exampleRoughnessTex);
  209. exampleMaterial->setTexture("gMetalnessTex", assets.exampleMetalnessTex);
  210. assets.exampleMaterial = exampleMaterial;
  211. }
  212. /** Set up the 3D object used by the example, and the camera to view the world through. */
  213. void setUp3DScene(const Assets& assets)
  214. {
  215. /************************************************************************/
  216. /* SCENE OBJECT */
  217. /************************************************************************/
  218. // Now we create a scene object that has a position, orientation, scale and optionally
  219. // components to govern its logic. In this particular case we are creating a SceneObject
  220. // with a Renderable component which will render a mesh at the position of the scene object
  221. // with the provided material.
  222. // Create new scene object at (0, 0, 0)
  223. HSceneObject pistolSO = SceneObject::create("Pistol");
  224. // Attach the Renderable component and hook up the mesh we imported earlier,
  225. // and the material we created in the previous section.
  226. HRenderable renderable = pistolSO->addComponent<CRenderable>();
  227. renderable->setMesh(assets.exampleModel);
  228. renderable->setMaterial(assets.exampleMaterial);
  229. // Add a rotator component so we can rotate the object during runtime
  230. pistolSO->addComponent<ObjectRotator>();
  231. /************************************************************************/
  232. /* SKYBOX */
  233. /************************************************************************/
  234. // Add a skybox texture for sky reflections
  235. HSceneObject skyboxSO = SceneObject::create("Skybox");
  236. HSkybox skybox = skyboxSO->addComponent<CSkybox>();
  237. skybox->setTexture(assets.exampleSkyCubemap);
  238. /************************************************************************/
  239. /* CAMERA */
  240. /************************************************************************/
  241. // In order something to render on screen we need at least one camera.
  242. // Like before, we create a new scene object at (0, 0, 0).
  243. HSceneObject sceneCameraSO = SceneObject::create("SceneCamera");
  244. // Get the primary render window we need for creating the camera. Additionally
  245. // hook up a callback so we are notified when user resizes the window.
  246. SPtr<RenderWindow> window = gApplication().getPrimaryWindow();
  247. window->onResized.connect(&renderWindowResized);
  248. // Add a Camera component that will output whatever it sees into that window
  249. // (You could also use a render texture or another window you created).
  250. sceneCamera = sceneCameraSO->addComponent<CCamera>(window);
  251. // Set up camera component properties
  252. // Set closest distance that is visible. Anything below that is clipped.
  253. sceneCamera->setNearClipDistance(0.005f);
  254. // Set farthest distance that is visible. Anything above that is clipped.
  255. sceneCamera->setFarClipDistance(1000);
  256. // Set aspect ratio depending on the current resolution
  257. sceneCamera->setAspectRatio(windowResWidth / (float)windowResHeight);
  258. // Enable multi-sample anti-aliasing for better quality
  259. sceneCamera->setMSAACount(4);
  260. // Add a CameraFlyer component that allows us to move the camera. See CameraFlyer for more information.
  261. sceneCameraSO->addComponent<CameraFlyer>();
  262. // Position and orient the camera scene object
  263. sceneCameraSO->setPosition(Vector3(0.2f, 0.1f, 0.2f));
  264. sceneCameraSO->lookAt(Vector3(-0.1f, 0, 0));
  265. }
  266. /** Register mouse and keyboard inputs that will be used for controlling the camera. */
  267. void setUpInput()
  268. {
  269. // Register input configuration
  270. // Banshee allows you to use VirtualInput system which will map input device buttons
  271. // and axes to arbitrary names, which allows you to change input buttons without affecting
  272. // the code that uses it, since the code is only aware of the virtual names.
  273. // If you want more direct input, see Input class.
  274. auto inputConfig = VirtualInput::instance().getConfiguration();
  275. // Camera controls for buttons (digital 0-1 input, e.g. keyboard or gamepad button)
  276. inputConfig->registerButton("Forward", BC_W);
  277. inputConfig->registerButton("Back", BC_S);
  278. inputConfig->registerButton("Left", BC_A);
  279. inputConfig->registerButton("Right", BC_D);
  280. inputConfig->registerButton("Forward", BC_UP);
  281. inputConfig->registerButton("Back", BC_BACK);
  282. inputConfig->registerButton("Left", BC_LEFT);
  283. inputConfig->registerButton("Right", BC_RIGHT);
  284. inputConfig->registerButton("FastMove", BC_LSHIFT);
  285. inputConfig->registerButton("RotateObj", BC_MOUSE_LEFT);
  286. inputConfig->registerButton("RotateCam", BC_MOUSE_RIGHT);
  287. // Camera controls for axes (analog input, e.g. mouse or gamepad thumbstick)
  288. // These return values in [-1.0, 1.0] range.
  289. inputConfig->registerAxis("Horizontal", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseX));
  290. inputConfig->registerAxis("Vertical", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseY));
  291. }
  292. /** Callback triggered wheneve the user resizes the example window. */
  293. void renderWindowResized()
  294. {
  295. SPtr<RenderWindow> window = gApplication().getPrimaryWindow();
  296. const RenderWindowProperties& rwProps = window->getProperties();
  297. windowResWidth = rwProps.getWidth();
  298. windowResHeight = rwProps.getHeight();
  299. sceneCamera->setAspectRatio(rwProps.getWidth() / (float)rwProps.getHeight());
  300. }
  301. }