void write(bx::WriterI* _writer, const uint8_t* _vertices, uint32_t _numVertices, const bgfx::VertexDecl& _decl, const uint16_t* _indices, uint32_t _numIndices, const std::string& _material, const PrimitiveArray& _primitives) { uint32_t stride = _decl.getStride(); bx::write(_writer, BGFX_CHUNK_MAGIC_VB); writeBounds(_writer, _vertices, _numVertices, stride); bx::write(_writer, _decl); bx::write(_writer, uint16_t(_numVertices) ); bx::write(_writer, _vertices, _numVertices*stride); bx::write(_writer, BGFX_CHUNK_MAGIC_IB); bx::write(_writer, _numIndices); bx::write(_writer, _indices, _numIndices*2); bx::write(_writer, BGFX_CHUNK_MAGIC_PRI); uint16_t nameLen = uint16_t(_material.size() ); bx::write(_writer, nameLen); bx::write(_writer, _material.c_str(), nameLen); bx::write(_writer, uint16_t(_primitives.size() ) ); for (PrimitiveArray::const_iterator primIt = _primitives.begin(); primIt != _primitives.end(); ++primIt) { const Primitive& prim = *primIt; nameLen = uint16_t(prim.m_name.size() ); bx::write(_writer, nameLen); bx::write(_writer, prim.m_name.c_str(), nameLen); bx::write(_writer, prim.m_startIndex); bx::write(_writer, prim.m_numIndices); bx::write(_writer, prim.m_startVertex); bx::write(_writer, prim.m_numVertices); writeBounds(_writer, &_vertices[prim.m_startVertex*stride], prim.m_numVertices, stride); } }
void Model::create(const bgfx::VertexDecl& def, Material* material, const int* indices_data, int indices_size, const void* attributes_data, int attributes_size) { m_geometry_buffer_object.setAttributesData( attributes_data, attributes_size, def); m_geometry_buffer_object.setIndicesData(indices_data, indices_size); m_meshes.emplace(def, material, 0, attributes_size, 0, indices_size / sizeof(int), "default", m_allocator); Model::LOD lod; lod.m_distance = FLT_MAX; lod.m_from_mesh = 0; lod.m_to_mesh = 0; m_lods.push(lod); m_indices.resize(indices_size / sizeof(m_indices[0])); memcpy(&m_indices[0], indices_data, indices_size); m_vertices.resize(attributes_size / def.getStride()); computeRuntimeData((const uint8_t*)attributes_data); onReady(); }
void Model::create(const bgfx::VertexDecl& def, Material* material, const int* indices_data, int indices_size, const void* attributes_data, int attributes_size) { ASSERT(!bgfx::isValid(m_vertices_handle)); m_vertices_handle = bgfx::createVertexBuffer(bgfx::copy(attributes_data, attributes_size), def); m_vertices_size = attributes_size; ASSERT(!bgfx::isValid(m_indices_handle)); auto* mem = bgfx::copy(indices_data, indices_size); m_indices_handle = bgfx::createIndexBuffer(mem, BGFX_BUFFER_INDEX32); m_indices_size = indices_size; m_meshes.emplace(def, material, 0, attributes_size, 0, indices_size / int(sizeof(int)), "default", m_allocator); Model::LOD lod; lod.m_distance = FLT_MAX; lod.m_from_mesh = 0; lod.m_to_mesh = 0; m_lods.push(lod); m_indices.resize(indices_size / sizeof(m_indices[0])); copyMemory(&m_indices[0], indices_data, indices_size); m_vertices.resize(attributes_size / def.getStride()); computeRuntimeData((const uint8*)attributes_data); onCreated(State::READY); }
void load(const void* _vertices, uint32_t _numVertices, const bgfx::VertexDecl _decl, const uint16_t* _indices, uint32_t _numIndices) { Group group; const bgfx::Memory* mem; uint32_t size; size = _numVertices*_decl.getStride(); mem = bgfx::makeRef(_vertices, size); group.m_vbh = bgfx::createVertexBuffer(mem, _decl); size = _numIndices*2; mem = bgfx::makeRef(_indices, size); group.m_ibh = bgfx::createIndexBuffer(mem); //TODO: // group.m_sphere = ... // group.m_aabb = ... // group.m_obb = ... // group.m_prims = ... m_groups.push_back(group); }
int _main_(int _argc, char** _argv) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_NONE; bgfx::init(); bgfx::reset(width, height); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (bgfx::getRendererType() ) { default: case bgfx::RendererType::Direct3D9: s_shaderPath = "shaders/dx9/"; break; case bgfx::RendererType::Direct3D11: s_shaderPath = "shaders/dx11/"; break; case bgfx::RendererType::OpenGL: s_shaderPath = "shaders/glsl/"; s_flipV = true; break; case bgfx::RendererType::OpenGLES2: case bgfx::RendererType::OpenGLES3: s_shaderPath = "shaders/gles/"; s_flipV = true; break; } // Create vertex stream declaration. s_PosColorTexCoord0Decl.begin(); s_PosColorTexCoord0Decl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float); s_PosColorTexCoord0Decl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true); s_PosColorTexCoord0Decl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float); s_PosColorTexCoord0Decl.end(); bgfx::UniformHandle u_time = bgfx::createUniform("u_time", bgfx::UniformType::Uniform1f); bgfx::UniformHandle u_mtx = bgfx::createUniform("u_mtx", bgfx::UniformType::Uniform4x4fv); bgfx::UniformHandle u_lightDir = bgfx::createUniform("u_lightDir", bgfx::UniformType::Uniform3fv); bgfx::ProgramHandle raymarching = loadProgram("vs_raymarching", "fs_raymarching"); while (!processEvents(width, height, debug, reset) ) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // Set view 1 default viewport. bgfx::setViewRect(1, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to viewZ 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/03-raymarch"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Updating shader uniforms."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -15.0f }; float view[16]; float proj[16]; mtxLookAt(view, eye, at); mtxProj(proj, 60.0f, 16.0f/9.0f, 0.1f, 100.0f); // Set view and projection matrix for view 1. bgfx::setViewTransform(0, view, proj); float ortho[16]; mtxOrtho(ortho, 0.0f, 1280.0f, 720.0f, 0.0f, 0.0f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(1, NULL, ortho); float time = (float)(bx::getHPCounter()/double(bx::getHPFrequency() ) ); float vp[16]; mtxMul(vp, view, proj); float mtx[16]; mtxRotateXY(mtx , time , time*0.37f ); float mtxInv[16]; mtxInverse(mtxInv, mtx); float lightDirModel[4] = { -0.4f, -0.5f, -1.0f, 0.0f }; float lightDirModelN[4]; vec3Norm(lightDirModelN, lightDirModel); float lightDir[4]; vec4MulMtx(lightDir, lightDirModelN, mtxInv); bgfx::setUniform(u_lightDir, lightDir); float mvp[16]; mtxMul(mvp, mtx, vp); float invMvp[16]; mtxInverse(invMvp, mvp); bgfx::setUniform(u_mtx, invMvp); bgfx::setUniform(u_time, &time); renderScreenSpaceQuad(1, raymarching, 0.0f, 0.0f, 1280.0f, 720.0f); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // Cleanup. bgfx::destroyProgram(raymarching); bgfx::destroyUniform(u_time); bgfx::destroyUniform(u_mtx); bgfx::destroyUniform(u_lightDir); // Shutdown bgfx. bgfx::shutdown(); return 0; }
int _main_(int _argc, char** _argv) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_NONE; bgfx::init(); bgfx::reset(width, height); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (bgfx::getRendererType() ) { default: case bgfx::RendererType::Direct3D9: s_shaderPath = "shaders/dx9/"; break; case bgfx::RendererType::Direct3D11: s_shaderPath = "shaders/dx11/"; break; case bgfx::RendererType::OpenGL: s_shaderPath = "shaders/glsl/"; break; case bgfx::RendererType::OpenGLES2: case bgfx::RendererType::OpenGLES3: s_shaderPath = "shaders/gles/"; break; } // Create vertex stream declaration. s_PosNormalTangentTexcoordDecl.begin(); s_PosNormalTangentTexcoordDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float); s_PosNormalTangentTexcoordDecl.add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true); s_PosNormalTangentTexcoordDecl.add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true); s_PosNormalTangentTexcoordDecl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Int16, true, true); s_PosNormalTangentTexcoordDecl.end(); const bgfx::Memory* mem; calcTangents(s_cubeVertices, countof(s_cubeVertices), s_PosNormalTangentTexcoordDecl, s_cubeIndices, countof(s_cubeIndices) ); // Create static vertex buffer. mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ); bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(mem, s_PosNormalTangentTexcoordDecl); // Create static index buffer. mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ); bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(mem); // Create texture sampler uniforms. bgfx::UniformHandle u_texColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle u_texNormal = bgfx::createUniform("u_texNormal", bgfx::UniformType::Uniform1iv); uint16_t numLights = 4; bgfx::UniformHandle u_lightPosRadius = bgfx::createUniform("u_lightPosRadius", bgfx::UniformType::Uniform4fv, numLights); bgfx::UniformHandle u_lightRgbInnerR = bgfx::createUniform("u_lightRgbInnerR", bgfx::UniformType::Uniform4fv, numLights); // Load vertex shader. mem = loadShader("vs_bump"); bgfx::VertexShaderHandle vsh = bgfx::createVertexShader(mem); // Load fragment shader. mem = loadShader("fs_bump"); bgfx::FragmentShaderHandle fsh = bgfx::createFragmentShader(mem); // Create program from shaders. bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh); // We can destroy vertex and fragment shader here since // their reference is kept inside bgfx after calling createProgram. // Vertex and fragment shader will be destroyed once program is^ // destroyed. bgfx::destroyVertexShader(vsh); bgfx::destroyFragmentShader(fsh); // Load diffuse texture. mem = loadTexture("fieldstone-rgba.dds"); bgfx::TextureHandle textureColor = bgfx::createTexture(mem); // Load normal texture. mem = loadTexture("fieldstone-n.dds"); bgfx::TextureHandle textureNormal = bgfx::createTexture(mem); while (!processEvents(width, height, debug, reset) ) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; float time = (float)(now/freq); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/06-bump"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Loading textures."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -7.0f }; float view[16]; float proj[16]; mtxLookAt(view, eye, at); mtxProj(proj, 60.0f, 16.0f/9.0f, 0.1f, 100.0f); float lightPosRadius[4][4]; for (uint32_t ii = 0; ii < numLights; ++ii) { lightPosRadius[ii][0] = sin( (time*(0.1f + ii*0.17f) + float(ii*M_PI_2)*1.37f ) )*3.0f; lightPosRadius[ii][1] = cos( (time*(0.2f + ii*0.29f) + float(ii*M_PI_2)*1.49f ) )*3.0f; lightPosRadius[ii][2] = -2.5f; lightPosRadius[ii][3] = 3.0f; } bgfx::setUniform(u_lightPosRadius, lightPosRadius, numLights); float lightRgbInnerR[4][4] = { { 1.0f, 0.7f, 0.2f, 0.8f }, { 0.7f, 0.2f, 1.0f, 0.8f }, { 0.2f, 1.0f, 0.7f, 0.8f }, { 1.0f, 0.4f, 0.2f, 0.8f }, }; bgfx::setUniform(u_lightRgbInnerR, lightRgbInnerR, numLights); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); const uint16_t instanceStride = 64; const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(9, instanceStride); if (NULL != idb) { uint8_t* data = idb->data; // Write instance data for 3x3 cubes. for (uint32_t yy = 0; yy < 3; ++yy) { for (uint32_t xx = 0; xx < 3; ++xx) { float* mtx = (float*)data; mtxRotateXY(mtx, time*0.023f + xx*0.21f, time*0.03f + yy*0.37f); mtx[12] = -3.0f + float(xx)*3.0f; mtx[13] = -3.0f + float(yy)*3.0f; mtx[14] = 0.0f; float* color = (float*)&data[64]; color[0] = sin(time+float(xx)/11.0f)*0.5f+0.5f; color[1] = cos(time+float(yy)/11.0f)*0.5f+0.5f; color[2] = sin(time*3.0f)*0.5f+0.5f; color[3] = 1.0f; data += instanceStride; } } uint16_t numInstances = (uint16_t)( (data - idb->data)/instanceStride); // Set vertex and fragment shaders. bgfx::setProgram(program); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh); // Set instance data buffer. bgfx::setInstanceDataBuffer(idb, numInstances); // Bind textures. bgfx::setTexture(0, u_texColor, textureColor); bgfx::setTexture(1, u_texNormal, textureNormal); // Set render states. bgfx::setState(0 |BGFX_STATE_RGB_WRITE |BGFX_STATE_ALPHA_WRITE |BGFX_STATE_DEPTH_WRITE |BGFX_STATE_DEPTH_TEST_LESS |BGFX_STATE_MSAA ); // Submit primitive for rendering to view 0. bgfx::submit(0); } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // Cleanup. bgfx::destroyIndexBuffer(ibh); bgfx::destroyVertexBuffer(vbh); bgfx::destroyProgram(program); bgfx::destroyTexture(textureColor); bgfx::destroyTexture(textureNormal); bgfx::destroyUniform(u_texColor); bgfx::destroyUniform(u_texNormal); bgfx::destroyUniform(u_lightPosRadius); bgfx::destroyUniform(u_lightRgbInnerR); // Shutdown bgfx. bgfx::shutdown(); return 0; }
namespace GFX { lmDefineLogGroup(gGFXQuadRendererLogGroup, "GFXQuadRenderer", 1, LoomLogInfo); // coincides w/ struct VertexPosColorTex in gfxQuadRenderer.h static bgfx::VertexDecl sVertexPosColorTexDecl; static bgfx::UniformHandle sUniformTexColor; static bgfx::UniformHandle sUniformNodeMatrixRemoveMe; static bgfx::ProgramHandle sProgramPosColorTex; static bgfx::ProgramHandle sProgramPosTex; static bgfx::IndexBufferHandle sIndexBufferHandle; static bool sTinted = true; bgfx::DynamicVertexBufferHandle QuadRenderer::vertexBuffers[MAXVERTEXBUFFERS]; VertexPosColorTex* QuadRenderer::vertexData[MAXVERTEXBUFFERS]; void* QuadRenderer::vertexDataMemory = NULL; int QuadRenderer::maxVertexIdx[MAXVERTEXBUFFERS]; int QuadRenderer::numVertexBuffers; int QuadRenderer::currentVertexBufferIdx; VertexPosColorTex *QuadRenderer::currentVertexPtr; int QuadRenderer::vertexCount; int QuadRenderer::currentIndexBufferIdx; TextureID QuadRenderer::currentTexture; int QuadRenderer::quadCount; int QuadRenderer::numFrameSubmit; static loom_allocator_t *gQuadMemoryAllocator = NULL; void QuadRenderer::submit() { if (quadCount <= 0) { return; } numFrameSubmit++; if (Texture::sTextureInfos[currentTexture].handle.idx != MARKEDTEXTURE) { // On iPad 1, the PosColorTex shader, which multiplies texture color with // vertex color, is 5x slower than PosTex, which just draws the texture // unmodified. So we do this. if(sTinted) bgfx::setProgram(sProgramPosColorTex); else bgfx::setProgram(sProgramPosTex); lmAssert(sIndexBufferHandle.idx != bgfx::invalidHandle, "No index buffer!"); bgfx::setIndexBuffer(sIndexBufferHandle, currentIndexBufferIdx, (quadCount * 6)); bgfx::setVertexBuffer(vertexBuffers[currentVertexBufferIdx], MAXBATCHQUADS * 4); // set U and V wrap modes (repeat / mirror / clamp) uint32_t textureFlags = BGFX_TEXTURE_W_CLAMP; ///U switch(Texture::sTextureInfos[currentTexture].wrapU) { case TEXTUREINFO_WRAP_REPEAT: textureFlags |= BGFX_TEXTURE_NONE; break; case TEXTUREINFO_WRAP_MIRROR: textureFlags |= BGFX_TEXTURE_U_MIRROR; break; case TEXTUREINFO_WRAP_CLAMP: textureFlags |= BGFX_TEXTURE_U_CLAMP; break; } ///V switch(Texture::sTextureInfos[currentTexture].wrapV) { case TEXTUREINFO_WRAP_REPEAT: textureFlags |= BGFX_TEXTURE_NONE; break; case TEXTUREINFO_WRAP_MIRROR: textureFlags |= BGFX_TEXTURE_V_MIRROR; break; case TEXTUREINFO_WRAP_CLAMP: textureFlags |= BGFX_TEXTURE_V_CLAMP; break; } // set smoothing mode, bgfx default is bilinear switch (Texture::sTextureInfos[currentTexture].smoothing) { // use nearest neighbor case TEXTUREINFO_SMOOTHING_NONE: textureFlags |= BGFX_TEXTURE_MIN_POINT; textureFlags |= BGFX_TEXTURE_MAG_POINT; textureFlags |= BGFX_TEXTURE_MIP_POINT; break; } bgfx::setTexture(0, sUniformTexColor, Texture::sTextureInfos[currentTexture].handle, textureFlags); // Set render states. bgfx::setState(0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE //|BGFX_STATE_DEPTH_WRITE //|BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_BLEND_FUNC(BGFX_STATE_BLEND_SRC_ALPHA, BGFX_STATE_BLEND_INV_SRC_ALPHA) ); bgfx::submit(Graphics::getView()); currentIndexBufferIdx += quadCount * 6; } quadCount = 0; } VertexPosColorTex *QuadRenderer::getQuadVertices(TextureID texture, uint16_t numVertices, bool tinted) { if (!numVertices || (texture < 0) || (numVertices > MAXBATCHQUADS * 4)) { return NULL; } lmAssert(!(numVertices % 4), "numVertices % 4 != 0"); if (((currentTexture != TEXTUREINVALID) && (currentTexture != texture)) || (sTinted != tinted)) { submit(); } if ((vertexCount + numVertices) > MAXBATCHQUADS * 4) { submit(); if (numVertexBuffers == MAXVERTEXBUFFERS) { return NULL; } currentVertexBufferIdx++; if (currentVertexBufferIdx == numVertexBuffers) { // we need to allocate a new one printf("Allocating new dynamic vertex buffer\n"); vertexBuffers[numVertexBuffers++] = bgfx::createDynamicVertexBuffer(MAXBATCHQUADS * 4, sVertexPosColorTexDecl); } currentIndexBufferIdx = 0; maxVertexIdx[currentVertexBufferIdx] = 0; currentVertexPtr = vertexData[currentVertexBufferIdx]; vertexCount = 0; quadCount = 0; } VertexPosColorTex *returnPtr = currentVertexPtr; sTinted = tinted; currentVertexPtr += numVertices; vertexCount += numVertices; maxVertexIdx[currentVertexBufferIdx] = vertexCount; currentTexture = texture; quadCount += numVertices / 4; return returnPtr; } void QuadRenderer::batch(TextureID texture, VertexPosColorTex *vertices, uint16_t numVertices) { VertexPosColorTex *verticePtr = getQuadVertices(texture, numVertices, true); if (!verticePtr) { return; } memcpy((void *)verticePtr, (void *)vertices, sizeof(VertexPosColorTex) * numVertices); } void QuadRenderer::beginFrame() { currentIndexBufferIdx = 0; currentVertexBufferIdx = 0; vertexCount = 0; currentTexture = TEXTUREINVALID; quadCount = 0; currentVertexPtr = vertexData[currentVertexBufferIdx]; maxVertexIdx[currentIndexBufferIdx] = 0; numFrameSubmit = 0; // remove me float node[16]; mtxIdentity(node); bgfx::setUniform(sUniformNodeMatrixRemoveMe, (const void *)node); bgfx::setProgram(sProgramPosColorTex); } void QuadRenderer::endFrame() { submit(); //printf("numFrameSubmit %i\n", numFrameSubmit); for (int i = 0; i < currentVertexBufferIdx + 1; i++) { // may need to alloc or double buffer if we thread bgfx const bgfx::Memory *mem = bgfx::makeRef(vertexData[i], sizeof(VertexPosColorTex) * maxVertexIdx[i]); bgfx::updateDynamicVertexBuffer(vertexBuffers[i], mem); } } void QuadRenderer::destroyGraphicsResources() { for (int i = 0; i < MAXVERTEXBUFFERS; i++) { if (vertexBuffers[i].idx != bgfx::invalidHandle) { bgfx::destroyDynamicVertexBuffer(vertexBuffers[i]); vertexBuffers[i].idx = bgfx::invalidHandle; } } if (sIndexBufferHandle.idx != bgfx::invalidHandle) { bgfx::destroyIndexBuffer(sIndexBufferHandle); sIndexBufferHandle.idx = bgfx::invalidHandle; } if (sProgramPosColorTex.idx != bgfx::invalidHandle) { bgfx::destroyProgram(sProgramPosColorTex); } if (sUniformTexColor.idx != bgfx::invalidHandle) { bgfx::destroyUniform(sUniformTexColor); } if (sUniformNodeMatrixRemoveMe.idx != bgfx::invalidHandle) { bgfx::destroyUniform(sUniformNodeMatrixRemoveMe); } sUniformTexColor.idx = bgfx::invalidHandle; sUniformNodeMatrixRemoveMe.idx = bgfx::invalidHandle; sProgramPosColorTex.idx = bgfx::invalidHandle; if (vertexDataMemory) { lmFree(gQuadMemoryAllocator, vertexDataMemory); vertexDataMemory = NULL; } } void QuadRenderer::initializeGraphicsResources() { const bgfx::Memory *mem = NULL; lmLogInfo(gGFXQuadRendererLogGroup, "Initializing Graphics Resources"); // Create texture sampler uniforms. sUniformTexColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1iv); sUniformNodeMatrixRemoveMe = bgfx::createUniform("u_nodeMatrix", bgfx::UniformType::Uniform4x4fv); int sz; const uint8_t *pshader; // Load vertex shader. bgfx::VertexShaderHandle vsh_pct; pshader = GetVertexShaderPosColorTex(sz); mem = bgfx::makeRef(pshader, sz); vsh_pct = bgfx::createVertexShader(mem); bgfx::VertexShaderHandle vsh_pt; pshader = GetVertexShaderPosTex(sz); mem = bgfx::makeRef(pshader, sz); vsh_pt = bgfx::createVertexShader(mem); // Load fragment shaders. bgfx::FragmentShaderHandle fsh_pct; pshader = GetFragmentShaderPosColorTex(sz); mem = bgfx::makeRef(pshader, sz); fsh_pct = bgfx::createFragmentShader(mem); bgfx::FragmentShaderHandle fsh_pt; pshader = GetFragmentShaderPosTex(sz); mem = bgfx::makeRef(pshader, sz); fsh_pt = bgfx::createFragmentShader(mem); // Create program from shaders. sProgramPosColorTex = bgfx::createProgram(vsh_pct, fsh_pct); sProgramPosTex = bgfx::createProgram(vsh_pt, fsh_pt); // We can destroy vertex and fragment shader here since // their reference is kept inside bgfx after calling createProgram. // Vertex and fragment shader will be destroyed once program is // destroyed. bgfx::destroyVertexShader(vsh_pct); bgfx::destroyVertexShader(vsh_pt); bgfx::destroyFragmentShader(fsh_pct); bgfx::destroyFragmentShader(fsh_pt); // create the vertex stream sVertexPosColorTexDecl.begin(); sVertexPosColorTexDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float); sVertexPosColorTexDecl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true); sVertexPosColorTexDecl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float); sVertexPosColorTexDecl.end(); // create the single, reused quad index buffer numVertexBuffers = 0; vertexBuffers[numVertexBuffers++] = bgfx::createDynamicVertexBuffer(MAXBATCHQUADS * 4, sVertexPosColorTexDecl); mem = bgfx::alloc(sizeof(uint16_t) * 6 * MAXBATCHQUADS); uint16_t *pindice = (uint16_t *)mem->data; int j = 0; for (int i = 0; i < 6 * MAXBATCHQUADS; i += 6, j += 4, pindice += 6) { pindice[0] = j; pindice[1] = j + 2; pindice[2] = j + 1; pindice[3] = j + 1; pindice[4] = j + 2; pindice[5] = j + 3; } sIndexBufferHandle = bgfx::createIndexBuffer(mem); size_t bufferSize = MAXVERTEXBUFFERS * sizeof(VertexPosColorTex) * MAXBATCHQUADS * 4; vertexDataMemory = lmAlloc(gQuadMemoryAllocator, bufferSize); lmAssert(vertexDataMemory, "Unable to allocate buffer for quad vertex data"); VertexPosColorTex* p = (VertexPosColorTex*) vertexDataMemory; for (int i = 0; i < MAXVERTEXBUFFERS; i++) { // setup buffer pointer vertexData[i] = p; p += MAXBATCHQUADS * 4; } } void QuadRenderer::reset() { destroyGraphicsResources(); bgfx::frame(); initializeGraphicsResources(); } void QuadRenderer::initialize() { sUniformNodeMatrixRemoveMe.idx = bgfx::invalidHandle; sUniformTexColor.idx = bgfx::invalidHandle; sProgramPosColorTex.idx = bgfx::invalidHandle; sIndexBufferHandle.idx = bgfx::invalidHandle; for (int i = 0; i < MAXVERTEXBUFFERS; i++) { vertexBuffers[i].idx = bgfx::invalidHandle; } } }
void QuadRenderer::initializeGraphicsResources() { const bgfx::Memory *mem = NULL; lmLogInfo(gGFXQuadRendererLogGroup, "Initializing Graphics Resources"); // Create texture sampler uniforms. sUniformTexColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1iv); sUniformNodeMatrixRemoveMe = bgfx::createUniform("u_nodeMatrix", bgfx::UniformType::Uniform4x4fv); int sz; const uint8_t *pshader; // Load vertex shader. bgfx::VertexShaderHandle vsh_pct; pshader = GetVertexShaderPosColorTex(sz); mem = bgfx::makeRef(pshader, sz); vsh_pct = bgfx::createVertexShader(mem); bgfx::VertexShaderHandle vsh_pt; pshader = GetVertexShaderPosTex(sz); mem = bgfx::makeRef(pshader, sz); vsh_pt = bgfx::createVertexShader(mem); // Load fragment shaders. bgfx::FragmentShaderHandle fsh_pct; pshader = GetFragmentShaderPosColorTex(sz); mem = bgfx::makeRef(pshader, sz); fsh_pct = bgfx::createFragmentShader(mem); bgfx::FragmentShaderHandle fsh_pt; pshader = GetFragmentShaderPosTex(sz); mem = bgfx::makeRef(pshader, sz); fsh_pt = bgfx::createFragmentShader(mem); // Create program from shaders. sProgramPosColorTex = bgfx::createProgram(vsh_pct, fsh_pct); sProgramPosTex = bgfx::createProgram(vsh_pt, fsh_pt); // We can destroy vertex and fragment shader here since // their reference is kept inside bgfx after calling createProgram. // Vertex and fragment shader will be destroyed once program is // destroyed. bgfx::destroyVertexShader(vsh_pct); bgfx::destroyVertexShader(vsh_pt); bgfx::destroyFragmentShader(fsh_pct); bgfx::destroyFragmentShader(fsh_pt); // create the vertex stream sVertexPosColorTexDecl.begin(); sVertexPosColorTexDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float); sVertexPosColorTexDecl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true); sVertexPosColorTexDecl.add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float); sVertexPosColorTexDecl.end(); // create the single, reused quad index buffer numVertexBuffers = 0; vertexBuffers[numVertexBuffers++] = bgfx::createDynamicVertexBuffer(MAXBATCHQUADS * 4, sVertexPosColorTexDecl); mem = bgfx::alloc(sizeof(uint16_t) * 6 * MAXBATCHQUADS); uint16_t *pindice = (uint16_t *)mem->data; int j = 0; for (int i = 0; i < 6 * MAXBATCHQUADS; i += 6, j += 4, pindice += 6) { pindice[0] = j; pindice[1] = j + 2; pindice[2] = j + 1; pindice[3] = j + 1; pindice[4] = j + 2; pindice[5] = j + 3; } sIndexBufferHandle = bgfx::createIndexBuffer(mem); size_t bufferSize = MAXVERTEXBUFFERS * sizeof(VertexPosColorTex) * MAXBATCHQUADS * 4; vertexDataMemory = lmAlloc(gQuadMemoryAllocator, bufferSize); lmAssert(vertexDataMemory, "Unable to allocate buffer for quad vertex data"); VertexPosColorTex* p = (VertexPosColorTex*) vertexDataMemory; for (int i = 0; i < MAXVERTEXBUFFERS; i++) { // setup buffer pointer vertexData[i] = p; p += MAXBATCHQUADS * 4; } }
int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (bgfx::getRendererType() ) { default: case bgfx::RendererType::Direct3D9: s_shaderPath = "shaders/dx9/"; break; case bgfx::RendererType::Direct3D11: s_shaderPath = "shaders/dx11/"; break; case bgfx::RendererType::OpenGL: s_shaderPath = "shaders/glsl/"; break; case bgfx::RendererType::OpenGLES2: case bgfx::RendererType::OpenGLES3: s_shaderPath = "shaders/gles/"; break; } // Create vertex stream declaration. s_PosTexcoordDecl.begin(); s_PosTexcoordDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float); s_PosTexcoordDecl.add(bgfx::Attrib::TexCoord0, 3, bgfx::AttribType::Float); s_PosTexcoordDecl.end(); const bgfx::Memory* mem; // Create static vertex buffer. mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ); bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(mem, s_PosTexcoordDecl); // Create static index buffer. mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ); bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(mem); // Create texture sampler uniforms. bgfx::UniformHandle u_texCube = bgfx::createUniform("u_texCube", bgfx::UniformType::Uniform1iv); // Load vertex shader. mem = loadShader("vs_update"); bgfx::VertexShaderHandle vsh = bgfx::createVertexShader(mem); // Load fragment shader. mem = loadShader("fs_update"); bgfx::FragmentShaderHandle fsh = bgfx::createFragmentShader(mem); // Create program from shaders. bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh); // We can destroy vertex and fragment shader here since // their reference is kept inside bgfx after calling createProgram. // Vertex and fragment shader will be destroyed once program is // destroyed. bgfx::destroyVertexShader(vsh); bgfx::destroyFragmentShader(fsh); const uint32_t textureSide = 2048; bgfx::TextureHandle textureCube = bgfx::createTextureCube(6 , textureSide , 1 , bgfx::TextureFormat::BGRA8 , BGFX_TEXTURE_MIN_POINT|BGFX_TEXTURE_MAG_POINT|BGFX_TEXTURE_MIP_POINT ); uint8_t rr = rand()%255; uint8_t gg = rand()%255; uint8_t bb = rand()%255; int64_t updateTime = 0; RectPackCubeT<256> cube(textureSide); uint32_t hit = 0; uint32_t miss = 0; std::list<PackCube> quads; int64_t timeOffset = bx::getHPCounter(); while (!processEvents(width, height, debug, reset) ) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const int64_t freq = bx::getHPFrequency(); const double toMs = 1000.0/double(freq); float time = (float)( (now - timeOffset)/double(bx::getHPFrequency() ) ); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/08-update"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Updating textures."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); if (now > updateTime) { PackCube face; uint32_t bw = bx::uint16_max(1, rand()%(textureSide/4) ); uint32_t bh = bx::uint16_max(1, rand()%(textureSide/4) ); if (cube.find(bw, bh, face) ) { quads.push_back(face); ++hit; bgfx::TextureInfo ti; const Pack2D& rect = face.m_rect; bgfx::calcTextureSize(ti, rect.m_width, rect.m_height, 1, 1, bgfx::TextureFormat::BGRA8); // updateTime = now + freq/10; const bgfx::Memory* mem = bgfx::alloc(ti.storageSize); uint8_t* data = (uint8_t*)mem->data; for (uint32_t ii = 0, num = ti.storageSize*8/ti.bitsPerPixel; ii < num; ++ii) { data[0] = bb; data[1] = rr; data[2] = gg; data[3] = 0xff; data += 4; } bgfx::updateTextureCube(textureCube, face.m_side, 0, rect.m_x, rect.m_y, rect.m_width, rect.m_height, mem); rr = rand()%255; gg = rand()%255; bb = rand()%255; } else { ++miss; for (uint32_t ii = 0, num = bx::uint32_min(10, (uint32_t)quads.size() ); ii < num; ++ii) { const PackCube& face = quads.front(); cube.clear(face); quads.pop_front(); } } } bgfx::dbgTextPrintf(0, 4, 0x0f, "hit: %d, miss %d", hit, miss); float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -5.0f }; float view[16]; float proj[16]; mtxLookAt(view, eye, at); mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); float mtx[16]; mtxRotateXY(mtx, time, time*0.37f); // Set model matrix for rendering. bgfx::setTransform(mtx); // Set vertex and fragment shaders. bgfx::setProgram(program); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh); // Bind texture. bgfx::setTexture(0, u_texCube, textureCube); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // Cleanup. bgfx::destroyIndexBuffer(ibh); bgfx::destroyVertexBuffer(vbh); bgfx::destroyProgram(program); bgfx::destroyTexture(textureCube); bgfx::destroyUniform(u_texCube); // Shutdown bgfx. bgfx::shutdown(); return 0; }
int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (bgfx::getRendererType() ) { default: case bgfx::RendererType::Direct3D9: s_shaderPath = "shaders/dx9/"; break; case bgfx::RendererType::Direct3D11: s_shaderPath = "shaders/dx11/"; break; case bgfx::RendererType::OpenGL: s_shaderPath = "shaders/glsl/"; break; case bgfx::RendererType::OpenGLES2: case bgfx::RendererType::OpenGLES3: s_shaderPath = "shaders/gles/"; break; } // Create vertex stream declaration. s_PosColorDecl.begin(); s_PosColorDecl.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float); s_PosColorDecl.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true); s_PosColorDecl.end(); const bgfx::Memory* mem; // Create static vertex buffer. mem = bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ); bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(mem, s_PosColorDecl); // Create static index buffer. mem = bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ); bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(mem); // Load vertex shader. mem = loadShader("vs_instancing"); bgfx::VertexShaderHandle vsh = bgfx::createVertexShader(mem); // Load fragment shader. mem = loadShader("fs_instancing"); bgfx::FragmentShaderHandle fsh = bgfx::createFragmentShader(mem); // Create program from shaders. bgfx::ProgramHandle program = bgfx::createProgram(vsh, fsh); // We can destroy vertex and fragment shader here since // their reference is kept inside bgfx after calling createProgram. // Vertex and fragment shader will be destroyed once program is // destroyed. bgfx::destroyVertexShader(vsh); bgfx::destroyFragmentShader(fsh); int64_t timeOffset = bx::getHPCounter(); while (!entry::processEvents(width, height, debug, reset) ) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; float time = (float)( (now - timeOffset)/double(bx::getHPFrequency() ) ); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/05-instancing"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Geometry instancing."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -35.0f }; float view[16]; float proj[16]; mtxLookAt(view, eye, at); mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); const uint16_t instanceStride = 80; const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(121, instanceStride); if (NULL != idb) { uint8_t* data = idb->data; // Write instance data for 11x11 cubes. for (uint32_t yy = 0; yy < 11; ++yy) { for (uint32_t xx = 0; xx < 11; ++xx) { float* mtx = (float*)data; mtxRotateXY(mtx, time + xx*0.21f, time + yy*0.37f); mtx[12] = -15.0f + float(xx)*3.0f; mtx[13] = -15.0f + float(yy)*3.0f; mtx[14] = 0.0f; float* color = (float*)&data[64]; color[0] = sin(time+float(xx)/11.0f)*0.5f+0.5f; color[1] = cos(time+float(yy)/11.0f)*0.5f+0.5f; color[2] = sin(time*3.0f)*0.5f+0.5f; color[3] = 1.0f; data += instanceStride; } } // Set vertex and fragment shaders. bgfx::setProgram(program); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh); // Set instance data buffer. bgfx::setInstanceDataBuffer(idb); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0); } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // Cleanup. bgfx::destroyIndexBuffer(ibh); bgfx::destroyVertexBuffer(vbh); bgfx::destroyProgram(program); // Shutdown bgfx. bgfx::shutdown(); return 0; }
bool Model::parseMeshesOld(bgfx::VertexDecl global_vertex_decl, FS::IFile& file, FileVersion version, u32 global_flags) { int object_count = 0; file.read(&object_count, sizeof(object_count)); if (object_count <= 0) return false; m_meshes.reserve(object_count); char model_dir[MAX_PATH_LENGTH]; PathUtils::getDir(model_dir, MAX_PATH_LENGTH, getPath().c_str()); struct Offsets { i32 attribute_array_offset; i32 attribute_array_size; i32 indices_offset; i32 mesh_tri_count; }; Array<Offsets> mesh_offsets(m_allocator); for (int i = 0; i < object_count; ++i) { i32 str_size; file.read(&str_size, sizeof(str_size)); char material_name[MAX_PATH_LENGTH]; file.read(material_name, str_size); if (str_size >= MAX_PATH_LENGTH) return false; material_name[str_size] = 0; char material_path[MAX_PATH_LENGTH]; copyString(material_path, model_dir); catString(material_path, material_name); catString(material_path, ".mat"); auto* material_manager = m_resource_manager.getOwner().get(Material::TYPE); Material* material = static_cast<Material*>(material_manager->load(Path(material_path))); Offsets& offsets = mesh_offsets.emplace(); file.read(&offsets.attribute_array_offset, sizeof(offsets.attribute_array_offset)); file.read(&offsets.attribute_array_size, sizeof(offsets.attribute_array_size)); file.read(&offsets.indices_offset, sizeof(offsets.indices_offset)); file.read(&offsets.mesh_tri_count, sizeof(offsets.mesh_tri_count)); file.read(&str_size, sizeof(str_size)); if (str_size >= MAX_PATH_LENGTH) { material_manager->unload(*material); return false; } char mesh_name[MAX_PATH_LENGTH]; mesh_name[str_size] = 0; file.read(mesh_name, str_size); bgfx::VertexDecl vertex_decl = global_vertex_decl; if (version <= FileVersion::SINGLE_VERTEX_DECL) { parseVertexDecl(file, &vertex_decl); if (i != 0 && global_vertex_decl.m_hash != vertex_decl.m_hash) { g_log_error.log("Renderer") << "Model " << getPath().c_str() << " contains meshes with different vertex declarations."; } if(i == 0) global_vertex_decl = vertex_decl; } m_meshes.emplace(material, vertex_decl, mesh_name, m_allocator); addDependency(*material); } i32 indices_count = 0; file.read(&indices_count, sizeof(indices_count)); if (indices_count <= 0) return false; u32 INDICES_16BIT_FLAG = 1; int index_size = global_flags & INDICES_16BIT_FLAG ? 2 : 4; Array<u8> indices(m_allocator); indices.resize(indices_count * index_size); file.read(&indices[0], indices.size()); i32 vertices_size = 0; file.read(&vertices_size, sizeof(vertices_size)); if (vertices_size <= 0) return false; Array<u8> vertices(m_allocator); vertices.resize(vertices_size); file.read(&vertices[0], vertices.size()); int vertex_count = 0; for (const Offsets& offsets : mesh_offsets) { vertex_count += offsets.attribute_array_size / global_vertex_decl.getStride(); } if (version > FileVersion::BOUNDING_SHAPES_PRECOMPUTED) { file.read(&m_bounding_radius, sizeof(m_bounding_radius)); file.read(&m_aabb, sizeof(m_aabb)); } float bounding_radius_squared = 0; Vec3 min_vertex(0, 0, 0); Vec3 max_vertex(0, 0, 0); int vertex_size = global_vertex_decl.getStride(); int position_attribute_offset = global_vertex_decl.getOffset(bgfx::Attrib::Position); int uv_attribute_offset = global_vertex_decl.getOffset(bgfx::Attrib::TexCoord0); int weights_attribute_offset = global_vertex_decl.getOffset(bgfx::Attrib::Weight); int bone_indices_attribute_offset = global_vertex_decl.getOffset(bgfx::Attrib::Indices); bool keep_skin = global_vertex_decl.has(bgfx::Attrib::Weight) && global_vertex_decl.has(bgfx::Attrib::Indices); for (int i = 0; i < m_meshes.size(); ++i) { Offsets& offsets = mesh_offsets[i]; Mesh& mesh = m_meshes[i]; mesh.indices_count = offsets.mesh_tri_count * 3; mesh.indices.resize(mesh.indices_count * index_size); copyMemory(&mesh.indices[0], &indices[offsets.indices_offset * index_size], mesh.indices_count * index_size); int mesh_vertex_count = offsets.attribute_array_size / global_vertex_decl.getStride(); int mesh_attributes_array_offset = offsets.attribute_array_offset; mesh.vertices.resize(mesh_vertex_count); mesh.uvs.resize(mesh_vertex_count); if (keep_skin) mesh.skin.resize(mesh_vertex_count); for (int j = 0; j < mesh_vertex_count; ++j) { int offset = mesh_attributes_array_offset + j * vertex_size; if (keep_skin) { mesh.skin[j].weights = *(const Vec4*)&vertices[offset + weights_attribute_offset]; copyMemory(mesh.skin[j].indices, &vertices[offset + bone_indices_attribute_offset], sizeof(mesh.skin[j].indices)); } mesh.vertices[j] = *(const Vec3*)&vertices[offset + position_attribute_offset]; mesh.uvs[j] = *(const Vec2*)&vertices[offset + uv_attribute_offset]; float sq_len = mesh.vertices[j].squaredLength(); bounding_radius_squared = Math::maximum(bounding_radius_squared, sq_len > 0 ? sq_len : 0); min_vertex.x = Math::minimum(min_vertex.x, mesh.vertices[j].x); min_vertex.y = Math::minimum(min_vertex.y, mesh.vertices[j].y); min_vertex.z = Math::minimum(min_vertex.z, mesh.vertices[j].z); max_vertex.x = Math::maximum(max_vertex.x, mesh.vertices[j].x); max_vertex.y = Math::maximum(max_vertex.y, mesh.vertices[j].y); max_vertex.z = Math::maximum(max_vertex.z, mesh.vertices[j].z); } } if (version <= FileVersion::BOUNDING_SHAPES_PRECOMPUTED) { m_bounding_radius = sqrt(bounding_radius_squared); m_aabb = AABB(min_vertex, max_vertex); } for (int i = 0; i < m_meshes.size(); ++i) { Mesh& mesh = m_meshes[i]; Offsets offsets = mesh_offsets[i]; ASSERT(!bgfx::isValid(mesh.index_buffer_handle)); if (global_flags & INDICES_16BIT_FLAG) { mesh.flags.set(Mesh::Flags::INDICES_16_BIT); } int indices_size = index_size * mesh.indices_count; const bgfx::Memory* mem = bgfx::copy(&indices[offsets.indices_offset * index_size], indices_size); mesh.index_buffer_handle = bgfx::createIndexBuffer(mem, index_size == 4 ? BGFX_BUFFER_INDEX32 : 0); if (!bgfx::isValid(mesh.index_buffer_handle)) return false; ASSERT(!bgfx::isValid(mesh.vertex_buffer_handle)); const bgfx::Memory* vertices_mem = bgfx::copy(&vertices[offsets.attribute_array_offset], offsets.attribute_array_size); mesh.vertex_buffer_handle = bgfx::createVertexBuffer(vertices_mem, mesh.vertex_decl); if (!bgfx::isValid(mesh.vertex_buffer_handle)) return false; } return true; }