diff --git a/core/3d/CCBundle3D.cpp b/core/3d/CCBundle3D.cpp index 7133e05b99..c66d8bcdc5 100644 --- a/core/3d/CCBundle3D.cpp +++ b/core/3d/CCBundle3D.cpp @@ -298,7 +298,7 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, } // split into submesh according to material - std::map> subMeshMap; + std::map subMeshMap; for (size_t k = 0, size = mesh.material_ids.size(); k < size; ++k) { int id = mesh.material_ids[k]; @@ -312,9 +312,9 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, node->id = shape.name; for (auto& submesh : subMeshMap) { - meshdata->subMeshIndices.push_back(submesh.second); + auto& storedIndices = meshdata->subMeshIndices.emplace_back(std::move(submesh.second)); meshdata->subMeshAABB.push_back( - calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), submesh.second)); + calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), storedIndices)); sprintf(str, "%d", ++i); meshdata->subMeshIds.push_back(str); @@ -447,7 +447,7 @@ bool Bundle3D::loadMeshDatasBinary(MeshDatas& meshdatas) for (unsigned int k = 0; k < meshPartCount; ++k) { - std::vector indexArray; + IndexArray indexArray{}; std::string meshPartid = _binaryReader.readString(); meshData->subMeshIds.push_back(meshPartid); unsigned int nIndexCount; @@ -457,12 +457,12 @@ bool Bundle3D::loadMeshDatasBinary(MeshDatas& meshdatas) goto FAILED; } indexArray.resize(nIndexCount); - if (_binaryReader.read(&indexArray[0], 2, nIndexCount) != nIndexCount) + if (_binaryReader.read(indexArray.data(), 2, nIndexCount) != nIndexCount) { CCLOG("warning: Failed to read meshdata: indices '%s'.", _path.c_str()); goto FAILED; } - meshData->subMeshIndices.push_back(indexArray); + auto& storedIndices = meshData->subMeshIndices.emplace_back(std::move(indexArray)); meshData->numIndex = (int)meshData->subMeshIndices.size(); // meshData->subMeshAABB.push_back(calculateAABB(meshData->vertex, meshData->getPerVertexSize(), // indexArray)); @@ -474,13 +474,13 @@ bool Bundle3D::loadMeshDatasBinary(MeshDatas& meshdatas) { CCLOG("warning: Failed to read meshdata: aabb '%s'.", _path.c_str()); goto FAILED; - } + } meshData->subMeshAABB.push_back(AABB(Vec3(aabb[0], aabb[1], aabb[2]), Vec3(aabb[3], aabb[4], aabb[5]))); } else { meshData->subMeshAABB.push_back( - calculateAABB(meshData->vertex, meshData->getPerVertexSize(), indexArray)); + calculateAABB(meshData->vertex, meshData->getPerVertexSize(), storedIndices)); } } meshdatas.meshDatas.push_back(meshData); @@ -599,17 +599,17 @@ bool Bundle3D::loadMeshDatasBinary_0_1(MeshDatas& meshdatas) return false; } - std::vector indices; + IndexArray indices{}; indices.resize(nIndexCount); - if (_binaryReader.read(&indices[0], 2, nIndexCount) != nIndexCount) + if (_binaryReader.read(indices.data(), 2, nIndexCount) != nIndexCount) { CCLOG("warning: Failed to read meshdata: indices '%s'.", _path.c_str()); CC_SAFE_DELETE(meshdata); return false; } - meshdata->subMeshIndices.push_back(indices); - meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), indices)); + auto& storedIndices = meshdata->subMeshIndices.emplace_back(std::move(indices)); + meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), storedIndices)); } meshdatas.meshDatas.push_back(meshdata); @@ -720,17 +720,17 @@ bool Bundle3D::loadMeshDatasBinary_0_2(MeshDatas& meshdatas) return false; } - std::vector indices; + IndexArray indices{}; /* TODO: _version == 1.3 use U_INT?*/ indices.resize(nIndexCount); - if (_binaryReader.read(&indices[0], 2, nIndexCount) != nIndexCount) + if (_binaryReader.read(indices.data(), 2, nIndexCount) != nIndexCount) { CCLOG("warning: Failed to read meshdata: indices '%s'.", _path.c_str()); CC_SAFE_DELETE(meshdata); return false; } - meshdata->subMeshIndices.push_back(indices); - meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), indices)); + auto& storedIndices = meshdata->subMeshIndices.emplace_back(std::move(indices)); + meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), storedIndices)); } meshdatas.meshDatas.push_back(meshdata); @@ -777,7 +777,7 @@ bool Bundle3D::loadMeshDatasJson(MeshDatas& meshdatas) const rapidjson::Value& mesh_part_array = mesh_data[PARTS]; for (rapidjson::SizeType i = 0, mesh_part_array_size = mesh_part_array.Size(); i < mesh_part_array_size; ++i) { - std::vector indexArray; + IndexArray indexArray{}; const rapidjson::Value& mesh_part = mesh_part_array[i]; meshData->subMeshIds.push_back(mesh_part[ID].GetString()); // index_number @@ -786,7 +786,7 @@ bool Bundle3D::loadMeshDatasJson(MeshDatas& meshdatas) j < indices_val_array_size; ++j) indexArray.push_back((unsigned short)indices_val_array[j].GetUint()); - meshData->subMeshIndices.push_back(indexArray); + auto& storedIndices = meshData->subMeshIndices.emplace_back(std::move(indexArray)); meshData->numIndex = (int)meshData->subMeshIndices.size(); if (mesh_data.HasMember(AABBS)) @@ -805,13 +805,12 @@ bool Bundle3D::loadMeshDatasJson(MeshDatas& meshdatas) else { meshData->subMeshAABB.push_back( - calculateAABB(meshData->vertex, meshData->getPerVertexSize(), indexArray)); + calculateAABB(meshData->vertex, meshData->getPerVertexSize(), storedIndices)); } } else { - meshData->subMeshAABB.push_back( - calculateAABB(meshData->vertex, meshData->getPerVertexSize(), indexArray)); + meshData->subMeshAABB.push_back(calculateAABB(meshData->vertex, meshData->getPerVertexSize(), storedIndices)); } } meshdatas.meshDatas.push_back(meshData); @@ -1185,15 +1184,15 @@ bool Bundle3D::loadMeshDataJson_0_1(MeshDatas& meshdatas) unsigned int indexnum = mesh_data_body_array_0[INDEXNUM].GetUint(); // indices - std::vector indices; + IndexArray indices{}; indices.resize(indexnum); const rapidjson::Value& indices_val_array = mesh_data_body_array_0[INDICES]; for (rapidjson::SizeType i = 0; i < indices_val_array.Size(); ++i) - indices[i] = (unsigned short)indices_val_array[i].GetUint(); + indices.at(i) = (unsigned short)indices_val_array[i].GetUint(); - meshdata->subMeshIndices.push_back(indices); - meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), indices)); + auto& storedIndices = meshdata->subMeshIndices.emplace_back(std::move(indices)); + meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), storedIndices)); meshdatas.meshDatas.push_back(meshdata); return true; } @@ -1239,15 +1238,15 @@ bool Bundle3D::loadMeshDataJson_0_2(MeshDatas& meshdatas) unsigned int indexnum = mesh_submesh_val[INDEXNUM].GetUint(); // indices - std::vector indices; + IndexArray indices{}; indices.resize(indexnum); const rapidjson::Value& indices_val_array = mesh_submesh_val[INDICES]; for (rapidjson::SizeType j = 0; j < indices_val_array.Size(); ++j) - indices[j] = (unsigned short)indices_val_array[j].GetUint(); + indices.at(j) = (unsigned short)indices_val_array[j].GetUint(); - meshdata->subMeshIndices.push_back(indices); - meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), indices)); + auto& storedIndices = meshdata->subMeshIndices.emplace_back(std::move(indices)); + meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), storedIndices)); } meshdatas.meshDatas.push_back(meshdata); return true; @@ -2301,13 +2300,12 @@ std::vector Bundle3D::getTrianglesList(std::string_view path) for (auto iter : meshs.meshDatas) { int preVertexSize = iter->getPerVertexSize() / sizeof(float); - for (const auto& indexArray : iter->subMeshIndices) + for (const auto& indices : iter->subMeshIndices) { - for (auto i : indexArray) - { - trianglesList.push_back(Vec3(iter->vertex[i * preVertexSize], iter->vertex[i * preVertexSize + 1], - iter->vertex[i * preVertexSize + 2])); - } + indices.for_each([&](unsigned int ind) { + trianglesList.push_back(Vec3(iter->vertex[ind * preVertexSize], iter->vertex[ind * preVertexSize + 1], + iter->vertex[ind * preVertexSize + 2])); + }); } } @@ -2324,15 +2322,16 @@ Bundle3D::~Bundle3D() cocos2d::AABB Bundle3D::calculateAABB(const std::vector& vertex, int stride, - const std::vector& index) + const IndexArray& indices) { AABB aabb; stride /= 4; - for (const auto& it : index) - { - Vec3 point(vertex[it * stride], vertex[it * stride + 1], vertex[it * stride + 2]); - aabb.updateMinMax(&point, 1); - } + + indices.for_each ([&](uint32_t i) { + Vec3 point(vertex[i * stride], vertex[i * stride + 1], vertex[i * stride + 2]); + aabb.updateMinMax(&point, 1); + }); + return aabb; } diff --git a/core/3d/CCBundle3D.h b/core/3d/CCBundle3D.h index 23f7a34589..a2f1fa3cb1 100644 --- a/core/3d/CCBundle3D.h +++ b/core/3d/CCBundle3D.h @@ -113,7 +113,8 @@ public: const char* mtl_basepath = nullptr); // calculate aabb - static AABB calculateAABB(const std::vector& vertex, int stride, const std::vector& index); + static AABB calculateAABB(const std::vector& vertex, + int stride, const IndexArray& indices); Bundle3D(); virtual ~Bundle3D(); diff --git a/core/3d/CCBundle3DData.h b/core/3d/CCBundle3DData.h index 8bbf5cc784..494d8929c2 100644 --- a/core/3d/CCBundle3DData.h +++ b/core/3d/CCBundle3DData.h @@ -39,8 +39,135 @@ #include "3d/CC3DProgramInfo.h" +#include "yasio/detail/byte_buffer.hpp" + NS_CC_BEGIN +using uint16_index_format = std::integral_constant; +using uint32_index_format = std::integral_constant; + +class IndexArray +{ +public: + static constexpr unsigned int formatToStride(backend::IndexFormat format) { return 1 << (int)format; } + static constexpr backend::IndexFormat strideToFormat(unsigned int stride) + { + return (backend::IndexFormat)(stride >> 1); + } + + IndexArray() : _stride(formatToStride(backend::IndexFormat::U_SHORT)) {} + IndexArray(backend::IndexFormat indexFormat) : _stride(formatToStride(indexFormat)) {} + + IndexArray(std::initializer_list rhs, uint16_index_format /*U_SHORT*/) + : _stride(formatToStride(backend::IndexFormat::U_SHORT)), _buffer(rhs) + {} + IndexArray(std::initializer_list rhs, uint32_index_format /*U_INT*/) + : _stride(formatToStride(backend::IndexFormat::U_INT)), _buffer(rhs) + {} + + IndexArray(const IndexArray& rhs) : _stride(rhs._stride), _buffer(rhs._buffer) {} + IndexArray(IndexArray&& rhs) noexcept : _stride(rhs._stride), _buffer(std::move(rhs._buffer)) {} + + IndexArray& operator=(const IndexArray& rhs) + { + _stride = rhs._stride; + _buffer = rhs._buffer; + return *this; + } + IndexArray& operator=(IndexArray&& rhs) noexcept + { + this->swap(rhs); + return *this; + } + + void swap(IndexArray& rhs) + { + std::swap(_stride, rhs._stride); + _buffer.swap(rhs._buffer); + } + + /** Clears the internal byte buffer. */ + void clear() { _buffer.clear(); } + + /** Pushes back a value. */ + void push_back(uint32_t val) + { + assert(_stride == 2 || _stride == 4); + _buffer.append_n((uint8_t*)&val, _stride); + } + + /** Inserts a list containing unsigned short (uint16_t) data. */ + void insert(size_t offset, std::initializer_list ilist, uint16_index_format /*U_SHORT*/) + { + assert(_stride == 2); + binsert(offset * _stride, ilist.begin(), ilist.end()); + } + + /** Inserts a list containing unsigned int (uint32_t) data. */ + void insert(size_t offset, std::initializer_list ilist, uint32_index_format /*U_INT*/) + { + assert(_stride == 4); + binsert(offset * _stride, ilist.begin(), ilist.end()); + } + + /** Inserts range data based on an offset in bytes. */ + void binsert(size_t offset, const void* first, const void* last) + { + _buffer.insert(offset, (const uint8_t*)first, (const uint8_t*)last); + } + + template + _Ty& at(size_t idx) + { + assert(sizeof(_Ty) == _stride); + if (idx < this->size()) + return (_Ty&)_buffer[idx * sizeof(_Ty)]; + throw std::out_of_range("IndexArray: out of range!"); + } + + uint8_t* data() noexcept { return _buffer.data(); } + const uint8_t* data() const noexcept { return _buffer.data(); } + + /** Returns the count of indices in the container. */ + size_t size() const { return _buffer.size() / _stride; } + /** Returns the size of the container in bytes. */ + size_t bsize() const { return _buffer.size(); } + + /** Resizes the count of indices in the container. */ + void resize(size_t size) { _buffer.resize(size * _stride); } + /** Resizes the container in bytes. */ + void bresize(size_t size) { _buffer.resize(size); } + + /** Returns true if the container is empty. Otherwise, false. */ + bool empty() const { return _buffer.empty(); } + + /** Returns the format of the index array. */ + backend::IndexFormat format() const { return strideToFormat(_stride); } + + /** Clears the internal byte buffer and sets the format specified. */ + void clear(backend::IndexFormat format) + { + clear(); + _stride = formatToStride(format); + } + + template + void for_each(_Fty cb) const + { + assert(_stride == 2 || _stride == 4); + for (auto it = _buffer.begin(); it != _buffer.end(); it += _stride) + { + uint32_t val = 0; + memcpy(&val, it, _stride); + cb(val); + } + } + +protected: + unsigned char _stride; + yasio::byte_buffer _buffer; +}; + /**mesh vertex attribute * @js NA * @lua NA @@ -128,13 +255,14 @@ struct NodeDatas } }; + /**mesh data * @js NA * @lua NA */ struct MeshData { - typedef std::vector IndexArray; + using IndexArray = ::cocos2d::IndexArray; std::vector vertex; int vertexSizeInFloat; std::vector subMeshIndices; @@ -147,7 +275,7 @@ struct MeshData public: /** * Get per vertex size - * @return return the sum of each vertex's all attribute size. + * @return return the sum size of all vertex attributes. */ int getPerVertexSize() const { diff --git a/core/3d/CCMesh.cpp b/core/3d/CCMesh.cpp index e09d260f6b..2484ebce6a 100644 --- a/core/3d/CCMesh.cpp +++ b/core/3d/CCMesh.cpp @@ -113,6 +113,7 @@ Mesh::Mesh() , _visible(true) , _isTransparent(false) , _force2DQueue(false) + , meshIndexFormat(CustomCommand::IndexFormat::U_SHORT) , _meshIndexData(nullptr) , _blend(BlendFunc::ALPHA_NON_PREMULTIPLIED) , _blendDirty(true) @@ -222,10 +223,13 @@ Mesh* Mesh::create(const std::vector& vertices, meshdata.vertex = vertices; meshdata.subMeshIndices.push_back(indices); meshdata.subMeshIds.push_back(""); - auto meshvertexdata = MeshVertexData::create(meshdata); + auto meshvertexdata = MeshVertexData::create(meshdata, indices.format()); auto indexData = meshvertexdata->getMeshIndexDataByIndex(0); - return create("", indexData); + auto mesh = create("", indexData); + mesh->setIndexFormat(indices.format()); + + return mesh; } Mesh* Mesh::create(std::string_view name, MeshIndexData* indexData, MeshSkin* skin) @@ -728,12 +732,17 @@ CustomCommand::PrimitiveType Mesh::getPrimitiveType() const ssize_t Mesh::getIndexCount() const { - return _meshIndexData->getIndexBuffer()->getSize() / sizeof(uint16_t); + return _meshIndexData->getIndexBuffer()->getSize() / IndexArray::formatToStride(meshIndexFormat); } CustomCommand::IndexFormat Mesh::getIndexFormat() const { - return CustomCommand::IndexFormat::U_SHORT; + return meshIndexFormat; +} + +void Mesh::setIndexFormat(CustomCommand::IndexFormat indexFormat) +{ + meshIndexFormat = indexFormat; } backend::Buffer* Mesh::getIndexBuffer() const diff --git a/core/3d/CCMesh.h b/core/3d/CCMesh.h index cb03a40b4c..c57d957725 100644 --- a/core/3d/CCMesh.h +++ b/core/3d/CCMesh.h @@ -64,7 +64,7 @@ class CC_DLL Mesh : public Ref friend class MeshRenderer; public: - typedef std::vector IndexArray; + /**create mesh from positions, normals, and so on, single SubMesh*/ static Mesh* create(const std::vector& positions, const std::vector& normals, @@ -191,6 +191,12 @@ public: * @lua NA */ CustomCommand::IndexFormat getIndexFormat() const; + /** + * set index format + * + * @lua NA + */ + void setIndexFormat(CustomCommand::IndexFormat indexFormat); /** * get index buffer * @@ -253,6 +259,7 @@ protected: bool _visible; // is the submesh visible bool _isTransparent; // is this mesh transparent, it is a property of material in fact bool _force2DQueue; // add this mesh to 2D render queue + CustomCommand::IndexFormat meshIndexFormat; std::string _name; MeshIndexData* _meshIndexData; diff --git a/core/3d/CCMeshMaterial.cpp b/core/3d/CCMeshMaterial.cpp index 4e7909cf47..224f92fa97 100644 --- a/core/3d/CCMeshMaterial.cpp +++ b/core/3d/CCMeshMaterial.cpp @@ -51,6 +51,9 @@ MeshMaterial* MeshMaterial::_vertexLitMaterialSkin = nullptr; MeshMaterial* MeshMaterial::_diffuseMaterialSkin = nullptr; MeshMaterial* MeshMaterial::_bumpedDiffuseMaterialSkin = nullptr; +MeshMaterial* MeshMaterial::_quadTextureMaterial = nullptr; +MeshMaterial* MeshMaterial::_quadColorMaterial = nullptr; + backend::ProgramState* MeshMaterial::_unLitMaterialProgState = nullptr; backend::ProgramState* MeshMaterial::_unLitNoTexMaterialProgState = nullptr; backend::ProgramState* MeshMaterial::_vertexLitMaterialProgState = nullptr; @@ -63,6 +66,9 @@ backend::ProgramState* MeshMaterial::_vertexLitMaterialSkinProgState = nullp backend::ProgramState* MeshMaterial::_diffuseMaterialSkinProgState = nullptr; backend::ProgramState* MeshMaterial::_bumpedDiffuseMaterialSkinProgState = nullptr; +backend::ProgramState* MeshMaterial::_quadTextureMaterialProgState = nullptr; +backend::ProgramState* MeshMaterial::_quadColorMaterialProgState = nullptr; + void MeshMaterial::createBuiltInMaterial() { auto* program = backend::Program::getBuiltinProgram(backend::ProgramType::SKINPOSITION_TEXTURE_3D); @@ -129,6 +135,22 @@ void MeshMaterial::createBuiltInMaterial() { _bumpedDiffuseMaterialSkin->_type = MeshMaterial::MaterialType::BUMPED_DIFFUSE; } + + program = backend::Program::getBuiltinProgram(backend::ProgramType::QUAD_TEXTURE_2D); + _quadTextureMaterialProgState = new backend::ProgramState(program); + _quadTextureMaterial = new MeshMaterial(); + if (_quadTextureMaterial && _quadTextureMaterial->initWithProgramState(_quadTextureMaterialProgState)) + { + _quadTextureMaterial->_type = MeshMaterial::MaterialType::QUAD_TEXTURE; + } + + program = backend::Program::getBuiltinProgram(backend::ProgramType::QUAD_COLOR_2D); + _quadColorMaterialProgState = new backend::ProgramState(program); + _quadColorMaterial = new MeshMaterial(); + if (_quadColorMaterial && _quadColorMaterial->initWithProgramState(_quadColorMaterialProgState)) + { + _quadColorMaterial->_type = MeshMaterial::MaterialType::QUAD_COLOR; + } } void MeshMaterial::releaseBuiltInMaterial() @@ -213,7 +235,7 @@ MeshMaterial* MeshMaterial::createBuiltInMaterial(MaterialType type, bool skinne break; case MeshMaterial::MaterialType::VERTEX_LIT: - CCASSERT(0, "not implemented."); + CCASSERT(0, "not implemented"); break; case MeshMaterial::MaterialType::DIFFUSE: @@ -228,6 +250,14 @@ MeshMaterial* MeshMaterial::createBuiltInMaterial(MaterialType type, bool skinne material = skinned ? _bumpedDiffuseMaterialSkin : _bumpedDiffuseMaterial; break; + case MeshMaterial::MaterialType::QUAD_TEXTURE: + material = _quadTextureMaterial; + break; + + case MeshMaterial::MaterialType::QUAD_COLOR: + material = _quadColorMaterial; + break; + default: break; } diff --git a/core/3d/CCMeshMaterial.h b/core/3d/CCMeshMaterial.h index 45c7a4fe59..d7ce3f3da9 100644 --- a/core/3d/CCMeshMaterial.h +++ b/core/3d/CCMeshMaterial.h @@ -63,6 +63,8 @@ public: DIFFUSE, // diffuse (pixel lighting) DIFFUSE_NOTEX, // diffuse (without texture) BUMPED_DIFFUSE, // bumped diffuse + QUAD_TEXTURE, // textured quad material + QUAD_COLOR, // colored quad material (without texture) // Custom material CUSTOM, // Create from a material file @@ -133,6 +135,9 @@ protected: static MeshMaterial* _diffuseMaterialSkin; static MeshMaterial* _bumpedDiffuseMaterialSkin; + static MeshMaterial* _quadTextureMaterial; + static MeshMaterial* _quadColorMaterial; + static backend::ProgramState* _unLitMaterialProgState; static backend::ProgramState* _unLitNoTexMaterialProgState; static backend::ProgramState* _vertexLitMaterialProgState; @@ -144,6 +149,9 @@ protected: static backend::ProgramState* _vertexLitMaterialSkinProgState; static backend::ProgramState* _diffuseMaterialSkinProgState; static backend::ProgramState* _bumpedDiffuseMaterialSkinProgState; + + static backend::ProgramState* _quadTextureMaterialProgState; + static backend::ProgramState* _quadColorMaterialProgState; }; /** diff --git a/core/3d/CCMeshVertexIndexData.cpp b/core/3d/CCMeshVertexIndexData.cpp index 688b055aa5..632bd46414 100644 --- a/core/3d/CCMeshVertexIndexData.cpp +++ b/core/3d/CCMeshVertexIndexData.cpp @@ -75,7 +75,7 @@ MeshIndexData::MeshIndexData() { #if CC_ENABLE_CACHE_TEXTURE_DATA _backToForegroundListener = EventListenerCustom::create(EVENT_RENDERER_RECREATED, [this](EventCustom*) { - _indexBuffer->updateData((void*)_indexData.data(), _indexData.size() * sizeof(_indexData[0])); + _indexBuffer->updateData((void*)_indexData.data(), _indexData.bsize()); }); Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_backToForegroundListener, 1); #endif @@ -108,7 +108,7 @@ void MeshVertexData::setVertexData(const std::vector& vertexData) #endif } -MeshVertexData* MeshVertexData::create(const MeshData& meshdata) +MeshVertexData* MeshVertexData::create(const MeshData& meshdata, CustomCommand::IndexFormat format) { auto vertexdata = new MeshVertexData(); vertexdata->_vertexBuffer = backend::Device::getInstance()->newBuffer( @@ -132,28 +132,28 @@ MeshVertexData* MeshVertexData::create(const MeshData& meshdata) bool needCalcAABB = (meshdata.subMeshAABB.size() != meshdata.subMeshIndices.size()); for (size_t i = 0, size = meshdata.subMeshIndices.size(); i < size; ++i) { - auto& index = meshdata.subMeshIndices[i]; + auto& indices = meshdata.subMeshIndices[i]; auto indexBuffer = backend::Device::getInstance()->newBuffer( - index.size() * sizeof(index[0]), backend::BufferType::INDEX, backend::BufferUsage::STATIC); + indices.bsize(), backend::BufferType::INDEX, backend::BufferUsage::STATIC); indexBuffer->autorelease(); #if CC_ENABLE_CACHE_TEXTURE_DATA indexBuffer->usingDefaultStoredData(false); #endif - indexBuffer->updateData((void*)index.data(), index.size() * sizeof(index[0])); + indexBuffer->updateData((void*)indices.data(), indices.bsize()); std::string id = (i < meshdata.subMeshIds.size() ? meshdata.subMeshIds[i] : ""); MeshIndexData* indexdata = nullptr; if (needCalcAABB) { - auto aabb = Bundle3D::calculateAABB(meshdata.vertex, meshdata.getPerVertexSize(), index); + auto aabb = Bundle3D::calculateAABB(meshdata.vertex, meshdata.getPerVertexSize(), indices); indexdata = MeshIndexData::create(id, vertexdata, indexBuffer, aabb); } else indexdata = MeshIndexData::create(id, vertexdata, indexBuffer, meshdata.subMeshAABB[i]); #if CC_ENABLE_CACHE_TEXTURE_DATA - indexdata->setIndexData(index); + indexdata->setIndexData(indices); #endif - vertexdata->_indexs.pushBack(indexdata); + vertexdata->_indices.pushBack(indexdata); } vertexdata->autorelease(); @@ -162,7 +162,7 @@ MeshVertexData* MeshVertexData::create(const MeshData& meshdata) MeshIndexData* MeshVertexData::getMeshIndexDataById(std::string_view id) const { - for (auto it : _indexs) + for (auto it : _indices) { if (it->getId() == id) return it; @@ -193,7 +193,7 @@ MeshVertexData::MeshVertexData() MeshVertexData::~MeshVertexData() { CC_SAFE_RELEASE(_vertexBuffer); - _indexs.clear(); + _indices.clear(); _vertexData.clear(); #if CC_ENABLE_CACHE_TEXTURE_DATA Director::getInstance()->getEventDispatcher()->removeEventListener(_backToForegroundListener); diff --git a/core/3d/CCMeshVertexIndexData.h b/core/3d/CCMeshVertexIndexData.h index bcf51e620a..64c826bde4 100644 --- a/core/3d/CCMeshVertexIndexData.h +++ b/core/3d/CCMeshVertexIndexData.h @@ -112,7 +112,7 @@ class CC_DLL MeshVertexData : public Ref public: /**create*/ - static MeshVertexData* create(const MeshData& meshdata); + static MeshVertexData* create(const MeshData& meshdata, CustomCommand::IndexFormat format = CustomCommand::IndexFormat::U_SHORT); /** get vertexbuffer */ backend::Buffer* getVertexBuffer() const { return _vertexBuffer; } @@ -124,9 +124,9 @@ public: const MeshVertexAttrib& getMeshVertexAttrib(ssize_t index) const { return _attribs[index]; } /** get index data count */ - ssize_t getMeshIndexDataCount() const { return _indexs.size(); } + ssize_t getMeshIndexDataCount() const { return _indices.size(); } /** get index data by index */ - MeshIndexData* getMeshIndexDataByIndex(int index) const { return _indexs.at(index); } + MeshIndexData* getMeshIndexDataByIndex(int index) const { return _indices.at(index); } /** get index data by id */ MeshIndexData* getMeshIndexDataById(std::string_view id) const; @@ -144,8 +144,8 @@ public: protected: backend::Buffer* _vertexBuffer = nullptr; // vertex buffer ssize_t _sizePerVertex = -1; - Vector _indexs; // index data - std::vector _attribs; // vertex attributes + Vector _indices; // index data + std::vector _attribs; // vertex attributes int _vertexCount = 0; // vertex count std::vector _vertexData; diff --git a/core/base/ccTypes.h b/core/base/ccTypes.h index 90d22917f9..ac243bebda 100644 --- a/core/base/ccTypes.h +++ b/core/base/ccTypes.h @@ -33,6 +33,7 @@ THE SOFTWARE. #include "math/CCMath.h" #include "base/CCRef.h" #include "renderer/backend/Types.h" + #include "ccEnums.h" /** diff --git a/core/renderer/CCCustomCommand.h b/core/renderer/CCCustomCommand.h index d7326bea5c..9eba70dfe6 100644 --- a/core/renderer/CCCustomCommand.h +++ b/core/renderer/CCCustomCommand.h @@ -53,13 +53,14 @@ public: using PrimitiveType = backend::PrimitiveType; /** - Buffer usage of vertex/index buffer. If the contents is not updated every frame, - then use STATIC, other use DYNAMIC. + Buffer usage of vertex/index buffer. If the contents are not updated every frame, + then STATIC should be used. Otherwise, DYNAMIC should be used. + This flag is not improtant because most GPU drivers ignore it, so it's best left to STATIC. */ using BufferUsage = backend::BufferUsage; /** - The index format determine the size for index data. U_SHORT is enough for most - cases. + The index format that determines the size of index data. U_SHORT (65535 vertices) is enough for most + cases, But support for U_INT (4294967295 vertices) has been added. */ using IndexFormat = backend::IndexFormat; @@ -208,6 +209,8 @@ TODO: should remove it. inline IndexFormat getIndexFormat() const { return _indexFormat; } + inline void setIndexFormat(IndexFormat format) { _indexFormat = format; } + /** * set a callback which will be invoke before rendering */ diff --git a/core/renderer/CMakeLists.txt b/core/renderer/CMakeLists.txt index aebc22aafa..be2becb233 100644 --- a/core/renderer/CMakeLists.txt +++ b/core/renderer/CMakeLists.txt @@ -33,6 +33,7 @@ set(COCOS_RENDERER_HEADER renderer/backend/Texture.h renderer/backend/PixelFormatUtils.h renderer/backend/Types.h + renderer/backend/Enums.h renderer/backend/VertexLayout.h renderer/backend/ProgramState.h renderer/backend/ProgramStateRegistry.h diff --git a/core/renderer/backend/Enums.h b/core/renderer/backend/Enums.h new file mode 100644 index 0000000000..c761aaaaba --- /dev/null +++ b/core/renderer/backend/Enums.h @@ -0,0 +1,375 @@ +/**************************************************************************** + Copyright (c) 2018-2019 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2020 C4games Ltd. + + https://adxeproject.github.io/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#pragma once + +#include "Macros.h" + +#include +#include +#include +#include "base/bitmask.h" + +CC_BACKEND_BEGIN + +enum class BufferUsage : uint32_t +{ + STATIC, + DYNAMIC +}; + +enum class BufferType : uint32_t +{ + VERTEX, + INDEX +}; + +enum class ShaderStage : uint32_t +{ + VERTEX, + FRAGMENT, + VERTEX_AND_FRAGMENT +}; + +enum class VertexFormat : uint32_t +{ + FLOAT4, + FLOAT3, + FLOAT2, + FLOAT, + INT4, + INT3, + INT2, + INT, + USHORT4, + USHORT2, + UBYTE4 +}; + +/** @typedef backend::PixelFormat + Possible texture pixel formats + */ +enum class PixelFormat : uint32_t +{ + /* below is compression format */ + + /* PVRTCV1, OpenGL support PVRTCv2, but Metal only support PVRTCv1*/ + //! 4-bit PVRTC-compressed texture: PVRTC4 + PVRTC4, + //! 4-bit PVRTC-compressed texture: PVRTC4 (has alpha channel) + PVRTC4A, + //! 2-bit PVRTC-compressed texture: PVRTC2 + PVRTC2, + //! 2-bit PVRTC-compressed texture: PVRTC2 (has alpha channel) + PVRTC2A, + + //! ETC1-compressed texture: ETC1 4 BPP + ETC1, + //! ETC2-compressed texture: ETC2_RGB 4 BPP + ETC2_RGB, + //! ETC2-compressed texture: ETC2_RGBA 8 BPP + ETC2_RGBA, + + //! S3TC-compressed texture: S3TC_Dxt1 + S3TC_DXT1, + //! S3TC-compressed texture: S3TC_Dxt3 + S3TC_DXT3, + //! S3TC-compressed texture: S3TC_Dxt5 + S3TC_DXT5, + + //! ATITC-compressed texture: ATC_RGB + ATC_RGB, + //! ATITC-compressed texture: ATC_EXPLICIT_ALPHA + ATC_EXPLICIT_ALPHA, + //! ATITC-compressed texture: ATC_INTERPOLATED_ALPHA + ATC_INTERPOLATED_ALPHA, + + ASTC4x4, //!< ASTC 4x4 8.0 BPP + ASTC5x5, //!< ASTC 5x5 5.12 BPP + ASTC6x6, //!< ASTC 6x6 3.56 BPP + ASTC8x5, //!< ASTC 8x5 3.20 BPP + ASTC8x6, //!< ASTC 8x6 2.67 BPP + ASTC8x8, //!< ASTC 8x8 2.0 BPP + ASTC10x5, //!< ASTC 10x5 2.56 BPP + //!!!Please append compression pixel format + + /* below is normal pixel format */ + //! 32-bit texture: RGBA8888 + RGBA8, + //! 32-bit texture: BGRA8888 + BGRA8, + //! 24-bit texture: RGBA888 + RGB8, + //! 16-bit texture without Alpha channel + RGB565, // !render as BGR565 + //! 16-bit textures: RGBA4444 + RGBA4, // !render as ABGR4 + //! 16-bit textures: RGB5A1 + RGB5A1, // !render as BGR5A1 + //! 8-bit textures used as masks + A8, + //! 8-bit Luminance texture + L8, + //! 16-bit Luminance with alpha used as masks + LA8, + + //!!!Please append normal pixel format + + /* below is depth compression format */ + // A packed 32-bit combined depth and stencil pixel format with two nomorlized unsigned integer + // components: 24 bits, typically used for a depth render target, and 8 bits, typically used for + // a stencil render target. + D24S8, + //!!!Please append depth stencil pixel format + + /* the count of pixel format supported by adxe */ + COUNT, + + NONE = 0xffff +}; + +enum class TextureUsage : uint32_t +{ + READ, + WRITE, + RENDER_TARGET +}; + +enum class IndexFormat : uint32_t +{ + U_SHORT = 1, + U_INT = 2, +}; + +enum class VertexStepMode : uint32_t +{ + VERTEX, + INSTANCE +}; + +enum class PrimitiveType : uint32_t +{ + POINT, + LINE, + LINE_STRIP, + TRIANGLE, + TRIANGLE_STRIP +}; + +enum class TextureType : uint32_t +{ + TEXTURE_2D, + TEXTURE_CUBE +}; + +enum class SamplerAddressMode : uint32_t +{ + REPEAT, + MIRROR_REPEAT, + CLAMP_TO_EDGE, + DONT_CARE, +}; + +enum class SamplerFilter : uint32_t +{ + NEAREST, + NEAREST_MIPMAP_NEAREST, + NEAREST_MIPMAP_LINEAR, + LINEAR, + LINEAR_MIPMAP_LINEAR, + LINEAR_MIPMAP_NEAREST, + DONT_CARE, +}; + +enum class StencilOperation : uint32_t +{ + KEEP, + ZERO, + REPLACE, + INVERT, + INCREMENT_WRAP, + DECREMENT_WRAP +}; + +enum class CompareFunction : uint32_t +{ + NEVER, + LESS, + LESS_EQUAL, + GREATER, + GREATER_EQUAL, + EQUAL, + NOT_EQUAL, + ALWAYS +}; + +enum class BlendOperation : uint32_t +{ + ADD, + SUBTRACT, + RESERVE_SUBTRACT +}; + +enum class BlendFactor : uint32_t +{ + ZERO, + ONE, + SRC_COLOR, + ONE_MINUS_SRC_COLOR, + SRC_ALPHA, + ONE_MINUS_SRC_ALPHA, + DST_COLOR, + ONE_MINUS_DST_COLOR, + DST_ALPHA, + ONE_MINUS_DST_ALPHA, + CONSTANT_ALPHA, + SRC_ALPHA_SATURATE, + ONE_MINUS_CONSTANT_ALPHA, + BLEND_CLOLOR +}; + +enum class ColorWriteMask : uint32_t +{ + RED_BIT = 0, + GREEN_BIT = 1, + BLUE_BIT = 2, + ALPHA_BIT = 3, + NONE = 0, + RED = 1 << RED_BIT, + GREEN = 1 << GREEN_BIT, + BLUE = 1 << BLUE_BIT, + ALPHA = 1 << ALPHA_BIT, + ALL = 0x0000000F +}; +CC_ENABLE_BITMASK_OPS(ColorWriteMask) +CC_ENABLE_BITSHIFT_OPS(ColorWriteMask) + +/** + * Bitmask for selecting render buffers + */ +enum class TargetBufferFlags : uint8_t +{ + NONE = 0x0u, //!< No buffer selected. + COLOR0 = 0x1u, //!< Color buffer selected. + COLOR1 = 0x2u, //!< Color buffer selected. + COLOR2 = 0x4u, //!< Color buffer selected. + COLOR3 = 0x8u, //!< Color buffer selected. + COLOR = COLOR0, //!< \deprecated + COLOR_ALL = COLOR0 | COLOR1 | COLOR2 | COLOR3, + DEPTH = 0x10u, //!< Depth buffer selected. + STENCIL = 0x20u, //!< Stencil buffer selected. + DEPTH_AND_STENCIL = DEPTH | STENCIL, //!< depth and stencil buffer selected. + ALL = COLOR_ALL | DEPTH | STENCIL //!< Color, depth and stencil buffer selected. +}; +CC_ENABLE_BITMASK_OPS(TargetBufferFlags) + +enum class DepthStencilFlags : unsigned int +{ + NONE = 0, + DEPTH_TEST = 1, + DEPTH_WRITE = 1 << 1, + STENCIL_TEST = 1 << 2, + DEPTH_STENCIL_TEST = DEPTH_TEST | STENCIL_TEST, + ALL = DEPTH_TEST | STENCIL_TEST | DEPTH_WRITE, +}; +CC_ENABLE_BITMASK_OPS(DepthStencilFlags) +CC_ENABLE_BITSHIFT_OPS(DepthStencilFlags) + +enum class CullMode : uint32_t +{ + NONE = 0x00000000, + BACK = 0x00000001, + FRONT = 0x00000002 +}; + +enum class Winding : uint32_t +{ + CLOCK_WISE, + COUNTER_CLOCK_WISE +}; + +enum class TextureCubeFace : uint32_t +{ + POSITIVE_X = 0, + NEGATIVE_X = 1, + POSITIVE_Y = 2, + NEGATIVE_Y = 3, + POSITIVE_Z = 4, + NEGATIVE_Z = 5 +}; + +struct ProgramType +{ + enum : uint32_t + { + POSITION_COLOR_LENGTH_TEXTURE, // positionColorLengthTexture_vert, positionColorLengthTexture_frag + POSITION_COLOR_TEXTURE_AS_POINTSIZE, // positionColorTextureAsPointsize_vert, positionColor_frag + POSITION_COLOR, // positionColor_vert, positionColor_frag + POSITION_UCOLOR, // positionUColor_vert, positionUColor_frag + POSITION_TEXTURE, // positionTexture_vert, positionTexture_frag + POSITION_TEXTURE_COLOR, // positionTextureColor_vert, positionTextureColor_frag + POSITION_TEXTURE_COLOR_ALPHA_TEST, // positionTextureColor_vert, positionTextureColorAlphaTest_frag + LABEL_NORMAL, // positionTextureColor_vert, label_normal_frag + LABLE_OUTLINE, // positionTextureColor_vert, labelOutline_frag + LABLE_DISTANCEFIELD_GLOW, // positionTextureColor_vert, labelDistanceFieldGlow_frag + LABEL_DISTANCE_NORMAL, // positionTextureColor_vert, label_distanceNormal_frag + + LAYER_RADIA_GRADIENT, // position_vert, layer_radialGradient_frag + + DUAL_SAMPLER, + DUAL_SAMPLER_GRAY, + ETC1 = DUAL_SAMPLER, // positionTextureColor_vert, etc1_frag + ETC1_GRAY = DUAL_SAMPLER_GRAY, // positionTextureColor_vert, etc1Gray_frag + GRAY_SCALE, // positionTextureColor_vert, grayScale_frag + CAMERA_CLEAR, // cameraClear_vert, cameraClear_frag + + TERRAIN_3D, // CC3D_terrain_vert, CC3D_terrain_frag + LINE_COLOR_3D, // lineColor3D_vert, lineColor3D_frag + SKYBOX_3D, // CC3D_skybox_vert, CC3D_skybox_frag + SKINPOSITION_TEXTURE_3D, // CC3D_skinPositionTexture_vert, CC3D_colorTexture_frag + SKINPOSITION_NORMAL_TEXTURE_3D, // CC3D_skinPositionNormalTexture_vert, CC3D_colorNormalTexture_frag + POSITION_NORMAL_TEXTURE_3D, // CC3D_positionNormalTexture_vert, CC3D_colorNormalTexture_frag + POSITION_NORMAL_3D, // CC3D_positionNormalTexture_vert, CC3D_colorNormal_frag + POSITION_TEXTURE_3D, // CC3D_positionTexture_vert, CC3D_colorTexture_frag + POSITION_3D, // CC3D_positionTexture_vert, CC3D_color_frag + POSITION_BUMPEDNORMAL_TEXTURE_3D, // CC3D_positionNormalTexture_vert, CC3D_colorNormalTexture_frag + SKINPOSITION_BUMPEDNORMAL_TEXTURE_3D, // CC3D_skinPositionNormalTexture_vert, CC3D_colorNormalTexture_frag + PARTICLE_TEXTURE_3D, // CC3D_particle_vert, CC3D_particleTexture_frag + PARTICLE_COLOR_3D, // CC3D_particle_vert, CC3D_particleColor_frag + + QUAD_COLOR_2D, // CC2D_quad_vert, CC2D_quadColor_frag + QUAD_TEXTURE_2D, // CC2D_quad_vert, CC2D_quadTexture_frag + + HSV, + HSV_DUAL_SAMPLER, + HSV_ETC1 = HSV_DUAL_SAMPLER, + + BUILTIN_COUNT, + + CUSTOM_PROGRAM = 0x1000, // user-define program, used by engine + }; +}; + +CC_BACKEND_END diff --git a/core/renderer/backend/ProgramCache.cpp b/core/renderer/backend/ProgramCache.cpp index ba5b8cdfc3..109bb3e3d6 100644 --- a/core/renderer/backend/ProgramCache.cpp +++ b/core/renderer/backend/ProgramCache.cpp @@ -123,6 +123,8 @@ bool ProgramCache::init() registerProgramFactory(ProgramType::TERRAIN_3D, CC3D_terrain_vert, CC3D_terrain_frag); registerProgramFactory(ProgramType::PARTICLE_TEXTURE_3D, CC3D_particle_vert, CC3D_particleTexture_frag); registerProgramFactory(ProgramType::PARTICLE_COLOR_3D, CC3D_particle_vert, CC3D_particleColor_frag); + registerProgramFactory(ProgramType::QUAD_COLOR_2D, CC2D_quad_vert, CC2D_quadColor_frag); + registerProgramFactory(ProgramType::QUAD_TEXTURE_2D, CC2D_quad_vert, CC2D_quadTexture_frag); registerProgramFactory(ProgramType::HSV, positionTextureColor_vert, hsv_frag); registerProgramFactory(ProgramType::HSV_DUAL_SAMPLER, positionTextureColor_vert, dualSampler_hsv_frag); diff --git a/core/renderer/backend/Types.h b/core/renderer/backend/Types.h index 0f2a85d3f5..b3932c99a3 100644 --- a/core/renderer/backend/Types.h +++ b/core/renderer/backend/Types.h @@ -32,259 +32,10 @@ #include #include "base/bitmask.h" +#include "Enums.h" + CC_BACKEND_BEGIN -enum class BufferUsage : uint32_t -{ - STATIC, - DYNAMIC -}; - -enum class BufferType : uint32_t -{ - VERTEX, - INDEX -}; - -enum class ShaderStage : uint32_t -{ - VERTEX, - FRAGMENT, - VERTEX_AND_FRAGMENT -}; - -enum class VertexFormat : uint32_t -{ - FLOAT4, - FLOAT3, - FLOAT2, - FLOAT, - INT4, - INT3, - INT2, - INT, - USHORT4, - USHORT2, - UBYTE4 -}; - -/** @typedef backend::PixelFormat - Possible texture pixel formats - */ -enum class PixelFormat : uint32_t -{ - /* below is compression format */ - - /* PVRTCV1, OpenGL support PVRTCv2, but Metal only support PVRTCv1*/ - //! 4-bit PVRTC-compressed texture: PVRTC4 - PVRTC4, - //! 4-bit PVRTC-compressed texture: PVRTC4 (has alpha channel) - PVRTC4A, - //! 2-bit PVRTC-compressed texture: PVRTC2 - PVRTC2, - //! 2-bit PVRTC-compressed texture: PVRTC2 (has alpha channel) - PVRTC2A, - - //! ETC1-compressed texture: ETC1 4 BPP - ETC1, - //! ETC2-compressed texture: ETC2_RGB 4 BPP - ETC2_RGB, - //! ETC2-compressed texture: ETC2_RGBA 8 BPP - ETC2_RGBA, - - //! S3TC-compressed texture: S3TC_Dxt1 - S3TC_DXT1, - //! S3TC-compressed texture: S3TC_Dxt3 - S3TC_DXT3, - //! S3TC-compressed texture: S3TC_Dxt5 - S3TC_DXT5, - - //! ATITC-compressed texture: ATC_RGB - ATC_RGB, - //! ATITC-compressed texture: ATC_EXPLICIT_ALPHA - ATC_EXPLICIT_ALPHA, - //! ATITC-compressed texture: ATC_INTERPOLATED_ALPHA - ATC_INTERPOLATED_ALPHA, - - ASTC4x4, //!< ASTC 4x4 8.0 BPP - ASTC5x5, //!< ASTC 5x5 5.12 BPP - ASTC6x6, //!< ASTC 6x6 3.56 BPP - ASTC8x5, //!< ASTC 8x5 3.20 BPP - ASTC8x6, //!< ASTC 8x6 2.67 BPP - ASTC8x8, //!< ASTC 8x8 2.0 BPP - ASTC10x5, //!< ASTC 10x5 2.56 BPP - //!!!Please append compression pixel format - - /* below is normal pixel format */ - //! 32-bit texture: RGBA8888 - RGBA8, - //! 32-bit texture: BGRA8888 - BGRA8, - //! 24-bit texture: RGBA888 - RGB8, - //! 16-bit texture without Alpha channel - RGB565, // !render as BGR565 - //! 16-bit textures: RGBA4444 - RGBA4, // !render as ABGR4 - //! 16-bit textures: RGB5A1 - RGB5A1, // !render as BGR5A1 - //! 8-bit textures used as masks - A8, - //! 8-bit Luminance texture - L8, - //! 16-bit Luminance with alpha used as masks - LA8, - - //!!!Please append normal pixel format - - /* below is depth compression format */ - // A packed 32-bit combined depth and stencil pixel format with two nomorlized unsigned integer - // components: 24 bits, typically used for a depth render target, and 8 bits, typically used for - // a stencil render target. - D24S8, - //!!!Please append depth stencil pixel format - - /* the count of pixel format supported by adxe */ - COUNT, - - NONE = 0xffff -}; - -enum class TextureUsage : uint32_t -{ - READ, - WRITE, - RENDER_TARGET -}; - -enum class IndexFormat : uint32_t -{ - U_SHORT, - U_INT -}; - -enum class VertexStepMode : uint32_t -{ - VERTEX, - INSTANCE -}; - -enum class PrimitiveType : uint32_t -{ - POINT, - LINE, - LINE_STRIP, - TRIANGLE, - TRIANGLE_STRIP -}; - -enum class TextureType : uint32_t -{ - TEXTURE_2D, - TEXTURE_CUBE -}; - -enum class SamplerAddressMode : uint32_t -{ - REPEAT, - MIRROR_REPEAT, - CLAMP_TO_EDGE, - DONT_CARE, -}; - -enum class SamplerFilter : uint32_t -{ - NEAREST, - NEAREST_MIPMAP_NEAREST, - NEAREST_MIPMAP_LINEAR, - LINEAR, - LINEAR_MIPMAP_LINEAR, - LINEAR_MIPMAP_NEAREST, - DONT_CARE, -}; - -enum class StencilOperation : uint32_t -{ - KEEP, - ZERO, - REPLACE, - INVERT, - INCREMENT_WRAP, - DECREMENT_WRAP -}; - -enum class CompareFunction : uint32_t -{ - NEVER, - LESS, - LESS_EQUAL, - GREATER, - GREATER_EQUAL, - EQUAL, - NOT_EQUAL, - ALWAYS -}; - -enum class BlendOperation : uint32_t -{ - ADD, - SUBTRACT, - RESERVE_SUBTRACT -}; - -enum class BlendFactor : uint32_t -{ - ZERO, - ONE, - SRC_COLOR, - ONE_MINUS_SRC_COLOR, - SRC_ALPHA, - ONE_MINUS_SRC_ALPHA, - DST_COLOR, - ONE_MINUS_DST_COLOR, - DST_ALPHA, - ONE_MINUS_DST_ALPHA, - CONSTANT_ALPHA, - SRC_ALPHA_SATURATE, - ONE_MINUS_CONSTANT_ALPHA, - BLEND_CLOLOR -}; - -enum class ColorWriteMask : uint32_t -{ - RED_BIT = 0, - GREEN_BIT = 1, - BLUE_BIT = 2, - ALPHA_BIT = 3, - NONE = 0, - RED = 1 << RED_BIT, - GREEN = 1 << GREEN_BIT, - BLUE = 1 << BLUE_BIT, - ALPHA = 1 << ALPHA_BIT, - ALL = 0x0000000F -}; -CC_ENABLE_BITMASK_OPS(ColorWriteMask) -CC_ENABLE_BITSHIFT_OPS(ColorWriteMask) - -/** - * Bitmask for selecting render buffers - */ -enum class TargetBufferFlags : uint8_t -{ - NONE = 0x0u, //!< No buffer selected. - COLOR0 = 0x1u, //!< Color buffer selected. - COLOR1 = 0x2u, //!< Color buffer selected. - COLOR2 = 0x4u, //!< Color buffer selected. - COLOR3 = 0x8u, //!< Color buffer selected. - COLOR = COLOR0, //!< \deprecated - COLOR_ALL = COLOR0 | COLOR1 | COLOR2 | COLOR3, - DEPTH = 0x10u, //!< Depth buffer selected. - STENCIL = 0x20u, //!< Stencil buffer selected. - DEPTH_AND_STENCIL = DEPTH | STENCIL, //!< depth and stencil buffer selected. - ALL = COLOR_ALL | DEPTH | STENCIL //!< Color, depth and stencil buffer selected. -}; -CC_ENABLE_BITMASK_OPS(TargetBufferFlags) - inline TargetBufferFlags getMRTColorFlag(size_t index) noexcept { assert(index < 4); @@ -294,18 +45,6 @@ inline TargetBufferFlags getMRTColorFlag(size_t index) noexcept typedef TargetBufferFlags ClearFlag; typedef TargetBufferFlags RenderTargetFlag; -enum class DepthStencilFlags : unsigned int -{ - NONE = 0, - DEPTH_TEST = 1, - DEPTH_WRITE = 1 << 1, - STENCIL_TEST = 1 << 2, - DEPTH_STENCIL_TEST = DEPTH_TEST | STENCIL_TEST, - ALL = DEPTH_TEST | STENCIL_TEST | DEPTH_WRITE, -}; -CC_ENABLE_BITMASK_OPS(DepthStencilFlags) -CC_ENABLE_BITSHIFT_OPS(DepthStencilFlags) - struct SamplerDescriptor { SamplerFilter magFilter = SamplerFilter::LINEAR; @@ -323,19 +62,6 @@ struct SamplerDescriptor {} }; -enum class CullMode : uint32_t -{ - NONE = 0x00000000, - BACK = 0x00000001, - FRONT = 0x00000002 -}; - -enum class Winding : uint32_t -{ - CLOCK_WISE, - COUNTER_CLOCK_WISE -}; - struct UniformInfo { int count = 0; @@ -382,65 +108,6 @@ struct AttributeBindInfo int type = 0; }; -enum class TextureCubeFace : uint32_t -{ - POSITIVE_X = 0, - NEGATIVE_X = 1, - POSITIVE_Y = 2, - NEGATIVE_Y = 3, - POSITIVE_Z = 4, - NEGATIVE_Z = 5 -}; - -struct ProgramType -{ - enum : uint32_t - { - POSITION_COLOR_LENGTH_TEXTURE, // positionColorLengthTexture_vert, positionColorLengthTexture_frag - POSITION_COLOR_TEXTURE_AS_POINTSIZE, // positionColorTextureAsPointsize_vert, positionColor_frag - POSITION_COLOR, // positionColor_vert, positionColor_frag - POSITION_UCOLOR, // positionUColor_vert, positionUColor_frag - POSITION_TEXTURE, // positionTexture_vert, positionTexture_frag - POSITION_TEXTURE_COLOR, // positionTextureColor_vert, positionTextureColor_frag - POSITION_TEXTURE_COLOR_ALPHA_TEST, // positionTextureColor_vert, positionTextureColorAlphaTest_frag - LABEL_NORMAL, // positionTextureColor_vert, label_normal_frag - LABLE_OUTLINE, // positionTextureColor_vert, labelOutline_frag - LABLE_DISTANCEFIELD_GLOW, // positionTextureColor_vert, labelDistanceFieldGlow_frag - LABEL_DISTANCE_NORMAL, // positionTextureColor_vert, label_distanceNormal_frag - - LAYER_RADIA_GRADIENT, // position_vert, layer_radialGradient_frag - - DUAL_SAMPLER, - DUAL_SAMPLER_GRAY, - ETC1 = DUAL_SAMPLER, // positionTextureColor_vert, etc1_frag - ETC1_GRAY = DUAL_SAMPLER_GRAY, // positionTextureColor_vert, etc1Gray_frag - GRAY_SCALE, // positionTextureColor_vert, grayScale_frag - CAMERA_CLEAR, // cameraClear_vert, cameraClear_frag - - TERRAIN_3D, // CC3D_terrain_vert, CC3D_terrain_frag - LINE_COLOR_3D, // lineColor3D_vert, lineColor3D_frag - SKYBOX_3D, // CC3D_skybox_vert, CC3D_skybox_frag - SKINPOSITION_TEXTURE_3D, // CC3D_skinPositionTexture_vert, CC3D_colorTexture_frag - SKINPOSITION_NORMAL_TEXTURE_3D, // CC3D_skinPositionNormalTexture_vert, CC3D_colorNormalTexture_frag - POSITION_NORMAL_TEXTURE_3D, // CC3D_positionNormalTexture_vert, CC3D_colorNormalTexture_frag - POSITION_NORMAL_3D, // CC3D_positionNormalTexture_vert, CC3D_colorNormal_frag - POSITION_TEXTURE_3D, // CC3D_positionTexture_vert, CC3D_colorTexture_frag - POSITION_3D, // CC3D_positionTexture_vert, CC3D_color_frag - POSITION_BUMPEDNORMAL_TEXTURE_3D, // CC3D_positionNormalTexture_vert, CC3D_colorNormalTexture_frag - SKINPOSITION_BUMPEDNORMAL_TEXTURE_3D, // CC3D_skinPositionNormalTexture_vert, CC3D_colorNormalTexture_frag - PARTICLE_TEXTURE_3D, // CC3D_particle_vert, CC3D_particleTexture_frag - PARTICLE_COLOR_3D, // CC3D_particle_vert, CC3D_particleColor_frag - - HSV, - HSV_DUAL_SAMPLER, - HSV_ETC1 = HSV_DUAL_SAMPLER, - - BUILTIN_COUNT, - - CUSTOM_PROGRAM = 0x1000, // user-define program, used by engine - }; -}; - /// built-in uniform name static const char* UNIFORM_NAME_MVP_MATRIX = "u_MVPMatrix"; static const char* UNIFORM_NAME_TEXTURE = "u_tex0"; diff --git a/core/renderer/ccShaders.cpp b/core/renderer/ccShaders.cpp index 0b5cdfb106..1e0914d42d 100644 --- a/core/renderer/ccShaders.cpp +++ b/core/renderer/ccShaders.cpp @@ -73,4 +73,7 @@ NS_CC_BEGIN #include "renderer/shaders/hsv.frag" #include "renderer/shaders/dualSampler_hsv.frag" +#include "renderer/shaders/quad.vert" +#include "renderer/shaders/quad.frag" + NS_CC_END diff --git a/core/renderer/ccShaders.h b/core/renderer/ccShaders.h index 16c00c3800..6168d29b21 100644 --- a/core/renderer/ccShaders.h +++ b/core/renderer/ccShaders.h @@ -78,6 +78,10 @@ extern CC_DLL const char* CC3D_skybox_vert; extern CC_DLL const char* CC3D_terrain_frag; extern CC_DLL const char* CC3D_terrain_vert; +extern CC_DLL const char* CC2D_quadTexture_frag; +extern CC_DLL const char* CC2D_quadColor_frag; +extern CC_DLL const char* CC2D_quad_vert; + extern CC_DLL const char* hsv_frag; extern CC_DLL const char* dualSampler_hsv_frag; NS_CC_END diff --git a/core/renderer/shaders/quad.frag b/core/renderer/shaders/quad.frag new file mode 100644 index 0000000000..0abd3e4611 --- /dev/null +++ b/core/renderer/shaders/quad.frag @@ -0,0 +1,58 @@ +/**************************************************************************** + Copyright (c) 2018-2019 Xiamen Yaji Software Co., Ltd. + + https://adxeproject.github.io/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + + +const char* CC2D_quadTexture_frag = R"( + +#ifdef GL_ES +varying mediump vec2 TextureCoordOut; +varying mediump vec4 ColorOut; +#else +varying vec4 ColorOut; +varying vec2 TextureCoordOut; +#endif +uniform vec4 u_color; + +uniform sampler2D u_tex0; + +void main(void) +{ + gl_FragColor = texture2D(u_tex0, TextureCoordOut) * ColorOut * u_color; +} +)"; + +const char* CC2D_quadColor_frag = R"( + +#ifdef GL_ES +varying mediump vec4 ColorOut; +#else +varying vec4 ColorOut; +#endif +uniform vec4 u_color; + +void main(void) +{ + gl_FragColor = ColorOut * u_color; +} +)"; diff --git a/core/renderer/shaders/quad.vert b/core/renderer/shaders/quad.vert new file mode 100644 index 0000000000..02d3aaaf9f --- /dev/null +++ b/core/renderer/shaders/quad.vert @@ -0,0 +1,44 @@ +/**************************************************************************** + Copyright (c) 2018-2019 Xiamen Yaji Software Co., Ltd. + + https://adxeproject.github.io/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + + +const char* CC2D_quad_vert = R"( + +attribute vec4 a_position; +attribute vec4 a_color; +attribute vec2 a_texCoord; + +varying vec2 TextureCoordOut; +varying vec4 ColorOut; + +uniform mat4 u_PMatrix; +void main() +{ + ColorOut = a_color; + TextureCoordOut = a_texCoord; + TextureCoordOut.y = 1.0 - TextureCoordOut.y; + gl_Position = u_PMatrix * a_position; +} + +)"; diff --git a/thirdparty/yasio/detail/byte_buffer.hpp b/thirdparty/yasio/detail/byte_buffer.hpp index 2afa9d0563..bdcb86f840 100644 --- a/thirdparty/yasio/detail/byte_buffer.hpp +++ b/thirdparty/yasio/detail/byte_buffer.hpp @@ -41,6 +41,7 @@ The byte_buffer concepts: #include #include #include +#include #include "yasio/compiler/feature_test.hpp" namespace yasio @@ -48,9 +49,11 @@ namespace yasio struct default_allocator { static void* reallocate(void* old_block, size_t /*old_size*/, size_t new_size) { return ::realloc(old_block, new_size); } }; -template class basic_byte_buffer final { +template +class basic_byte_buffer { static_assert(std::is_same<_Elem, char>::value || std::is_same<_Elem, unsigned char>::value, "The basic_byte_buffer only accept type which is char or unsigned char!"); + public: using pointer = _Elem*; using const_pointer = const _Elem*; @@ -61,29 +64,77 @@ public: basic_byte_buffer(size_t count, std::true_type /*fit*/) { resize_fit(count); } basic_byte_buffer(size_t count, _Elem val) { resize(count, val); } basic_byte_buffer(size_t count, _Elem val, std::true_type /*fit*/) { resize_fit(count, val); } - template basic_byte_buffer(_Iter first, _Iter last) { _Assign_range(first, last); } - template basic_byte_buffer(_Iter first, _Iter last, std::true_type /*fit*/) { _Assign_range(first, last, std::true_type{}); } - basic_byte_buffer(const basic_byte_buffer& rhs) { _Assign_range(rhs.begin(), rhs.end()); }; - basic_byte_buffer(const basic_byte_buffer& rhs, std::true_type /*fit*/) { _Assign_range(rhs.begin(), rhs.end(), std::true_type{}); }; - basic_byte_buffer(basic_byte_buffer&& rhs) noexcept { _Assign_rv(std::move(rhs)); } - ~basic_byte_buffer() { shrink_to_fit(0); } - basic_byte_buffer& operator=(const basic_byte_buffer& rhs) { return assign(rhs.begin(), rhs.end()); } - basic_byte_buffer& operator=(basic_byte_buffer&& rhs) noexcept { return this->swap(rhs); } - template basic_byte_buffer& assign(const _Iter first, const _Iter last) + template + basic_byte_buffer(_Iter first, _Iter last) { - clear(); - _Assign_range(first, last); + assign(first, last); + } + template + basic_byte_buffer(_Iter first, _Iter last, std::true_type /*fit*/) + { + assign(first, last, std::true_type{}); + } + basic_byte_buffer(const basic_byte_buffer& rhs) { assign(rhs); }; + basic_byte_buffer(const basic_byte_buffer& rhs, std::true_type /*fit*/) { assign(rhs, std::true_type{}); }; + basic_byte_buffer(basic_byte_buffer&& rhs) noexcept { assign(std::move(rhs)); } + template + basic_byte_buffer(std::initializer_list<_Ty> rhs) + { + assign(rhs); + } + template + basic_byte_buffer(std::initializer_list<_Ty> rhs, std::true_type /*fit*/) + { + assign(rhs, std::true_type{}); + } + ~basic_byte_buffer() { shrink_to_fit(0); } + basic_byte_buffer& operator=(const basic_byte_buffer& rhs) + { + assign(rhs); return *this; } - basic_byte_buffer& swap(basic_byte_buffer& rhs) noexcept + basic_byte_buffer& operator=(basic_byte_buffer&& rhs) noexcept + { + this->swap(rhs); + return *this; + } + template + void assign(const _Iter first, const _Iter last) + { + _Assign_range(first, last); + } + template + void assign(const _Iter first, const _Iter last, std::true_type /*fit*/) + { + _Assign_range(first, last, std::true_type{}); + } + void assign(const basic_byte_buffer& rhs) { _Assign_range(rhs.begin(), rhs.end()); } + void assign(const basic_byte_buffer& rhs, std::true_type) { _Assign_range(rhs.begin(), rhs.end(), std::true_type{}); } + void assign(basic_byte_buffer&& rhs) { _Assign_rv(std::move(rhs)); } + template + void assign(std::initializer_list<_Ty> rhs) + { + _Assign_range((_Elem*)rhs.begin(), (_Elem*)rhs.end()); + } + template + void assign(std::initializer_list<_Ty> rhs, std::true_type /*fit*/) + { + _Assign_range((_Elem*)rhs.begin(), (_Elem*)rhs.end(), std::true_type{}); + } + void swap(basic_byte_buffer& rhs) noexcept { char _Tmp[sizeof(rhs)]; memcpy(_Tmp, &rhs, sizeof(rhs)); memcpy(&rhs, this, sizeof(rhs)); memcpy(this, _Tmp, sizeof(_Tmp)); - return *this; } - template void insert(_Elem* where, _Iter first, const _Iter last) + template + void insert(size_t offset, _Iter first, const _Iter last) + { + insert((std::min)(_Myfirst + offset, _Mylast), first, last); + } + template + void insert(_Elem* where, _Iter first, const _Iter last) { if (where == _Mylast) append(first, last); @@ -102,8 +153,13 @@ public: } } } - template void append(_Iter first, const _Iter last) { append_n(first, std::distance(first, last)); } - template void append_n(_Iter first, ptrdiff_t count) + template + void append(_Iter first, const _Iter last) + { + append_n(first, std::distance(first, last)); + } + template + void append_n(_Iter first, ptrdiff_t count) { if (count > 0) { @@ -206,7 +262,8 @@ public: _Myend = _Mylast = _Myfirst + len; } } - template _Elem* detach(_TSIZE& len) noexcept + template + _Elem* detach(_TSIZE& len) noexcept { auto ptr = _Myfirst; len = static_cast<_TSIZE>(this->size()); @@ -215,13 +272,17 @@ public: } private: - template void _Assign_range(_Iter first, _Iter last) + template + void _Assign_range(_Iter first, _Iter last) { + _Mylast = _Myfirst; if (last > first) std::copy(first, last, resize(std::distance(first, last))); } - template void _Assign_range(_Iter first, _Iter last, std::true_type) + template + void _Assign_range(_Iter first, _Iter last, std::true_type) { + _Mylast = _Myfirst; if (last > first) std::copy(first, last, resize_fit(std::distance(first, last))); } diff --git a/thirdparty/yasio/detail/ifaddrs.hpp b/thirdparty/yasio/detail/ifaddrs.hpp index 1df6135139..7584bd730a 100644 --- a/thirdparty/yasio/detail/ifaddrs.hpp +++ b/thirdparty/yasio/detail/ifaddrs.hpp @@ -372,7 +372,7 @@ static int open_netlink_session(netlink_session* session) assert(session != 0); memset(session, 0, sizeof(*session)); - session->sock_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); + session->sock_fd = ::socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (session->sock_fd == -1) { YASIO_LOG("Failed to create a netlink socket. %s", strerror(errno)); @@ -392,7 +392,7 @@ static int open_netlink_session(netlink_session* session) session->them.nl_family = AF_NETLINK; - if (bind(session->sock_fd, (struct sockaddr*)&session->us, sizeof(session->us)) < 0) + if (::bind(session->sock_fd, (struct sockaddr*)&session->us, sizeof(session->us)) < 0) { YASIO_LOG("Failed to bind to the netlink socket. %s", strerror(errno)); return -1; @@ -430,7 +430,7 @@ static int send_netlink_dump_request(netlink_session* session, int type) session->message_header.msg_iovlen = 1; session->message_header.msg_iov = &session->payload_vector; - if (sendmsg(session->sock_fd, (const struct msghdr*)&session->message_header, 0) < 0) + if (::sendmsg(session->sock_fd, (const struct msghdr*)&session->message_header, 0) < 0) { YASIO_LOG("Failed to send netlink message. %s", strerror(errno)); return -1; @@ -510,7 +510,7 @@ static int parse_netlink_reply(netlink_session* session, struct ifaddrs** ifaddr netlink_reply.msg_iovlen = 1; netlink_reply.msg_iov = &reply_vector; - length = recvmsg(session->sock_fd, &netlink_reply, 0); + length = ::recvmsg(session->sock_fd, &netlink_reply, 0); YASIO_LOGV(" length == %d", static_cast(length)); if (length < 0)