Main.cpp 15 KB

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