Main.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. // Define a video mode for the resolution of the primary rendering window.
  98. VideoMode videoMode(windowResWidth, windowResHeight);
  99. // Start-up the engine using our custom MyApplication class. This will also create the primary rendering window.
  100. // We provide the initial resolution of the window, its title and fullscreen state.
  101. Application::startUp<MyApplication>(videoMode, "Banshee Example App", false);
  102. // Runs the main loop that does most of the work. This method will exit when user closes the main
  103. // window or exits in some other way.
  104. Application::instance().runMainLoop();
  105. Application::shutDown();
  106. return 0;
  107. }
  108. namespace bs { namespace ct
  109. {
  110. // Declarations for some helper methods we'll use during setup
  111. void writeBoxVertices(const AABox& box, UINT8* positions, UINT8* uvs, UINT32 stride);
  112. void writeBoxIndices(UINT32* indices);
  113. const char* getVertexProgSource();
  114. const char* getFragmentProgSource();
  115. Matrix4 createWorldViewProjectionMatrix();
  116. // Fields where we'll store the resources required during calls to render(). These are initialized in setup()
  117. // and cleaned up in shutDown()
  118. SPtr<GraphicsPipelineState> gPipelineState;
  119. SPtr<Texture> gSurfaceTex;
  120. SPtr<SamplerState> gSurfaceSampler;
  121. SPtr<GpuParams> gGpuParams;
  122. SPtr<VertexDeclaration> gVertexDecl;
  123. SPtr<VertexBuffer> gVertexBuffer;
  124. SPtr<IndexBuffer> gIndexBuffer;
  125. SPtr<RenderTexture> gRenderTarget;
  126. SPtr<RenderWindow> gRenderWindow;
  127. const bool USE_HLSL = BS_RENDER_API_MODULE == "BansheeD3D11RenderAPI";
  128. const UINT32 NUM_VERTICES = 24;
  129. const UINT32 NUM_INDICES = 36;
  130. // Structure that will hold uniform block variables for the GPU programs
  131. struct UniformBlock
  132. {
  133. Matrix4 gMatWVP; // World view projection matrix
  134. Color gTint; // Tint to apply on top of the texture
  135. };
  136. // Initializes any resources required for rendering
  137. void setup(const SPtr<RenderWindow>& renderWindow)
  138. {
  139. // This will be the primary output for our rendering (created by the main thread on start-up)
  140. gRenderWindow = renderWindow;
  141. // Create a vertex GPU program
  142. const char* vertProgSrc = getVertexProgSource();
  143. GPU_PROGRAM_DESC vertProgDesc;
  144. vertProgDesc.type = GPT_VERTEX_PROGRAM;
  145. vertProgDesc.entryPoint = "main";
  146. vertProgDesc.language = USE_HLSL ? "hlsl" : "glsl";
  147. vertProgDesc.source = vertProgSrc;
  148. SPtr<GpuProgram> vertProg = GpuProgram::create(vertProgDesc);
  149. // Create a fragment GPU program
  150. const char* fragProgSrc = getFragmentProgSource();
  151. GPU_PROGRAM_DESC fragProgDesc;
  152. fragProgDesc.type = GPT_FRAGMENT_PROGRAM;
  153. fragProgDesc.entryPoint = "main";
  154. fragProgDesc.language = USE_HLSL ? "hlsl" : "glsl";
  155. fragProgDesc.source = fragProgSrc;
  156. SPtr<GpuProgram> fragProg = GpuProgram::create(fragProgDesc);
  157. // Create a graphics pipeline state
  158. BLEND_STATE_DESC blendDesc;
  159. blendDesc.renderTargetDesc[0].blendEnable = true;
  160. blendDesc.renderTargetDesc[0].renderTargetWriteMask = 0b0111; // RGB, don't write to alpha
  161. blendDesc.renderTargetDesc[0].blendOp = BO_ADD;
  162. blendDesc.renderTargetDesc[0].srcBlend = BF_SOURCE_ALPHA;
  163. blendDesc.renderTargetDesc[0].dstBlend = BF_INV_SOURCE_ALPHA;
  164. DEPTH_STENCIL_STATE_DESC depthStencilDesc;
  165. depthStencilDesc.depthWriteEnable = false;
  166. depthStencilDesc.depthReadEnable = false;
  167. PIPELINE_STATE_DESC pipelineDesc;
  168. pipelineDesc.blendState = BlendState::create(blendDesc);
  169. pipelineDesc.depthStencilState = DepthStencilState::create(depthStencilDesc);
  170. pipelineDesc.vertexProgram = vertProg;
  171. pipelineDesc.fragmentProgram = fragProg;
  172. gPipelineState = GraphicsPipelineState::create(pipelineDesc);
  173. // Create an object containing GPU program parameters
  174. gGpuParams = GpuParams::create(gPipelineState);
  175. // Create a vertex declaration for shader inputs
  176. SPtr<VertexDataDesc> vertexDesc = VertexDataDesc::create();
  177. vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION);
  178. vertexDesc->addVertElem(VET_FLOAT2, VES_TEXCOORD);
  179. gVertexDecl = VertexDeclaration::create(vertexDesc);
  180. // Create & fill the vertex buffer for a box mesh
  181. UINT32 vertexStride = vertexDesc->getVertexStride();
  182. VERTEX_BUFFER_DESC vbDesc;
  183. vbDesc.numVerts = NUM_VERTICES;
  184. vbDesc.vertexSize = vertexStride;
  185. gVertexBuffer = VertexBuffer::create(vbDesc);
  186. UINT8* vbData = (UINT8*)gVertexBuffer->lock(0, vertexStride * NUM_VERTICES, GBL_WRITE_ONLY_DISCARD);
  187. UINT8* positions = vbData + vertexDesc->getElementOffsetFromStream(VES_POSITION);
  188. UINT8* uvs = vbData + vertexDesc->getElementOffsetFromStream(VES_TEXCOORD);
  189. AABox box(Vector3::ONE * -10.0f, Vector3::ONE * 10.0f);
  190. writeBoxVertices(box, positions, uvs, vertexStride);
  191. gVertexBuffer->unlock();
  192. // Create & fill the index buffer for a box mesh
  193. INDEX_BUFFER_DESC ibDesc;
  194. ibDesc.numIndices = NUM_INDICES;
  195. ibDesc.indexType = IT_32BIT;
  196. gIndexBuffer = IndexBuffer::create(ibDesc);
  197. UINT32* ibData = (UINT32*)gIndexBuffer->lock(0, NUM_INDICES * sizeof(UINT32), GBL_WRITE_ONLY_DISCARD);
  198. writeBoxIndices(ibData);
  199. gIndexBuffer->unlock();
  200. // Create a simple 2x2 checkerboard texture to map to the object we're about to render
  201. SPtr<PixelData> pixelData = PixelData::create(2, 2, 1, PF_R8G8B8A8);
  202. pixelData->setColorAt(Color::White, 0, 0);
  203. pixelData->setColorAt(Color::Black, 1, 0);
  204. pixelData->setColorAt(Color::White, 1, 1);
  205. pixelData->setColorAt(Color::Black, 0, 1);
  206. gSurfaceTex = Texture::create(pixelData);
  207. // Create a sampler state for the texture above
  208. SAMPLER_STATE_DESC samplerDesc;
  209. samplerDesc.minFilter = FO_POINT;
  210. samplerDesc.magFilter = FO_POINT;
  211. gSurfaceSampler = SamplerState::create(samplerDesc);
  212. // Create a color attachment texture for the render surface
  213. TEXTURE_DESC colorAttDesc;
  214. colorAttDesc.width = windowResWidth;
  215. colorAttDesc.height = windowResHeight;
  216. colorAttDesc.format = PF_R8G8B8A8;
  217. colorAttDesc.usage = TU_RENDERTARGET;
  218. SPtr<Texture> colorAtt = Texture::create(colorAttDesc);
  219. // Create a depth attachment texture for the render surface
  220. TEXTURE_DESC depthAttDesc;
  221. depthAttDesc.width = windowResWidth;
  222. depthAttDesc.height = windowResHeight;
  223. depthAttDesc.format = PF_D32;
  224. depthAttDesc.usage = TU_DEPTHSTENCIL;
  225. SPtr<Texture> depthAtt = Texture::create(depthAttDesc);
  226. // Create the render surface
  227. RENDER_TEXTURE_DESC desc;
  228. desc.colorSurfaces[0].texture = colorAtt;
  229. desc.depthStencilSurface.texture = depthAtt;
  230. gRenderTarget = RenderTexture::create(desc);
  231. }
  232. // Render the box, called every frame
  233. void render()
  234. {
  235. // Fill out the uniform block variables
  236. UniformBlock uniformBlock;
  237. uniformBlock.gMatWVP = createWorldViewProjectionMatrix();
  238. uniformBlock.gTint = Color(1.0f, 1.0f, 1.0f, 0.5f);
  239. // Create a uniform block buffer for holding the uniform variables
  240. SPtr<GpuParamBlockBuffer> uniformBuffer = GpuParamBlockBuffer::create(sizeof(UniformBlock));
  241. uniformBuffer->write(0, &uniformBlock, sizeof(uniformBlock));
  242. // Assign the uniform buffer & texture
  243. gGpuParams->setParamBlockBuffer(GPT_FRAGMENT_PROGRAM, "Params", uniformBuffer);
  244. gGpuParams->setParamBlockBuffer(GPT_VERTEX_PROGRAM, "Params", uniformBuffer);
  245. gGpuParams->setTexture(GPT_FRAGMENT_PROGRAM, "gMainTexture", gSurfaceTex);
  246. // HLSL uses separate sampler states, so we need to use a different name for the sampler
  247. if(USE_HLSL)
  248. gGpuParams->setSamplerState(GPT_FRAGMENT_PROGRAM, "gMainTexSamp", gSurfaceSampler);
  249. else
  250. gGpuParams->setSamplerState(GPT_FRAGMENT_PROGRAM, "gMainTexture", gSurfaceSampler);
  251. // Create a command buffer
  252. SPtr<CommandBuffer> cmds = CommandBuffer::create(GQT_GRAPHICS);
  253. // Get the primary render API access point
  254. RenderAPI& rapi = RenderAPI::instance();
  255. // Bind render surface & clear it
  256. rapi.setRenderTarget(gRenderTarget, false, RT_NONE, cmds);
  257. rapi.clearRenderTarget(FBT_COLOR | FBT_DEPTH, Color::Blue, 1, 0, 0xFF, cmds);
  258. // Bind the pipeline state
  259. rapi.setGraphicsPipeline(gPipelineState, cmds);
  260. // Set the vertex & index buffers, as well as vertex declaration and draw type
  261. rapi.setVertexBuffers(0, &gVertexBuffer, 1, cmds);
  262. rapi.setIndexBuffer(gIndexBuffer, cmds);
  263. rapi.setVertexDeclaration(gVertexDecl, cmds);
  264. rapi.setDrawOperation(DOT_TRIANGLE_LIST, cmds);
  265. // Bind the GPU program parameters (i.e. resource descriptors)
  266. rapi.setGpuParams(gGpuParams, cmds);
  267. // Draw
  268. rapi.drawIndexed(0, NUM_INDICES, 0, NUM_VERTICES, 1, cmds);
  269. // Submit the command buffer
  270. rapi.submitCommandBuffer(cmds);
  271. // Blit the image from the render texture, to the render window
  272. rapi.setRenderTarget(gRenderWindow);
  273. // Get the color attachment
  274. SPtr<Texture> colorTexture = gRenderTarget->getColorTexture(0);
  275. // Use the helper RendererUtility to draw a full-screen quad of the provided texture and output it to the currently
  276. // bound render target. Internally this uses the same calls we used above, just with a different pipeline and mesh.
  277. gRendererUtility().blit(colorTexture);
  278. // Present the rendered image to the user
  279. rapi.swapBuffers(gRenderWindow);
  280. }
  281. // Clean up any resources
  282. void shutdown()
  283. {
  284. gPipelineState = nullptr;
  285. gSurfaceTex = nullptr;
  286. gGpuParams = nullptr;
  287. gVertexDecl = nullptr;
  288. gVertexBuffer = nullptr;
  289. gIndexBuffer = nullptr;
  290. gRenderTarget = nullptr;
  291. gRenderWindow = nullptr;
  292. gSurfaceSampler = nullptr;
  293. }
  294. /////////////////////////////////////////////////////////////////////////////////////
  295. //////////////////////////////////HELPER METHODS/////////////////////////////////////
  296. /////////////////////////////////////////////////////////////////////////////////////
  297. void writeBoxVertices(const AABox& box, UINT8* positions, UINT8* uvs, UINT32 stride)
  298. {
  299. AABox::CornerEnum vertOrder[] =
  300. {
  301. AABox::NEAR_LEFT_BOTTOM, AABox::NEAR_RIGHT_BOTTOM, AABox::NEAR_RIGHT_TOP, AABox::NEAR_LEFT_TOP,
  302. AABox::FAR_RIGHT_BOTTOM, AABox::FAR_LEFT_BOTTOM, AABox::FAR_LEFT_TOP, AABox::FAR_RIGHT_TOP,
  303. AABox::FAR_LEFT_BOTTOM, AABox::NEAR_LEFT_BOTTOM, AABox::NEAR_LEFT_TOP, AABox::FAR_LEFT_TOP,
  304. AABox::NEAR_RIGHT_BOTTOM, AABox::FAR_RIGHT_BOTTOM, AABox::FAR_RIGHT_TOP, AABox::NEAR_RIGHT_TOP,
  305. AABox::FAR_LEFT_TOP, AABox::NEAR_LEFT_TOP, AABox::NEAR_RIGHT_TOP, AABox::FAR_RIGHT_TOP,
  306. AABox::FAR_LEFT_BOTTOM, AABox::FAR_RIGHT_BOTTOM, AABox::NEAR_RIGHT_BOTTOM, AABox::NEAR_LEFT_BOTTOM
  307. };
  308. for (auto& entry : vertOrder)
  309. {
  310. Vector3 pos = box.getCorner(entry);
  311. memcpy(positions, &pos, sizeof(pos));
  312. positions += stride;
  313. }
  314. for (UINT32 i = 0; i < 6; i++)
  315. {
  316. Vector2 uv;
  317. uv = Vector2(0.0f, 1.0f);
  318. memcpy(uvs, &uv, sizeof(uv));
  319. uvs += stride;
  320. uv = Vector2(1.0f, 1.0f);
  321. memcpy(uvs, &uv, sizeof(uv));
  322. uvs += stride;
  323. uv = Vector2(1.0f, 0.0f);
  324. memcpy(uvs, &uv, sizeof(uv));
  325. uvs += stride;
  326. uv = Vector2(0.0f, 0.0f);
  327. memcpy(uvs, &uv, sizeof(uv));
  328. uvs += stride;
  329. }
  330. }
  331. void writeBoxIndices(UINT32* indices)
  332. {
  333. for (UINT32 face = 0; face < 6; face++)
  334. {
  335. UINT32 faceVertOffset = face * 4;
  336. indices[face * 6 + 0] = faceVertOffset + 2;
  337. indices[face * 6 + 1] = faceVertOffset + 1;
  338. indices[face * 6 + 2] = faceVertOffset + 0;
  339. indices[face * 6 + 3] = faceVertOffset + 0;
  340. indices[face * 6 + 4] = faceVertOffset + 3;
  341. indices[face * 6 + 5] = faceVertOffset + 2;
  342. }
  343. }
  344. const char* getVertexProgSource()
  345. {
  346. if(USE_HLSL)
  347. {
  348. static char* src = R"(
  349. cbuffer Params
  350. {
  351. float4x4 gMatWVP;
  352. float4 gTint;
  353. }
  354. void main(
  355. in float3 inPos : POSITION,
  356. in float2 uv : TEXCOORD0,
  357. out float4 oPosition : SV_Position,
  358. out float2 oUv : TEXCOORD0)
  359. {
  360. oPosition = mul(gMatWVP, float4(inPos.xyz, 1));
  361. oUv = uv;
  362. }
  363. )";
  364. return src;
  365. }
  366. else
  367. {
  368. static char* src = R"(
  369. layout (binding = 0, std140) uniform Params
  370. {
  371. mat4 gMatWVP;
  372. vec4 gTint;
  373. };
  374. layout (location = 0) in vec3 bs_position;
  375. layout (location = 1) in vec2 bs_texcoord0;
  376. layout (location = 0) out vec2 texcoord0;
  377. out gl_PerVertex
  378. {
  379. vec4 gl_Position;
  380. };
  381. void main()
  382. {
  383. gl_Position = gMatWVP * vec4(bs_position.xyz, 1);
  384. texcoord0 = bs_texcoord0;
  385. }
  386. )";
  387. return src;
  388. }
  389. }
  390. const char* getFragmentProgSource()
  391. {
  392. if (USE_HLSL)
  393. {
  394. static char* src = R"(
  395. cbuffer Params
  396. {
  397. float4x4 gMatWVP;
  398. float4 gTint;
  399. }
  400. SamplerState gMainTexSamp : register(s0);
  401. Texture2D gMainTexture : register(t0);
  402. float4 main(in float4 inPos : SV_Position, float2 uv : TEXCOORD0) : SV_Target
  403. {
  404. float4 color = gMainTexture.Sample(gMainTexSamp, uv);
  405. return color * gTint;
  406. }
  407. )";
  408. return src;
  409. }
  410. else
  411. {
  412. static char* src = R"(
  413. layout (binding = 0, std140) uniform Params
  414. {
  415. mat4 gMatWVP;
  416. vec4 gTint;
  417. };
  418. layout (binding = 1) uniform sampler2D gMainTexture;
  419. layout (location = 0) in vec2 texcoord0;
  420. layout (location = 0) out vec4 fragColor;
  421. void main()
  422. {
  423. vec4 color = texture(gMainTexture, texcoord0.st);
  424. fragColor = color * gTint;
  425. }
  426. )";
  427. return src;
  428. }
  429. }
  430. Matrix4 createWorldViewProjectionMatrix()
  431. {
  432. Matrix4 proj = Matrix4::projectionPerspective(Degree(75.0f), 16.0f / 9.0f, 0.05f, 1000.0f);
  433. bs::RenderAPI::convertProjectionMatrix(proj, proj);
  434. Vector3 cameraPos = Vector3(0.0f, -20.0f, 50.0f);
  435. Vector3 lookDir = -Vector3::normalize(cameraPos);
  436. Quaternion cameraRot(BsIdentity);
  437. cameraRot.lookRotation(lookDir);
  438. Matrix4 view = Matrix4::view(cameraPos, cameraRot);
  439. Quaternion rotation(Vector3::UNIT_Y, Degree(gTime().getTime() * 90.0f));
  440. Matrix4 world = Matrix4::TRS(Vector3::ZERO, rotation, Vector3::ONE);
  441. Matrix4 viewProj = proj * view * world;
  442. // GLSL uses column major matrices, so transpose
  443. if(!USE_HLSL)
  444. viewProj = viewProj.transpose();
  445. return viewProj;
  446. }
  447. }}