]> git.localhorst.tv Git - blank.git/blobdiff - src/model/model.cpp
save a little bandwidth
[blank.git] / src / model / model.cpp
index 4e000806cff56c2812f9aaa42fc459c642cc29ca..ed443138e23e0d5746a551c25fd7e1f6956cf198 100644 (file)
-#include "BlockModel.hpp"
 #include "Model.hpp"
-#include "OutlineModel.hpp"
-#include "SpriteModel.hpp"
+#include "ModelRegistry.hpp"
+#include "Instance.hpp"
+#include "Part.hpp"
+
+#include "Shape.hpp"
+#include "ShapeRegistry.hpp"
+#include "../io/TokenStreamReader.hpp"
+#include "../graphics/DirectionalLighting.hpp"
+#include "../graphics/EntityMesh.hpp"
+#include "../shared/ResourceIndex.hpp"
 
 #include <iostream>
+#include <glm/gtx/quaternion.hpp>
+#include <glm/gtx/io.hpp>
 
 
 namespace blank {
 
-Model::Model() noexcept
-: va(0)
-, handle{}
-, count(0) {
-       glGenVertexArrays(1, &va);
-       glGenBuffers(ATTRIB_COUNT, handle);
-}
+Instance::Instance()
+: model(nullptr)
+, state() {
 
-Model::~Model() noexcept {
-       glDeleteBuffers(ATTRIB_COUNT, handle);
-       glDeleteVertexArrays(1, &va);
 }
 
-Model::Model(Model &&other) noexcept
-: va(other.va)
-, count(other.count) {
-       other.va = 0;
-       for (int i = 0; i < ATTRIB_COUNT; ++i) {
-               handle[i] = other.handle[i];
-               other.handle[i] = 0;
-       }
-}
+Instance::~Instance() {
 
-Model &Model::operator =(Model &&other) noexcept {
-       std::swap(va, other.va);
-       for (int i = 0; i < ATTRIB_COUNT; ++i) {
-               std::swap(handle[i], other.handle[i]);
-       }
-       count = other.count;
-       return *this;
-}
-
-void Model::Update(const Buffer &buf) noexcept {
-       glBindVertexArray(va);
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_VERTEX]);
-       glBufferData(GL_ARRAY_BUFFER, buf.vertices.size() * sizeof(glm::vec3), buf.vertices.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_VERTEX);
-       glVertexAttribPointer(
-               ATTRIB_VERTEX, // location (for shader)
-               3,             // size
-               GL_FLOAT,      // type
-               GL_FALSE,      // normalized
-               0,             // stride
-               nullptr        // offset
-       );
-
-#ifndef NDEBUG
-       if (buf.colors.size() < buf.vertices.size()) {
-               std::cerr << "Model: not enough colors!" << std::endl;
-       }
-#endif
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_COLOR]);
-       glBufferData(GL_ARRAY_BUFFER, buf.colors.size() * sizeof(glm::vec3), buf.colors.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_COLOR);
-       glVertexAttribPointer(
-               ATTRIB_COLOR,  // location (for shader)
-               3,             // size
-               GL_FLOAT,      // type
-               GL_FALSE,      // normalized
-               0,             // stride
-               nullptr        // offset
-       );
-
-#ifndef NDEBUG
-       if (buf.normals.size() < buf.vertices.size()) {
-               std::cerr << "Model: not enough normals!" << std::endl;
-       }
-#endif
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_NORMAL]);
-       glBufferData(GL_ARRAY_BUFFER, buf.normals.size() * sizeof(glm::vec3), buf.normals.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_NORMAL);
-       glVertexAttribPointer(
-               ATTRIB_NORMAL, // location (for shader)
-               3,             // size
-               GL_FLOAT,      // type
-               GL_FALSE,      // normalized
-               0,             // stride
-               nullptr        // offset
-       );
-
-       glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle[ATTRIB_INDEX]);
-       glBufferData(GL_ELEMENT_ARRAY_BUFFER, buf.indices.size() * sizeof(Index), buf.indices.data(), GL_STATIC_DRAW);
-       count = buf.indices.size();
 }
 
