#include "render/ModelNode.h" #include "model/Parallel.h" #include "render/GpuCaps.h" #include "render/Shaders.h" #include "render/TextureLoader.h" #include #include #include #include #include #include #include namespace mr { namespace { // MMD's default light: direction (-0.5, -1, 0.5) in its left-handed space. const osg::Vec3f kMmdLightDirection(-0.5f, -1.0f, -0.5f); class DeformCallback : public osg::NodeCallback { public: void operator()(osg::Node* node, osg::NodeVisitor* nv) override { static_cast(node)->updateDeformation(); traverse(node, nv); } }; // In hardware mode the vertex arrays hold rest positions, so bounds come from the posed skeleton. class PosedBoundsCallback : public osg::Drawable::ComputeBoundingBoxCallback { public: explicit PosedBoundsCallback(const ModelNode* node) : node_(node) {} osg::BoundingBox computeBound(const osg::Drawable& drawable) const override { if (node_->activeSkinningMode() == SkinningMode::Hardware && node_->posedBounds().valid()) return node_->posedBounds(); return drawable.computeBoundingBox(); } private: const ModelNode* node_; }; } // namespace ModelNode::ModelNode(std::shared_ptr model) : model_(std::move(model)), poser_(model_) { setMatrix(osg::Matrix::rotate(osg::PI_2, osg::X_AXIS)); // Y-up model -> Z-up world setDataVariance(osg::Object::DYNAMIC); osg::StateSet* ss = getOrCreateStateSet(); ss->setAttributeAndModes(createModelProgram(), osg::StateAttribute::ON); ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF); ss->addUniform(new osg::Uniform("u_texture", 0)); ss->addUniform(new osg::Uniform("u_sphere", 1)); ss->addUniform(new osg::Uniform("u_toon", 2)); ss->addUniform(new osg::Uniform("u_lightColor", osg::Vec3f(0.6f, 0.6f, 0.6f))); const bool isMmd = model_->format != SourceFormat::Assimp; lightingUniform_ = new osg::Uniform("u_lightingModel", isMmd ? 0 : 1); lightFollowUniform_ = new osg::Uniform("u_lightFollowsCamera", 0); osg::Vec3f worldLight = osg::Matrixf::transform3x3(kMmdLightDirection, osg::Matrixf(getMatrix())); lightDirUniform_ = new osg::Uniform("u_lightDirection", worldLight); ss->addUniform(lightingUniform_); ss->addUniform(lightFollowUniform_); ss->addUniform(lightDirUniform_); textures_.resize(model_->textures.size()); textureTried_.assign(model_->textures.size(), false); preloadTextureImages(); buildMesh(); buildSkinning(); buildSkeleton(); setShowSkeleton(false); updateDeformation(); setUpdateCallback(new DeformCallback); } // Decoding large PNGs dominates load time, so decode all textures in parallel up front. void ModelNode::preloadTextureImages() { const auto& textures = model_->textures; preloadedImages_.assign(textures.size(), nullptr); parallelFor(textures.size(), 1, [&](size_t begin, size_t end) { for (size_t i = begin; i < end; ++i) preloadedImages_[i] = loadTextureImage(textures[i]); }); } osg::Texture2D* ModelNode::texture(int index, bool clamp) { if (index < 0 || index >= static_cast(textures_.size())) return nullptr; if (!textureTried_[index]) { textureTried_[index] = true; if (osg::ref_ptr image = std::move(preloadedImages_[index])) textures_[index] = makeTexture(image.get(), clamp); } return textures_[index].get(); } osg::StateSet* ModelNode::buildMaterialState(const Material& m, int order) { auto* ss = new osg::StateSet; ss->addUniform(new osg::Uniform("u_diffuse", m.diffuse)); ss->addUniform(new osg::Uniform("u_ambient", m.ambient)); ss->addUniform(new osg::Uniform("u_specular", m.specular)); ss->addUniform(new osg::Uniform("u_shininess", m.shininess)); osg::Texture2D* main = texture(m.texture, false); if (main) ss->setTextureAttributeAndModes(0, main, osg::StateAttribute::ON); ss->addUniform(new osg::Uniform("u_useTexture", main ? 1 : 0)); osg::Texture2D* sphere = nullptr; if (m.sphereMode == SphereMode::Multiply || m.sphereMode == SphereMode::Add) sphere = texture(m.sphereTexture, true); if (sphere) ss->setTextureAttributeAndModes(1, sphere, osg::StateAttribute::ON); ss->addUniform(new osg::Uniform("u_sphereMode", !sphere ? 0 : m.sphereMode == SphereMode::Add ? 2 : 1)); osg::Texture2D* toon = texture(m.toonTexture, true); if (!toon && m.sharedToon >= 0 && m.sharedToon <= 9) { if (!sharedToons_[m.sharedToon]) sharedToons_[m.sharedToon] = makeTexture(makeSharedToonImage(m.sharedToon), true); toon = sharedToons_[m.sharedToon].get(); } if (toon) ss->setTextureAttributeAndModes(2, toon, osg::StateAttribute::ON); ss->addUniform(new osg::Uniform("u_useToon", toon ? 1 : 0)); osg::ref_ptr cull = new osg::CullFace(osg::CullFace::BACK); ss->setAttributeAndModes(cull, m.doubleSided ? osg::StateAttribute::OFF : osg::StateAttribute::ON); // MMD draws materials in file order with alpha blending always enabled. ss->setAttributeAndModes(new osg::BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), osg::StateAttribute::ON); ss->setRenderBinDetails(10 + order, "RenderBin"); return ss; } void ModelNode::buildMesh() { const Model& model = *model_; positions_ = new osg::Vec3Array(model.vertices.size()); normals_ = new osg::Vec3Array(model.vertices.size()); osg::ref_ptr uvs = new osg::Vec2Array(model.vertices.size()); for (size_t i = 0; i < model.vertices.size(); ++i) { (*positions_)[i] = model.vertices[i].position; (*normals_)[i] = model.vertices[i].normal; (*uvs)[i] = model.vertices[i].uv; } positions_->setDataVariance(osg::Object::DYNAMIC); normals_->setDataVariance(osg::Object::DYNAMIC); osg::ref_ptr geode = new osg::Geode; for (size_t i = 0; i < model.materials.size(); ++i) { const Material& m = model.materials[i]; if (m.indexCount == 0) continue; osg::ref_ptr geom = new osg::Geometry; geom->setName(m.name); geom->setDataVariance(osg::Object::DYNAMIC); geom->setUseDisplayList(false); geom->setUseVertexBufferObjects(true); geom->setVertexArray(positions_); geom->setNormalArray(normals_, osg::Array::BIND_PER_VERTEX); geom->setTexCoordArray(0, uvs, osg::Array::BIND_PER_VERTEX); osg::ref_ptr elements = new osg::DrawElementsUInt( GL_TRIANGLES, model.indices.begin() + m.indexOffset, model.indices.begin() + m.indexOffset + m.indexCount); geom->addPrimitiveSet(elements); geom->setStateSet(buildMaterialState(m, static_cast(i))); geom->setComputeBoundingBoxCallback(new PosedBoundsCallback(this)); geode->addDrawable(geom); geometries_.push_back(geom); } meshGroup_ = geode; addChild(meshGroup_); } void ModelNode::buildSkinning() { const Model& model = *model_; const size_t boneCount = model.bones.size(); osg::StateSet* ss = getOrCreateStateSet(); skinningUniform_ = new osg::Uniform("u_skinning", 0); ss->addUniform(skinningUniform_); osg::ref_ptr indices = new osg::Vec4Array(model.vertices.size()); osg::ref_ptr weights = new osg::Vec4Array(model.vertices.size()); for (size_t i = 0; i < model.vertices.size(); ++i) { const Vertex& v = model.vertices[i]; for (int k = 0; k < 4; ++k) { const bool used = v.bones[k] >= 0 && v.weights[k] > 0.f; (*indices)[i][k] = used ? float(v.bones[k]) : 0.f; (*weights)[i][k] = used ? v.weights[k] : 0.f; } } for (auto& g : geometries_) { g->setVertexAttribArray(kBoneIndexAttrib, indices, osg::Array::BIND_PER_VERTEX); g->setVertexAttribArray(kBoneWeightAttrib, weights, osg::Array::BIND_PER_VERTEX); } boneRestPositions_.resize(boneCount); for (size_t b = 0; b < boneCount; ++b) boneRestPositions_[b] = osg::Matrixf::inverse(model.bones[b].inverseBind).getTrans(); float morphReach = 0.f; for (const auto& m : model.morphs) for (const auto& o : m.vertexOffsets) morphReach = std::max(morphReach, o.offset.length()); for (const auto& v : model.vertices) { if (v.bones[0] < 0) { unskinnedBounds_.expandBy(v.position); continue; } int main = 0; for (int k = 1; k < 4; ++k) if (v.bones[k] >= 0 && v.weights[k] > v.weights[main]) main = k; boneReach_ = std::max(boneReach_, (v.position - boneRestPositions_[v.bones[main]]).length()); } boneReach_ += morphReach; if (unskinnedBounds_.valid()) { const osg::Vec3f pad(morphReach, morphReach, morphReach); unskinnedBounds_.expandBy(unskinnedBounds_._max + pad); unskinnedBounds_.expandBy(unskinnedBounds_._min - pad); } if (boneCount == 0) return; const int columns = static_cast(std::min(boneCount, kBonesPerTextureRow)); const int rows = static_cast((boneCount + kBonesPerTextureRow - 1) / kBonesPerTextureRow); boneImage_ = new osg::Image; boneImage_->allocateImage(columns * 3, rows, 1, GL_RGBA, GL_FLOAT); boneImage_->setInternalTextureFormat(GL_RGBA32F_ARB); std::fill(reinterpret_cast(boneImage_->data()), reinterpret_cast(boneImage_->data()) + columns * 3 * rows * 4, 0.f); boneImage_->setDataVariance(osg::Object::DYNAMIC); boneTexture_ = new osg::Texture2D(boneImage_); boneTexture_->setDataVariance(osg::Object::DYNAMIC); boneTexture_->setResizeNonPowerOfTwoHint(false); boneTexture_->setUseHardwareMipMapGeneration(false); boneTexture_->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST); boneTexture_->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST); boneTexture_->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE); boneTexture_->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE); ss->setTextureAttribute(kBoneTextureUnit, boneTexture_); ss->addUniform(new osg::Uniform("u_boneTexture", static_cast(kBoneTextureUnit))); ss->addUniform(new osg::Uniform("u_boneTexSize", osg::Vec2f(float(columns * 3), float(rows)))); } void ModelNode::uploadBoneMatrices() { const auto& skin = poser_.skinMatrices(); const auto& bones = model_->bones; float* data = reinterpret_cast(boneImage_->data()); const int width = boneImage_->s(); posedBounds_ = unskinnedBounds_; const osg::Vec3f reach(boneReach_, boneReach_, boneReach_); for (size_t b = 0; b < skin.size(); ++b) { const osg::Matrixf& m = skin[b]; float* texel = data + ((b / kBonesPerTextureRow) * width + (b % kBonesPerTextureRow) * 3) * 4; for (int k = 0; k < 3; ++k) for (int r = 0; r < 4; ++r) texel[k * 4 + r] = m(r, k); if (bones[b].isSkinBone) { const osg::Vec3f p = boneRestPositions_[b] * m; posedBounds_.expandBy(p - reach); posedBounds_.expandBy(p + reach); } } boneImage_->dirty(); } void ModelNode::setSkinningMode(SkinningMode mode) { requestedSkinning_ = mode; } void ModelNode::buildSkeleton() { const Model& model = *model_; for (size_t i = 0; i < model.bones.size(); ++i) if (model.bones[i].visible || model.bones[i].isSkinBone) skeletonBones_.push_back(static_cast(i)); skeletonGeode_ = new osg::Geode; osg::StateSet* ss = skeletonGeode_->getOrCreateStateSet(); ss->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON); // fixed function ss->setMode(GL_LIGHTING, osg::StateAttribute::OFF); ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF); ss->setMode(GL_BLEND, osg::StateAttribute::OFF); ss->setAttributeAndModes(new osg::PolygonMode(), osg::StateAttribute::ON | osg::StateAttribute::PROTECTED); ss->setAttribute(new osg::LineWidth(2.f)); ss->setAttribute(new osg::Point(6.f)); ss->setRenderBinDetails(100000, "RenderBin"); auto makeGeom = [](GLenum mode) { osg::ref_ptr g = new osg::Geometry; g->setDataVariance(osg::Object::DYNAMIC); g->setUseDisplayList(false); g->setUseVertexBufferObjects(true); g->setVertexArray(new osg::Vec3Array); g->setColorArray(new osg::Vec4Array, osg::Array::BIND_PER_VERTEX); g->addPrimitiveSet(new osg::DrawArrays(mode, 0, 0)); return g; }; skeletonLines_ = makeGeom(GL_LINES); skeletonPoints_ = makeGeom(GL_POINTS); skeletonGeode_->addDrawable(skeletonLines_); skeletonGeode_->addDrawable(skeletonPoints_); addChild(skeletonGeode_); } void ModelNode::updateSkeleton() { const auto& globals = poser_.boneGlobals(); const auto& bones = model_->bones; auto* lineVerts = static_cast(skeletonLines_->getVertexArray()); auto* lineColors = static_cast(skeletonLines_->getColorArray()); auto* pointVerts = static_cast(skeletonPoints_->getVertexArray()); auto* pointColors = static_cast(skeletonPoints_->getColorArray()); lineVerts->clear(); lineColors->clear(); pointVerts->clear(); pointColors->clear(); const osg::Vec4 normal(0.3f, 0.8f, 1.f, 1.f), selected(1.f, 0.85f, 0.1f, 1.f); for (int b : skeletonBones_) { const osg::Vec4& color = b == selectedBone_ ? selected : normal; osg::Vec3 head = globals[b].getTrans(); pointVerts->push_back(head); pointColors->push_back(color); int parent = bones[b].parent; if (parent >= 0) { lineVerts->push_back(globals[parent].getTrans()); lineVerts->push_back(head); lineColors->push_back(color); lineColors->push_back(color); } } static_cast(skeletonLines_->getPrimitiveSet(0))->setCount(lineVerts->size()); static_cast(skeletonPoints_->getPrimitiveSet(0))->setCount(pointVerts->size()); for (osg::Array* a : {static_cast(lineVerts), static_cast(lineColors), static_cast(pointVerts), static_cast(pointColors)}) a->dirty(); skeletonLines_->dirtyBound(); skeletonPoints_->dirtyBound(); } void ModelNode::updateDeformation() { const bool hardware = requestedSkinning_ == SkinningMode::Hardware && gpuCaps().skinning && boneImage_.valid(); const SkinningMode wanted = hardware ? SkinningMode::Hardware : SkinningMode::Software; if (wanted != activeSkinning_) { activeSkinning_ = wanted; poser_.setSkinningMode(wanted); skinningUniform_->set(hardware ? 1 : 0); if (hardware) { for (size_t i = 0; i < model_->vertices.size(); ++i) (*normals_)[i] = model_->vertices[i].normal; normals_->dirty(); } } if (poser_.update()) { if (activeSkinning_ == SkinningMode::Software) { const auto& p = poser_.positions(); const auto& n = poser_.normals(); std::copy(p.begin(), p.end(), positions_->begin()); std::copy(n.begin(), n.end(), normals_->begin()); positions_->dirty(); normals_->dirty(); } else { uploadBoneMatrices(); if (poser_.morphsChangedInLastUpdate()) { const auto& p = poser_.morphedPositions(); std::copy(p.begin(), p.end(), positions_->begin()); positions_->dirty(); } } for (auto& g : geometries_) g->dirtyBound(); skeletonDirty_ = true; } if (skeletonDirty_ && skeletonGeode_->getNodeMask() != 0) { updateSkeleton(); skeletonDirty_ = false; } } void ModelNode::setShowSkeleton(bool show) { skeletonGeode_->setNodeMask(show ? ~0u : 0u); skeletonDirty_ = true; } void ModelNode::setSelectedBone(int bone) { if (bone == selectedBone_) return; selectedBone_ = bone; skeletonDirty_ = true; } void ModelNode::setBackfaceCulling(bool enabled) { osg::StateSet* ss = meshGroup_->getOrCreateStateSet(); if (enabled) ss->removeMode(GL_CULL_FACE); else ss->setMode(GL_CULL_FACE, osg::StateAttribute::OFF | osg::StateAttribute::OVERRIDE); } void ModelNode::setWireframe(bool enabled) { osg::StateSet* ss = meshGroup_->getOrCreateStateSet(); if (enabled) ss->setAttributeAndModes(new osg::PolygonMode(osg::PolygonMode::FRONT_AND_BACK, osg::PolygonMode::LINE), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); else ss->removeAttribute(osg::StateAttribute::POLYGONMODE); } void ModelNode::setLightingModel(LightingModel lighting) { lightingUniform_->set(static_cast(lighting)); } void ModelNode::setLightFollowsCamera(bool follow) { lightFollowUniform_->set(follow ? 1 : 0); // In view space a light from the upper left, slightly in front of the camera. osg::Vec3f dir = follow ? osg::Vec3f(0.3f, -0.5f, -1.f) : osg::Matrixf::transform3x3(kMmdLightDirection, osg::Matrixf(getMatrix())); lightDirUniform_->set(dir); } osg::BoundingSphere ModelNode::restBound() const { osg::Vec3f lo, hi; model_->computeBounds(lo, hi); osg::BoundingBox box(lo, hi); osg::BoundingSphere sphere(box); sphere.center() = sphere.center() * getMatrix(); return sphere; } } // namespace mr