Main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 "BsMeshImportOptions.h"
  10. #include "BsMaterial.h"
  11. #include "BsVirtualInput.h"
  12. #include "BsCCamera.h"
  13. #include "BsCRenderable.h"
  14. #include "BsCLight.h"
  15. #include "BsRenderAPI.h"
  16. #include "BsBuiltinResources.h"
  17. #include "BsRTTIType.h"
  18. #include "BsRenderWindow.h"
  19. #include "BsSceneObject.h"
  20. #include "BsCoreThread.h"
  21. #include "BsCSkybox.h"
  22. #include "BsEngineConfig.h"
  23. // Example includes
  24. #include "CameraFlyer.h"
  25. #include "ObjectRotator.h"
  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. int CALLBACK WinMain(
  61. _In_ HINSTANCE hInstance,
  62. _In_ HINSTANCE hPrevInstance,
  63. _In_ LPSTR lpCmdLine,
  64. _In_ int nCmdShow
  65. )
  66. {
  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. return 0;
  94. }
  95. namespace bs
  96. {
  97. Path dataPath = Paths::getRuntimeDataPath();
  98. Path exampleModelPath = dataPath + "Examples\\Pistol\\Pistol01.fbx";
  99. Path exampleAlbedoTexPath = dataPath + "Examples\\Pistol\\Pistol_DFS.png";
  100. Path exampleNormalsTexPath = dataPath + "Examples\\Pistol\\Pistol_NM.png";
  101. Path exampleRoughnessTexPath = dataPath + "Examples\\Pistol\\Pistol_RGH.png";
  102. Path exampleMetalnessTexPath = dataPath + "Examples\\Pistol\\Pistol_MTL.png";
  103. Path exampleSkyCubemapPath = dataPath + "Examples\\Environments\\PaperMill_E_3k.hdr";
  104. HCamera sceneCamera;
  105. /** Container for all resources used by the example. */
  106. struct Assets
  107. {
  108. HMesh exampleModel;
  109. HTexture exampleAlbedoTex;
  110. HTexture exampleNormalsTex;
  111. HTexture exampleRoughnessTex;
  112. HTexture exampleMetalnessTex;
  113. HTexture exampleSkyCubemap;
  114. HShader exampleShader;
  115. HMaterial exampleMaterial;
  116. };
  117. void setUpExample()
  118. {
  119. Assets assets;
  120. loadAssets(assets);
  121. createMaterial(assets);
  122. setUp3DScene(assets);
  123. setUpInput();
  124. }
  125. /**
  126. * Load the required resources. First try to load a pre-processed version of the resources. If they don't exist import
  127. * resources from the source formats into engine format, and save them for next time.
  128. */
  129. void loadAssets(Assets& assets)
  130. {
  131. // Load an FBX mesh.
  132. assets.exampleModel = loadMesh(exampleModelPath, 10.0f);
  133. // Load textures
  134. assets.exampleAlbedoTex = loadTexture(exampleAlbedoTexPath);
  135. assets.exampleNormalsTex = loadTexture(exampleNormalsTexPath, false);
  136. assets.exampleRoughnessTex = loadTexture(exampleRoughnessTexPath, false);
  137. assets.exampleMetalnessTex = loadTexture(exampleMetalnessTexPath, false);
  138. assets.exampleSkyCubemap = loadTexture(exampleSkyCubemapPath, false, true, true);
  139. // Load the default physically based shader for rendering opaque objects
  140. assets.exampleShader = BuiltinResources::instance().getBuiltinShader(BuiltinShader::Standard);
  141. }
  142. HMesh loadMesh(const Path& path, float scale)
  143. {
  144. Path assetPath = path;
  145. assetPath.setExtension(path.getExtension() + ".asset");
  146. HMesh model = gResources().load<Mesh>(assetPath);
  147. if (model == nullptr) // Mesh file doesn't exist, import from the source file.
  148. {
  149. // When importing you may specify optional import options that control how is the asset imported.
  150. SPtr<ImportOptions> meshImportOptions = Importer::instance().createImportOptions(path);
  151. // rtti_is_of_type checks if the import options are of valid type, in case the provided path is pointing to a
  152. // non-mesh resource. This is similar to dynamic_cast but uses Banshee internal RTTI system for type checking.
  153. if (rtti_is_of_type<MeshImportOptions>(meshImportOptions))
  154. {
  155. MeshImportOptions* importOptions = static_cast<MeshImportOptions*>(meshImportOptions.get());
  156. importOptions->setImportScale(scale);
  157. }
  158. model = gImporter().import<Mesh>(path, meshImportOptions);
  159. // Save for later use, so we don't have to import on the next run.
  160. gResources().save(model, assetPath, true);
  161. }
  162. return model;
  163. }
  164. HTexture loadTexture(const Path& path, bool isSRGB, bool isCubemap, bool isHDR)
  165. {
  166. Path assetPath = path;
  167. assetPath.setExtension(path.getExtension() + ".asset");
  168. HTexture texture = gResources().load<Texture>(assetPath);
  169. if (texture == nullptr) // Texture file doesn't exist, import from the source file.
  170. {
  171. // When importing you may specify optional import options that control how is the asset imported.
  172. SPtr<ImportOptions> textureImportOptions = Importer::instance().createImportOptions(path);
  173. // rtti_is_of_type checks if the import options are of valid type, in case the provided path is pointing to a
  174. // non-texture resource. This is similar to dynamic_cast but uses Banshee internal RTTI system for type checking.
  175. if (rtti_is_of_type<TextureImportOptions>(textureImportOptions))
  176. {
  177. TextureImportOptions* importOptions = static_cast<TextureImportOptions*>(textureImportOptions.get());
  178. // We want maximum number of mipmaps to be generated
  179. importOptions->setGenerateMipmaps(true);
  180. // If the texture is in sRGB space the system needs to know about it
  181. importOptions->setSRGB(isSRGB);
  182. // Ensures we can save the texture contents
  183. importOptions->setCPUCached(true);
  184. // Import as cubemap if needed
  185. importOptions->setIsCubemap(isCubemap);
  186. // If importing as cubemap, assume source is a panorama
  187. importOptions->setCubemapSourceType(CubemapSourceType::Cylindrical);
  188. // Importing using a HDR format if requested
  189. if (isHDR)
  190. importOptions->setFormat(PF_FLOAT_R11G11B10);
  191. }
  192. // Import texture with specified import options
  193. texture = gImporter().import<Texture>(path, textureImportOptions);
  194. // Save for later use, so we don't have to import on the next run.
  195. gResources().save(texture, assetPath, true);
  196. }
  197. return texture;
  198. }
  199. /** Create a material using the active shader, and assign the relevant textures to it. */
  200. void createMaterial(Assets& assets)
  201. {
  202. // Create a material with the active shader.
  203. HMaterial exampleMaterial = Material::create(assets.exampleShader);
  204. // Assign the four textures requires by the PBS shader
  205. exampleMaterial->setTexture("gAlbedoTex", assets.exampleAlbedoTex);
  206. exampleMaterial->setTexture("gNormalTex", assets.exampleNormalsTex);
  207. exampleMaterial->setTexture("gRoughnessTex", assets.exampleRoughnessTex);
  208. exampleMaterial->setTexture("gMetalnessTex", assets.exampleMetalnessTex);
  209. assets.exampleMaterial = exampleMaterial;
  210. }
  211. /** Set up the 3D object used by the example, and the camera to view the world through. */
  212. void setUp3DScene(const Assets& assets)
  213. {
  214. /************************************************************************/
  215. /* SCENE OBJECT */
  216. /************************************************************************/
  217. // Now we create a scene object that has a position, orientation, scale and optionally
  218. // components to govern its logic. In this particular case we are creating a SceneObject
  219. // with a Renderable component which will render a mesh at the position of the scene object
  220. // with the provided material.
  221. // Create new scene object at (0, 0, 0)
  222. HSceneObject pistolSO = SceneObject::create("Pistol");
  223. // Attach the Renderable component and hook up the mesh we imported earlier,
  224. // and the material we created in the previous section.
  225. HRenderable renderable = pistolSO->addComponent<CRenderable>();
  226. renderable->setMesh(assets.exampleModel);
  227. renderable->setMaterial(assets.exampleMaterial);
  228. // Add a rotator component so we can rotate the object during runtime
  229. pistolSO->addComponent<ObjectRotator>();
  230. /************************************************************************/
  231. /* SKYBOX */
  232. /************************************************************************/
  233. // Add a skybox texture for sky reflections
  234. HSceneObject skyboxSO = SceneObject::create("Skybox");
  235. HSkybox skybox = skyboxSO->addComponent<CSkybox>();
  236. skybox->setTexture(assets.exampleSkyCubemap);
  237. /************************************************************************/
  238. /* CAMERA */
  239. /************************************************************************/
  240. // In order something to render on screen we need at least one camera.
  241. // Like before, we create a new scene object at (0, 0, 0).
  242. HSceneObject sceneCameraSO = SceneObject::create("SceneCamera");
  243. // Get the primary render window we need for creating the camera. Additionally
  244. // hook up a callback so we are notified when user resizes the window.
  245. SPtr<RenderWindow> window = gApplication().getPrimaryWindow();
  246. window->onResized.connect(&renderWindowResized);
  247. // Add a Camera component that will output whatever it sees into that window
  248. // (You could also use a render texture or another window you created).
  249. sceneCamera = sceneCameraSO->addComponent<CCamera>(window);
  250. // Set up camera component properties
  251. // Set closest distance that is visible. Anything below that is clipped.
  252. sceneCamera->setNearClipDistance(0.005f);
  253. // Set farthest distance that is visible. Anything above that is clipped.
  254. sceneCamera->setFarClipDistance(1000);
  255. // Set aspect ratio depending on the current resolution
  256. sceneCamera->setAspectRatio(windowResWidth / (float)windowResHeight);
  257. // Enable multi-sample anti-aliasing for better quality
  258. sceneCamera->setMSAACount(4);
  259. // Add a CameraFlyer component that allows us to move the camera. See CameraFlyer for more information.
  260. sceneCameraSO->addComponent<CameraFlyer>();
  261. // Position and orient the camera scene object
  262. sceneCameraSO->setPosition(Vector3(0.2f, 0.1f, 0.2f));
  263. sceneCameraSO->lookAt(Vector3(-0.1f, 0, 0));
  264. }
  265. /** Register mouse and keyboard inputs that will be used for controlling the camera. */
  266. void setUpInput()
  267. {
  268. // Register input configuration
  269. // Banshee allows you to use VirtualInput system which will map input device buttons
  270. // and axes to arbitrary names, which allows you to change input buttons without affecting
  271. // the code that uses it, since the code is only aware of the virtual names.
  272. // If you want more direct input, see Input class.
  273. auto inputConfig = VirtualInput::instance().getConfiguration();
  274. // Camera controls for buttons (digital 0-1 input, e.g. keyboard or gamepad button)
  275. inputConfig->registerButton("Forward", BC_W);
  276. inputConfig->registerButton("Back", BC_S);
  277. inputConfig->registerButton("Left", BC_A);
  278. inputConfig->registerButton("Right", BC_D);
  279. inputConfig->registerButton("Forward", BC_UP);
  280. inputConfig->registerButton("Back", BC_BACK);
  281. inputConfig->registerButton("Left", BC_LEFT);
  282. inputConfig->registerButton("Right", BC_RIGHT);
  283. inputConfig->registerButton("FastMove", BC_LSHIFT);
  284. inputConfig->registerButton("RotateObj", BC_MOUSE_LEFT);
  285. inputConfig->registerButton("RotateCam", BC_MOUSE_RIGHT);
  286. // Camera controls for axes (analog input, e.g. mouse or gamepad thumbstick)
  287. // These return values in [-1.0, 1.0] range.
  288. inputConfig->registerAxis("Horizontal", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseX));
  289. inputConfig->registerAxis("Vertical", VIRTUAL_AXIS_DESC((UINT32)InputAxis::MouseY));
  290. }
  291. /** Callback triggered wheneve the user resizes the example window. */
  292. void renderWindowResized()
  293. {
  294. SPtr<RenderWindow> window = gApplication().getPrimaryWindow();
  295. const RenderWindowProperties& rwProps = window->getProperties();
  296. windowResWidth = rwProps.getWidth();
  297. windowResHeight = rwProps.getHeight();
  298. sceneCamera->setAspectRatio(rwProps.getWidth() / (float)rwProps.getHeight());
  299. }
  300. }