Main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include <windows.h>
  4. #include "BsApplication.h"
  5. #include "BsMaterial.h"
  6. #include "BsRenderAPI.h"
  7. #include "BsRenderWindow.h"
  8. #include "BsCoreThread.h"
  9. #include "BsCommandBuffer.h"
  10. #include "BsGpuProgram.h"
  11. #include "BsGpuPipelineState.h"
  12. #include "BsBlendState.h"
  13. #include "BsDepthStencilState.h"
  14. #include "BsGpuParamBlockBuffer.h"
  15. #include "BsVertexDataDesc.h"
  16. #include "BsMeshData.h"
  17. #include "BsIndexBuffer.h"
  18. #include "BsQuaternion.h"
  19. #include "BsTime.h"
  20. #include "BsRendererUtility.h"
  21. #include <BsEngineConfig.h>
  22. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  23. // This example uses the low-level rendering API to render a textured cube mesh. This is opposed to using scene objects
  24. // and components, in which case objects are rendered automatically based on their transform and other properties.
  25. //
  26. // Using low-level rendering API gives you full control over rendering, similar to using Vulkan, DirectX or OpenGL APIs.
  27. //
  28. // In order to use the low-level rendering system we need to override the Application class so we get notified of updates
  29. // and start-up/shut-down events. This is normally not necessary for a high level scene object based model.
  30. //
  31. // The rendering is performed on the core (i.e. rendering) thread, as opposed to the main thread, where majority of
  32. // Banshee's code executes.
  33. //
  34. // The example first sets up necessary resources, like GPU programs, pipeline state, vertex & index buffers. Then every
  35. // frame it binds the necessary rendering resources and executes the draw call.
  36. //
  37. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  38. namespace bs
  39. {
  40. UINT32 windowResWidth = 1280;
  41. UINT32 windowResHeight = 720;
  42. // Declare the methods we'll use to do work on the core thread. Note the "ct" namespace, which we use because we render
  43. // on the core thread (ct = core thread). Every object usable on the core thread lives in this namespace.
  44. namespace ct
  45. {
  46. void setup(const SPtr<RenderWindow>& renderWindow);
  47. void render();
  48. void shutdown();
  49. }
  50. // Override the default Application so we can get notified when engine starts-up, shuts-down and when it executes
  51. // every frame
  52. class MyApplication : public Application
  53. {
  54. public:
  55. // Pass along the start-up structure to the parent, we don't need to handle it
  56. MyApplication(const START_UP_DESC& desc)
  57. :Application(desc)
  58. { }
  59. private:
  60. // Called when the engine is first started up
  61. void onStartUp() override
  62. {
  63. // Ensure all parent systems are initialized first
  64. Application::onStartUp();
  65. // Get the primary window that was created during start-up. This will be the final desination for all our
  66. // rendering.
  67. SPtr<RenderWindow> renderWindow = getPrimaryWindow();
  68. // Get the version of the render window usable on the core thread, and send it along to setup()
  69. SPtr<ct::RenderWindow> renderWindowCore = renderWindow->getCore();
  70. // Initialize all the resources we need for rendering. Since we do rendering on a separate thread (the "core
  71. // thread"), we don't call the method directly, but rather queue it for execution using the CoreThread class.
  72. gCoreThread().queueCommand(std::bind(&ct::setup, renderWindowCore));
  73. }
  74. // Called when the engine is about to be shut down
  75. void onShutDown() override
  76. {
  77. gCoreThread().queueCommand(&ct::shutdown);
  78. // Shut-down engine components
  79. Application::onShutDown();
  80. }
  81. // Called every frame, before any other engine system (optionally use postUpdate())
  82. void preUpdate() override
  83. {
  84. gCoreThread().queueCommand(&ct::render);
  85. }
  86. };
  87. }
  88. using namespace bs;
  89. // Main entry point into the application
  90. int CALLBACK WinMain(
  91. _In_ HINSTANCE hInstance,
  92. _In_ HINSTANCE hPrevInstance,
  93. _In_ LPSTR lpCmdLine,
  94. _In_ int nCmdShow
  95. )
  96. {
  97. // Ensure all errors are reported properly
  98. CrashHandler::startUp();
  99. // Define a video mode for the resolution of the primary rendering window.
  100. VideoMode videoMode(windowResWidth, windowResHeight);
  101. // Start-up the engine using our custom MyApplication class. This will also create the primary rendering window.
  102. // We provide the initial resolution of the window, its title and fullscreen state.
  103. Application::startUp<MyApplication>(videoMode, "Banshee Example App", false);
  104. // Runs the main loop that does most of the work. This method will exit when user closes the main
  105. // window or exits in some other way.
  106. Application::instance().runMainLoop();
  107. Application::shutDown();
  108. CrashHandler::shutDown();
  109. return 0;
  110. }
  111. namespace bs { namespace ct
  112. {
  113. // Declarations for some helper methods we'll use during setup
  114. void writeBoxVertices(const AABox& box, UINT8* positions, UINT8* uvs, UINT32 stride);
  115. void writeBoxIndices(UINT32* indices);
  116. const char* getVertexProgSource();
  117. const char* getFragmentProgSource();
  118. Matrix4 createWorldViewProjectionMatrix();
  119. // Fields where we'll store the resources required during calls to render(). These are initialized in setup()
  120. // and cleaned up in shutDown()
  121. SPtr<GraphicsPipelineState> gPipelineState;
  122. SPtr<Texture> gSurfaceTex;
  123. SPtr<SamplerState> gSurfaceSampler;
  124. SPtr<GpuParams> gGpuParams;
  125. SPtr<VertexDeclaration> gVertexDecl;
  126. SPtr<VertexBuffer> gVertexBuffer;
  127. SPtr<IndexBuffer> gIndexBuffer;
  128. SPtr<RenderTexture> gRenderTarget;
  129. SPtr<RenderWindow> gRenderWindow;
  130. const bool USE_HLSL = BS_RENDER_API_MODULE == "BansheeD3D11RenderAPI";
  131. const UINT32 NUM_VERTICES = 24;
  132. const UINT32 NUM_INDICES = 36;
  133. // Structure that will hold uniform block variables for the GPU programs
  134. struct UniformBlock
  135. {
  136. Matrix4 gMatWVP; // World view projection matrix
  137. Color gTint; // Tint to apply on top of the texture
  138. };
  139. // Initializes any resources required for rendering
  140. void setup(const SPtr<RenderWindow>& renderWindow)
  141. {
  142. // This will be the primary output for our rendering (created by the main thread on start-up)
  143. gRenderWindow = renderWindow;
  144. // Create a vertex GPU program
  145. const char* vertProgSrc = getVertexProgSource();
  146. GPU_PROGRAM_DESC vertProgDesc;
  147. vertProgDesc.type = GPT_VERTEX_PROGRAM;
  148. vertProgDesc.entryPoint = "main";
  149. vertProgDesc.language = USE_HLSL ? "hlsl" : "glsl";
  150. vertProgDesc.source = vertProgSrc;
  151. SPtr<GpuProgram> vertProg = GpuProgram::create(vertProgDesc);
  152. // Create a fragment GPU program
  153. const char* fragProgSrc = getFragmentProgSource();
  154. GPU_PROGRAM_DESC fragProgDesc;
  155. fragProgDesc.type = GPT_FRAGMENT_PROGRAM;
  156. fragProgDesc.entryPoint = "main";
  157. fragProgDesc.language = USE_HLSL ? "hlsl" : "glsl";
  158. fragProgDesc.source = fragProgSrc;
  159. SPtr<GpuProgram> fragProg = GpuProgram::create(fragProgDesc);
  160. // Create a graphics pipeline state
  161. BLEND_STATE_DESC blendDesc;
  162. blendDesc.renderTargetDesc[0].blendEnable = true;
  163. blendDesc.renderTargetDesc[0].renderTargetWriteMask = 0b0111; // RGB, don't write to alpha
  164. blendDesc.renderTargetDesc[0].blendOp = BO_ADD;
  165. blendDesc.renderTargetDesc[0].srcBlend = BF_SOURCE_ALPHA;
  166. blendDesc.renderTargetDesc[0].dstBlend = BF_INV_SOURCE_ALPHA;
  167. DEPTH_STENCIL_STATE_DESC depthStencilDesc;
  168. depthStencilDesc.depthWriteEnable = false;
  169. depthStencilDesc.depthReadEnable = false;
  170. PIPELINE_STATE_DESC pipelineDesc;
  171. pipelineDesc.blendState = BlendState::create(blendDesc);
  172. pipelineDesc.depthStencilState = DepthStencilState::create(depthStencilDesc);
  173. pipelineDesc.vertexProgram = vertProg;
  174. pipelineDesc.fragmentProgram = fragProg;
  175. gPipelineState = GraphicsPipelineState::create(pipelineDesc);
  176. // Create an object containing GPU program parameters
  177. gGpuParams = GpuParams::create(gPipelineState);
  178. // Create a vertex declaration for shader inputs
  179. SPtr<VertexDataDesc> vertexDesc = VertexDataDesc::create();
  180. vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION);
  181. vertexDesc->addVertElem(VET_FLOAT2, VES_TEXCOORD);
  182. gVertexDecl = VertexDeclaration::create(vertexDesc);
  183. // Create & fill the vertex buffer for a box mesh
  184. UINT32 vertexStride = vertexDesc->getVertexStride();
  185. VERTEX_BUFFER_DESC vbDesc;
  186. vbDesc.numVerts = NUM_VERTICES;
  187. vbDesc.vertexSize = vertexStride;
  188. gVertexBuffer = VertexBuffer::create(vbDesc);
  189. UINT8* vbData = (UINT8*)gVertexBuffer->lock(0, vertexStride * NUM_VERTICES, GBL_WRITE_ONLY_DISCARD);
  190. UINT8* positions = vbData + vertexDesc->getElementOffsetFromStream(VES_POSITION);
  191. UINT8* uvs = vbData + vertexDesc->getElementOffsetFromStream(VES_TEXCOORD);
  192. AABox box(Vector3::ONE * -10.0f, Vector3::ONE * 10.0f);
  193. writeBoxVertices(box, positions, uvs, vertexStride);
  194. gVertexBuffer->unlock();
  195. // Create & fill the index buffer for a box mesh
  196. INDEX_BUFFER_DESC ibDesc;
  197. ibDesc.numIndices = NUM_INDICES;
  198. ibDesc.indexType = IT_32BIT;
  199. gIndexBuffer = IndexBuffer::create(ibDesc);
  200. UINT32* ibData = (UINT32*)gIndexBuffer->lock(0, NUM_INDICES * sizeof(UINT32), GBL_WRITE_ONLY_DISCARD);
  201. writeBoxIndices(ibData);
  202. gIndexBuffer->unlock();
  203. // Create a simple 2x2 checkerboard texture to map to the object we're about to render
  204. SPtr<PixelData> pixelData = PixelData::create(2, 2, 1, PF_R8G8B8A8);
  205. pixelData->setColorAt(Color::White, 0, 0);
  206. pixelData->setColorAt(Color::Black, 1, 0);
  207. pixelData->setColorAt(Color::White, 1, 1);
  208. pixelData->setColorAt(Color::Black, 0, 1);
  209. gSurfaceTex = Texture::create(pixelData);
  210. // Create a sampler state for the texture above
  211. SAMPLER_STATE_DESC samplerDesc;
  212. samplerDesc.minFilter = FO_POINT;
  213. samplerDesc.magFilter = FO_POINT;
  214. gSurfaceSampler = SamplerState::create(samplerDesc);
  215. // Create a color attachment texture for the render surface
  216. TEXTURE_DESC colorAttDesc;
  217. colorAttDesc.width = windowResWidth;
  218. colorAttDesc.height = windowResHeight;
  219. colorAttDesc.format = PF_R8G8B8A8;
  220. colorAttDesc.usage = TU_RENDERTARGET;
  221. SPtr<Texture> colorAtt = Texture::create(colorAttDesc);
  222. // Create a depth attachment texture for the render surface
  223. TEXTURE_DESC depthAttDesc;
  224. depthAttDesc.width = windowResWidth;
  225. depthAttDesc.height = windowResHeight;
  226. depthAttDesc.format = PF_D32;
  227. depthAttDesc.usage = TU_DEPTHSTENCIL;
  228. SPtr<Texture> depthAtt = Texture::create(depthAttDesc);
  229. // Create the render surface
  230. RENDER_TEXTURE_DESC desc;
  231. desc.colorSurfaces[0].texture = colorAtt;
  232. desc.depthStencilSurface.texture = depthAtt;
  233. gRenderTarget = RenderTexture::create(desc);
  234. }
  235. // Render the box, called every frame
  236. void render()
  237. {
  238. // Fill out the uniform block variables
  239. UniformBlock uniformBlock;
  240. uniformBlock.gMatWVP = createWorldViewProjectionMatrix();
  241. uniformBlock.gTint = Color(1.0f, 1.0f, 1.0f, 0.5f);
  242. // Create a uniform block buffer for holding the uniform variables
  243. SPtr<GpuParamBlockBuffer> uniformBuffer = GpuParamBlockBuffer::create(sizeof(UniformBlock));
  244. uniformBuffer->write(0, &uniformBlock, sizeof(uniformBlock));
  245. // Assign the uniform buffer & texture
  246. gGpuParams->setParamBlockBuffer(GPT_FRAGMENT_PROGRAM, "Params", uniformBuffer);
  247. gGpuParams->setParamBlockBuffer(GPT_VERTEX_PROGRAM, "Params", uniformBuffer);
  248. gGpuParams->setTexture(GPT_FRAGMENT_PROGRAM, "gMainTexture", gSurfaceTex);
  249. // HLSL uses separate sampler states, so we need to use a different name for the sampler
  250. if(USE_HLSL)
  251. gGpuParams->setSamplerState(GPT_FRAGMENT_PROGRAM, "gMainTexSamp", gSurfaceSampler);
  252. else
  253. gGpuParams->setSamplerState(GPT_FRAGMENT_PROGRAM, "gMainTexture", gSurfaceSampler);
  254. // Create a command buffer
  255. SPtr<CommandBuffer> cmds = CommandBuffer::create(GQT_GRAPHICS);
  256. // Get the primary render API access point
  257. RenderAPI& rapi = RenderAPI::instance();
  258. // Bind render surface & clear it
  259. rapi.setRenderTarget(gRenderTarget, 0, RT_NONE, cmds);
  260. rapi.clearRenderTarget(FBT_COLOR | FBT_DEPTH, Color::Blue, 1, 0, 0xFF, cmds);
  261. // Bind the pipeline state
  262. rapi.setGraphicsPipeline(gPipelineState, cmds);
  263. // Set the vertex & index buffers, as well as vertex declaration and draw type
  264. rapi.setVertexBuffers(0, &gVertexBuffer, 1, cmds);
  265. rapi.setIndexBuffer(gIndexBuffer, cmds);
  266. rapi.setVertexDeclaration(gVertexDecl, cmds);
  267. rapi.setDrawOperation(DOT_TRIANGLE_LIST, cmds);
  268. // Bind the GPU program parameters (i.e. resource descriptors)
  269. rapi.setGpuParams(gGpuParams, cmds);
  270. // Draw
  271. rapi.drawIndexed(0, NUM_INDICES, 0, NUM_VERTICES, 1, cmds);
  272. // Submit the command buffer
  273. rapi.submitCommandBuffer(cmds);
  274. // Blit the image from the render texture, to the render window
  275. rapi.setRenderTarget(gRenderWindow);
  276. // Get the color attachment
  277. SPtr<Texture> colorTexture = gRenderTarget->getColorTexture(0);
  278. // Use the helper RendererUtility to draw a full-screen quad of the provided texture and output it to the currently
  279. // bound render target. Internally this uses the same calls we used above, just with a different pipeline and mesh.
  280. gRendererUtility().blit(colorTexture);
  281. // Present the rendered image to the user
  282. rapi.swapBuffers(gRenderWindow);
  283. }
  284. // Clean up any resources
  285. void shutdown()
  286. {
  287. gPipelineState = nullptr;
  288. gSurfaceTex = nullptr;
  289. gGpuParams = nullptr;
  290. gVertexDecl = nullptr;
  291. gVertexBuffer = nullptr;
  292. gIndexBuffer = nullptr;
  293. gRenderTarget = nullptr;
  294. gRenderWindow = nullptr;
  295. gSurfaceSampler = nullptr;
  296. }
  297. /////////////////////////////////////////////////////////////////////////////////////
  298. //////////////////////////////////HELPER METHODS/////////////////////////////////////
  299. /////////////////////////////////////////////////////////////////////////////////////
  300. void writeBoxVertices(const AABox& box, UINT8* positions, UINT8* uvs, UINT32 stride)
  301. {
  302. AABox::Corner vertOrder[] =
  303. {
  304. AABox::NEAR_LEFT_BOTTOM, AABox::NEAR_RIGHT_BOTTOM, AABox::NEAR_RIGHT_TOP, AABox::NEAR_LEFT_TOP,
  305. AABox::FAR_RIGHT_BOTTOM, AABox::FAR_LEFT_BOTTOM, AABox::FAR_LEFT_TOP, AABox::FAR_RIGHT_TOP,
  306. AABox::FAR_LEFT_BOTTOM, AABox::NEAR_LEFT_BOTTOM, AABox::NEAR_LEFT_TOP, AABox::FAR_LEFT_TOP,
  307. AABox::NEAR_RIGHT_BOTTOM, AABox::FAR_RIGHT_BOTTOM, AABox::FAR_RIGHT_TOP, AABox::NEAR_RIGHT_TOP,
  308. AABox::FAR_LEFT_TOP, AABox::NEAR_LEFT_TOP, AABox::NEAR_RIGHT_TOP, AABox::FAR_RIGHT_TOP,
  309. AABox::FAR_LEFT_BOTTOM, AABox::FAR_RIGHT_BOTTOM, AABox::NEAR_RIGHT_BOTTOM, AABox::NEAR_LEFT_BOTTOM
  310. };
  311. for (auto& entry : vertOrder)
  312. {
  313. Vector3 pos = box.getCorner(entry);
  314. memcpy(positions, &pos, sizeof(pos));
  315. positions += stride;
  316. }
  317. for (UINT32 i = 0; i < 6; i++)
  318. {
  319. Vector2 uv;
  320. uv = Vector2(0.0f, 1.0f);
  321. memcpy(uvs, &uv, sizeof(uv));
  322. uvs += stride;
  323. uv = Vector2(1.0f, 1.0f);
  324. memcpy(uvs, &uv, sizeof(uv));
  325. uvs += stride;
  326. uv = Vector2(1.0f, 0.0f);
  327. memcpy(uvs, &uv, sizeof(uv));
  328. uvs += stride;
  329. uv = Vector2(0.0f, 0.0f);
  330. memcpy(uvs, &uv, sizeof(uv));
  331. uvs += stride;
  332. }
  333. }
  334. void writeBoxIndices(UINT32* indices)
  335. {
  336. for (UINT32 face = 0; face < 6; face++)
  337. {
  338. UINT32 faceVertOffset = face * 4;
  339. indices[face * 6 + 0] = faceVertOffset + 2;
  340. indices[face * 6 + 1] = faceVertOffset + 1;
  341. indices[face * 6 + 2] = faceVertOffset + 0;
  342. indices[face * 6 + 3] = faceVertOffset + 0;
  343. indices[face * 6 + 4] = faceVertOffset + 3;
  344. indices[face * 6 + 5] = faceVertOffset + 2;
  345. }
  346. }
  347. const char* getVertexProgSource()
  348. {
  349. if(USE_HLSL)
  350. {
  351. static char* src = R"(
  352. cbuffer Params
  353. {
  354. float4x4 gMatWVP;
  355. float4 gTint;
  356. }
  357. void main(
  358. in float3 inPos : POSITION,
  359. in float2 uv : TEXCOORD0,
  360. out float4 oPosition : SV_Position,
  361. out float2 oUv : TEXCOORD0)
  362. {
  363. oPosition = mul(gMatWVP, float4(inPos.xyz, 1));
  364. oUv = uv;
  365. }
  366. )";
  367. return src;
  368. }
  369. else
  370. {
  371. static char* src = R"(
  372. layout (binding = 0, std140) uniform Params
  373. {
  374. mat4 gMatWVP;
  375. vec4 gTint;
  376. };
  377. layout (location = 0) in vec3 bs_position;
  378. layout (location = 1) in vec2 bs_texcoord0;
  379. layout (location = 0) out vec2 texcoord0;
  380. out gl_PerVertex
  381. {
  382. vec4 gl_Position;
  383. };
  384. void main()
  385. {
  386. gl_Position = gMatWVP * vec4(bs_position.xyz, 1);
  387. texcoord0 = bs_texcoord0;
  388. }
  389. )";
  390. return src;
  391. }
  392. }
  393. const char* getFragmentProgSource()
  394. {
  395. if (USE_HLSL)
  396. {
  397. static char* src = R"(
  398. cbuffer Params
  399. {
  400. float4x4 gMatWVP;
  401. float4 gTint;
  402. }
  403. SamplerState gMainTexSamp : register(s0);
  404. Texture2D gMainTexture : register(t0);
  405. float4 main(in float4 inPos : SV_Position, float2 uv : TEXCOORD0) : SV_Target
  406. {
  407. float4 color = gMainTexture.Sample(gMainTexSamp, uv);
  408. return color * gTint;
  409. }
  410. )";
  411. return src;
  412. }
  413. else
  414. {
  415. static char* src = R"(
  416. layout (binding = 0, std140) uniform Params
  417. {
  418. mat4 gMatWVP;
  419. vec4 gTint;
  420. };
  421. layout (binding = 1) uniform sampler2D gMainTexture;
  422. layout (location = 0) in vec2 texcoord0;
  423. layout (location = 0) out vec4 fragColor;
  424. void main()
  425. {
  426. vec4 color = texture(gMainTexture, texcoord0.st);
  427. fragColor = color * gTint;
  428. }
  429. )";
  430. return src;
  431. }
  432. }
  433. Matrix4 createWorldViewProjectionMatrix()
  434. {
  435. Matrix4 proj = Matrix4::projectionPerspective(Degree(75.0f), 16.0f / 9.0f, 0.05f, 1000.0f);
  436. bs::RenderAPI::convertProjectionMatrix(proj, proj);
  437. Vector3 cameraPos = Vector3(0.0f, -20.0f, 50.0f);
  438. Vector3 lookDir = -Vector3::normalize(cameraPos);
  439. Quaternion cameraRot(BsIdentity);
  440. cameraRot.lookRotation(lookDir);
  441. Matrix4 view = Matrix4::view(cameraPos, cameraRot);
  442. Quaternion rotation(Vector3::UNIT_Y, Degree(gTime().getTime() * 90.0f));
  443. Matrix4 world = Matrix4::TRS(Vector3::ZERO, rotation, Vector3::ONE);
  444. Matrix4 viewProj = proj * view * world;
  445. // GLSL uses column major matrices, so transpose
  446. if(!USE_HLSL)
  447. viewProj = viewProj.transpose();
  448. return viewProj;
  449. }
  450. }}