-
-void Model::Draw() const noexcept {
-       glBindVertexArray(va);
-       glDrawElements(
-               GL_TRIANGLES,    // how
-               count,           // count
-               GL_UNSIGNED_INT, // type
-               nullptr          // offset
-       );
+Part::State &Instance::BodyState() noexcept {
+       return state[model->GetBodyPart().ID()];
 }
 
-
-BlockModel::BlockModel() noexcept
-: va(0)
-, handle{}
-, count(0) {
-       glGenVertexArrays(1, &va);
-       glGenBuffers(ATTRIB_COUNT, handle);
+glm::mat4 Instance::BodyTransform() const noexcept {
+       return model->GetBodyPart().GlobalTransform(*this);
 }
 
-BlockModel::~BlockModel() noexcept {
-       glDeleteBuffers(ATTRIB_COUNT, handle);
-       glDeleteVertexArrays(1, &va);
+Part::State &Instance::EyesState() noexcept {
+       return state[model->GetEyesPart().ID()];
 }
 
-BlockModel::BlockModel(BlockModel &&other) noexcept
-: va(other.va)
-, count(other.count) {
-       other.va = 0;
-       for (int i = 0; i < ATTRIB_COUNT; ++i) {
-               handle[i] = other.handle[i];
-               other.handle[i] = 0;
-       }
+glm::mat4 Instance::EyesTransform() const noexcept {
+       return model->GetEyesPart().GlobalTransform(*this);
 }
 
-BlockModel &BlockModel::operator =(BlockModel &&other) noexcept {
-       std::swap(va, other.va);
-       for (int i = 0; i < ATTRIB_COUNT; ++i) {
-               std::swap(handle[i], other.handle[i]);
-       }
-       count = other.count;
-       return *this;
+void Instance::Render(const glm::mat4 &M, DirectionalLighting &prog) {
+       model->RootPart().Render(M, *this, prog);
 }
 
-void BlockModel::Update(const Buffer &buf) noexcept {
-       glBindVertexArray(va);
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_VERTEX]);
-       glBufferData(GL_ARRAY_BUFFER, buf.vertices.size() * sizeof(glm::vec3), buf.vertices.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_VERTEX);
-       glVertexAttribPointer(
-               ATTRIB_VERTEX, // location (for shader)
-               3,             // size
-               GL_FLOAT,      // type
-               GL_FALSE,      // normalized
-               0,             // stride
-               nullptr        // offset
-       );
-
-#ifndef NDEBUG
-       if (buf.colors.size() < buf.vertices.size()) {
-               std::cerr << "BlockModel: not enough colors!" << std::endl;
-       }
-#endif
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_COLOR]);
-       glBufferData(GL_ARRAY_BUFFER, buf.colors.size() * sizeof(glm::vec3), buf.colors.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_COLOR);
-       glVertexAttribPointer(
-               ATTRIB_COLOR,  // location (for shader)
-               3,             // size
-               GL_FLOAT,      // type
-               GL_FALSE,      // normalized
-               0,             // stride
-               nullptr        // offset
-       );
-
-#ifndef NDEBUG
-       if (buf.lights.size() < buf.vertices.size()) {
-               std::cerr << "BlockModel: not enough lights!" << std::endl;
-       }
-#endif
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_LIGHT]);
-       glBufferData(GL_ARRAY_BUFFER, buf.lights.size() * sizeof(float), buf.lights.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_LIGHT);
-       glVertexAttribPointer(
-               ATTRIB_LIGHT, // location (for shader)
-               1,            // size
-               GL_FLOAT,     // type
-               GL_FALSE,     // normalized
-               0,            // stride
-               nullptr       // offset
-       );
-
-       glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle[ATTRIB_INDEX]);
-       glBufferData(GL_ELEMENT_ARRAY_BUFFER, buf.indices.size() * sizeof(Index), buf.indices.data(), GL_STATIC_DRAW);
-       count = buf.indices.size();
-}
 
