Worldstone
 All Classes Files Functions Variables Enumerations Enumerator Macros Pages
bgfxUtils.cpp
1 /*
2  * Copyright 2011-2018 Branimir Karadzic. All rights reserved.
3  * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
4  */
5 #include "bgfxUtils.h"
6 #include <bx/bx.h>
7 #include <bx/readerwriter.h>
8 #include <bx/debug.h>
9 #include <bx/file.h>
10 
11 static const bgfx::Memory* loadMem(bx::FileReaderI* _reader, const char* _filePath)
12 {
13  if (bx::open(_reader, _filePath))
14  {
15  uint32_t size = (uint32_t)bx::getSize(_reader);
16  const bgfx::Memory* mem = bgfx::alloc(size + 1);
17  bx::read(_reader, mem->data, static_cast<int32_t>(size));
18  bx::close(_reader);
19  mem->data[mem->size - 1] = '\0';
20  return mem;
21  }
22 
23  bx::debugPrintf("Failed to load %s.\n", _filePath);
24  return nullptr;
25 }
26 
27 static bgfx::ShaderHandle loadShader(bx::FileReaderI* _reader, const char* _name)
28 {
29  char filePath[512];
30 
31  const char* shaderPath = "???";
32 
33  switch (bgfx::getRendererType())
34  {
35  case bgfx::RendererType::Noop:
36  case bgfx::RendererType::Direct3D9: shaderPath = "shaders/dx9/"; break;
37  case bgfx::RendererType::Direct3D11:
38  case bgfx::RendererType::Direct3D12: shaderPath = "shaders/dx11/"; break;
39  case bgfx::RendererType::Gnm: shaderPath = "shaders/pssl/"; break;
40  case bgfx::RendererType::Metal: shaderPath = "shaders/metal/"; break;
41  case bgfx::RendererType::OpenGL: shaderPath = "shaders/glsl/"; break;
42  case bgfx::RendererType::OpenGLES: shaderPath = "shaders/essl/"; break;
43  case bgfx::RendererType::Vulkan: shaderPath = "shaders/spirv/"; break;
44 
45  case bgfx::RendererType::Count:
46  BX_CHECK(false, "You should not be here!");
47  break;
48  }
49 
50  bx::strCopy(filePath, BX_COUNTOF(filePath), shaderPath);
51  bx::strCat(filePath, BX_COUNTOF(filePath), _name);
52  bx::strCat(filePath, BX_COUNTOF(filePath), ".bin");
53 
54  bgfx::ShaderHandle handle = bgfx::createShader(loadMem(_reader, filePath));
55  bgfx::setName(handle, filePath);
56 
57  return handle;
58 }
59 
60 bgfx::ShaderHandle loadShader(const char* _name)
61 {
62  bx::FileReader fileReader;
63  return loadShader(&fileReader, _name);
64 }
65 
66 bgfx::ProgramHandle loadProgram(bx::FileReaderI* _reader, const char* _vsName, const char* _fsName)
67 {
68  bgfx::ShaderHandle vsh = loadShader(_reader, _vsName);
69  bgfx::ShaderHandle fsh = BGFX_INVALID_HANDLE;
70  if (nullptr != _fsName)
71  {
72  fsh = loadShader(_reader, _fsName);
73  }
74 
75  return bgfx::createProgram(vsh, fsh, true /* destroy shaders when program is destroyed */);
76 }
77 
78 bgfx::ProgramHandle loadProgram(const char* _vsName, const char* _fsName)
79 {
80  bx::FileReader fileReader;
81  return loadProgram(&fileReader, _vsName, _fsName);
82 }