+Model::Model()
+: id(0)
+, root()
+, part()
+, body_id(0)
+, eyes_id(0) {
 
-void BlockModel::Draw() const noexcept {
-       glBindVertexArray(va);
-       glDrawElements(
-               GL_TRIANGLES,    // how
-               count,           // count
-               GL_UNSIGNED_INT, // type
-               nullptr          // offset
-       );
 }
 
-OutlineModel::OutlineModel() noexcept
-: vertices()
-, colors()
-, indices()
-, va(0)
-, handle{}
-, dirty(false) {
-       glGenVertexArrays(1, &va);
-       glGenBuffers(ATTRIB_COUNT, handle);
+void Model::Enumerate() {
+       part.clear();
+       part.resize(root.Enumerate(0), nullptr);
+       root.Index(part);
 }
 
-OutlineModel::~OutlineModel() noexcept {
-       glDeleteBuffers(ATTRIB_COUNT, handle);
-       glDeleteVertexArrays(1, &va);
+void Model::Instantiate(Instance &inst) const {
+       inst.model = this;
+       inst.state.clear();
+       inst.state.resize(part.size());
 }
 
 
-void OutlineModel::Clear() noexcept {
-       vertices.clear();
-       colors.clear();
-       indices.clear();
-       Invalidate();
-}
+ModelRegistry::ModelRegistry()
+: models()
+, name_index() {
 
-void OutlineModel::Reserve(int v, int i) {
-       vertices.reserve(v);
-       colors.reserve(v);
-       indices.reserve(i);
 }
 
+Model &ModelRegistry::Add(const std::string &name) {
+       models.emplace_back(new Model());
+       models.back()->ID(models.size());
+       name_index[name] = &*models.back();
+       return *models.back();
+}
 
-void OutlineModel::Update() noexcept {
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_VERTEX]);
-       glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), vertices.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_VERTEX);
-       glVertexAttribPointer(
-               ATTRIB_VERTEX, // location (for shader)
-               3,             // size
-               GL_FLOAT,      // type
-               GL_FALSE,      // normalized
-               0,             // stride
-               nullptr        // offset
-       );
-
-#ifndef NDEBUG
-       if (colors.size() < vertices.size()) {
-               std::cerr << "OutlineModel: not enough colors!" << std::endl;
-               colors.resize(vertices.size(), { 1, 0, 1 });
+Model &ModelRegistry::Get(const std::string &name) {
+       auto entry = name_index.find(name);
+       if (entry != name_index.end()) {
+               return *entry->second;
+       } else {
+               throw std::runtime_error("unknown model " + name);
        }
-#endif
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_COLOR]);
-       glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(glm::vec3), colors.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_COLOR);
-       glVertexAttribPointer(
-               ATTRIB_COLOR,  // location (for shader)
-               3,             // size
-               GL_FLOAT,      // type
-               GL_FALSE,      // normalized
-               0,             // stride
-               nullptr        // offset
-       );
-
-       glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle[ATTRIB_INDEX]);
-       glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(Index), indices.data(), GL_STATIC_DRAW);
-
-       dirty = false;
 }
 
-
-void OutlineModel::Draw() noexcept {
-       glBindVertexArray(va);
-
-       if (dirty) {
-               Update();
+const Model &ModelRegistry::Get(const std::string &name) const {
+       auto entry = name_index.find(name);
+       if (entry != name_index.end()) {
+               return *entry->second;
+       } else {
+               throw std::runtime_error("unknown model " + name);
        }
-
-       glEnable(GL_LINE_SMOOTH);
-       glLineWidth(2.0f);
-
-       glDrawElements(
-               GL_LINES,          // how
-               indices.size(),    // count
-               GL_UNSIGNED_SHORT, // type
-               nullptr            // offset
-       );
 }
 
 
-SpriteModel::SpriteModel() noexcept
-: vertices()
-, coords()
-, indices()
-, va(0)
-, handle{}
-, dirty(false) {
-       glGenVertexArrays(1, &va);
-       glGenBuffers(ATTRIB_COUNT, handle);
+Part::Part()
+: parent(nullptr)
+, shape(nullptr)
+, children()
+, tex_map()
+, mesh()
+, initial()
+, hsl_mod(0, 255, 255)
+, rgb_mod(255, 255, 255)
+, id(0) {
+
+}
+
+Part::~Part() {
+
+}
+
+void Part::Read(TokenStreamReader &in, ResourceIndex &tex_index, const ShapeRegistry &shapes) {
+       std::string name;
+       std::string shape_name;
+       std::string tex_name;
+       glm::vec3 color_conv;
+       in.Skip(Token::ANGLE_BRACKET_OPEN);
+       while (in.HasMore() && in.Peek().type != Token::ANGLE_BRACKET_CLOSE) {
+               in.ReadIdentifier(name);
+               in.Skip(Token::EQUALS);
+               if (name == "shape") {
+                       in.ReadIdentifier(shape_name);
+                       shape = &shapes.Get(shape_name);
+               } else if (name == "position") {
+                       in.ReadVec(initial.position);
+               } else if (name == "orientation") {
+                       in.ReadQuat(initial.orientation);
+               } else if (name == "hsl_mod") {
+                       in.ReadVec(color_conv);
+                       hsl_mod = glm::tvec3<unsigned char>(color_conv * 255.0f);
+               } else if (name == "rgb_mod") {
+                       in.ReadVec(color_conv);
+                       rgb_mod = glm::tvec3<unsigned char>(color_conv * 255.0f);
+               } else if (name == "textures") {
+                       in.Skip(Token::BRACKET_OPEN);
+                       while (in.HasMore() && in.Peek().type != Token::BRACKET_CLOSE) {
+                               in.ReadString(tex_name);
+                               tex_map.push_back(tex_index.GetID(tex_name));
+                               if (in.Peek().type == Token::COMMA) {
+                                       in.Skip(Token::COMMA);
+                               }
+                       }
+                       in.Skip(Token::BRACKET_CLOSE);
+               } else if (name == "children") {
+                       in.Skip(Token::BRACKET_OPEN);
+                       while (in.HasMore() && in.Peek().type != Token::BRACKET_CLOSE) {
+                               Part &child = AddChild();
+                               child.Read(in, tex_index, shapes);
+                               if (in.Peek().type == Token::COMMA) {
+                                       in.Skip(Token::COMMA);
+                               }
+                       }
+                       in.Skip(Token::BRACKET_CLOSE);
+               } else {
+                       while (in.HasMore() && in.Peek().type != Token::SEMICOLON) {
+                               in.Next();
+                       }
+               }
+               in.Skip(Token::SEMICOLON);
+       }
+       in.Skip(Token::ANGLE_BRACKET_CLOSE);
 }
 
-SpriteModel::~SpriteModel() noexcept {
-       glDeleteBuffers(ATTRIB_COUNT, handle);
-       glDeleteVertexArrays(1, &va);
+Part &Part::AddChild() {
+       children.emplace_back();
+       children.back().parent = this;
+       return children.back();
 }
 
-
-void SpriteModel::Clear() noexcept {
-       vertices.clear();
-       coords.clear();
-       indices.clear();
-       Invalidate();
+std::uint16_t Part::Enumerate(std::uint16_t counter) noexcept {
+       id = counter++;
+       for (Part &part : children) {
+               counter = part.Enumerate(counter);
+       }
+       return counter;
 }
 
-void SpriteModel::Reserve(int v, int i) {
-       vertices.reserve(v);
-       coords.reserve(v);
-       indices.reserve(i);
+void Part::Index(std::vector<Part *> &index) noexcept {
+       index[id] = this;
+       for (Part &part : children) {
+               part.Index(index);
+       }
 }
 
-
-void SpriteModel::LoadRect(
-       float w, float h,
-       const glm::vec2 &pivot,
-       const glm::vec2 &tex_begin,
-       const glm::vec2 &tex_end
-) {
-       Clear();
-       Reserve(4, 6);
-
-       vertices.emplace_back( -pivot.x,  -pivot.y, 0.0f);
-       vertices.emplace_back(w-pivot.x,  -pivot.y, 0.0f);
-       vertices.emplace_back( -pivot.x, h-pivot.y, 0.0f);
-       vertices.emplace_back(w-pivot.x, h-pivot.y, 0.0f);
-
-       coords.emplace_back(tex_begin.x, tex_begin.y);
-       coords.emplace_back(tex_end.x,   tex_begin.y);
-       coords.emplace_back(tex_begin.x, tex_end.y);
-       coords.emplace_back(tex_end.x,   tex_end.y);
-
-       indices.assign({ 0, 2, 1, 1, 2, 3 });
-
-       Invalidate();
+glm::mat4 Part::LocalTransform(const Instance &inst) const noexcept {
+       glm::mat4 transform(toMat4(initial.orientation * inst.state[id].orientation));
+       transform[3] = glm::vec4(initial.position + inst.state[id].position, 1.0f);
+       return transform;
 }
 
-
-void SpriteModel::Update() noexcept {
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_VERTEX]);
-       glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Position), vertices.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_VERTEX);
-       glVertexAttribPointer(
-               ATTRIB_VERTEX, // location (for shader)
-               3,             // size
-               GL_FLOAT,      // type
-               GL_FALSE,      // normalized
-               0,             // stride
-               nullptr        // offset
-       );
-
-#ifndef NDEBUG
-       if (coords.size() < vertices.size()) {
-               std::cerr << "SpriteModel: not enough coords!" << std::endl;
-               coords.resize(vertices.size(), { 1, 1 });
+glm::mat4 Part::GlobalTransform(const Instance &inst) const noexcept {
+       if (parent) {
+               return parent->GlobalTransform(inst) * LocalTransform(inst);
+       } else {
+               return LocalTransform(inst);
        }
-#endif
-       glBindBuffer(GL_ARRAY_BUFFER, handle[ATTRIB_TEXCOORD]);
-       glBufferData(GL_ARRAY_BUFFER, coords.size() * sizeof(TexCoord), coords.data(), GL_STATIC_DRAW);
-       glEnableVertexAttribArray(ATTRIB_TEXCOORD);
-       glVertexAttribPointer(
-               ATTRIB_TEXCOORD, // location (for shader)
-               2,               // size
-               GL_FLOAT,        // type
-               GL_FALSE,        // normalized
-               0,               // stride
-               nullptr          // offset
-       );
-
-       glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle[ATTRIB_INDEX]);
-       glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(Index), indices.data(), GL_STATIC_DRAW);
-
-       dirty = false;
 }
 
+namespace {
 
-void SpriteModel::Draw() noexcept {
-       glBindVertexArray(va);
+EntityMesh::Buffer buf;
 
-       if (dirty) {
-               Update();
-       }
+}
 
-       glDrawElements(
-               GL_TRIANGLES,      // how
-               indices.size(),    // count
-               GL_UNSIGNED_SHORT, // type
-               nullptr            // offset
-       );
+void Part::Render(
+       const glm::mat4 &M,
+       const Instance &inst,
+       DirectionalLighting &prog
+) const {
+       glm::mat4 transform = M * LocalTransform(inst);
+       if (shape && shape->IndexCount() > 0) {
+               if (!mesh) {
+                       buf.Clear();
+                       buf.hsl_mods.resize(shape->VertexCount(), hsl_mod);
+                       buf.rgb_mods.resize(shape->VertexCount(), rgb_mod);
+                       shape->Fill(buf, tex_map);
+                       mesh.reset(new EntityMesh());
+                       mesh->Update(buf);
+               }
+               prog.SetM(transform);
+               mesh->Draw();
+       }
+       for (const Part &part : children) {
+               part.Render(transform, inst, prog);
+       }
 }
 
 }