From 55c8a14a7e2b2dadf0def3e09f970818164366f5 Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Thu, 18 Jun 2015 12:14:05 -0400 Subject: Now displaying player character --- src/components/transformable.h | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/components/transformable.h (limited to 'src/components/transformable.h') diff --git a/src/components/transformable.h b/src/components/transformable.h new file mode 100644 index 0000000..87ba84d --- /dev/null +++ b/src/components/transformable.h @@ -0,0 +1,27 @@ +#ifndef LOCATABLE_H_39E526CA +#define LOCATABLE_H_39E526CA + +#include "component.h" + +class TransformableComponent : public Component { + public: + TransformableComponent(double x, double y, int w, int h); + + double getX() const; + double getY() const; + int getW() const; + int getH() const; + + void setX(double v); + void setY(double v); + void setW(int v); + void setH(int v); + + private: + double x; + double y; + int w; + int h; +}; + +#endif /* end of include guard: LOCATABLE_H_39E526CA */ -- cgit 1.4.1 From da3df061699203eccc9a0c98becaee3ce8050a4f Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Mon, 5 Feb 2018 11:51:24 -0500 Subject: Whitespace changes --- src/components/controllable.h | 6 +- src/components/droppable.h | 2 +- src/components/ponderable.h | 2 +- src/components/transformable.cpp | 2 +- src/components/transformable.h | 6 +- src/entity_manager.cpp | 8 +- src/entity_manager.h | 64 +++++------ src/game.cpp | 10 +- src/game.h | 6 +- src/main.cpp | 10 +- src/renderer.cpp | 228 +++++++++++++++++++-------------------- src/renderer.h | 2 +- src/system.h | 4 +- src/system_manager.h | 8 +- src/systems/controlling.cpp | 12 +-- src/systems/controlling.h | 6 +- src/systems/pondering.cpp | 6 +- src/systems/pondering.h | 2 +- src/systems/rendering.h | 4 +- 19 files changed, 194 insertions(+), 194 deletions(-) (limited to 'src/components/transformable.h') diff --git a/src/components/controllable.h b/src/components/controllable.h index 317d68d..baccf13 100644 --- a/src/components/controllable.h +++ b/src/components/controllable.h @@ -14,20 +14,20 @@ class ControllableComponent : public Component { void setJumpKey(int k); int getDropKey() const; void setDropKey(int k); - + bool isFrozen() const; void setFrozen(bool f); bool isHoldingLeft() const; void setHoldingLeft(bool f); bool isHoldingRight() const; void setHoldingRight(bool f); - + private: int leftKey = GLFW_KEY_LEFT; int rightKey = GLFW_KEY_RIGHT; int jumpKey = GLFW_KEY_UP; int dropKey = GLFW_KEY_DOWN; - + bool frozen = false; bool holdingLeft = false; bool holdingRight = false; diff --git a/src/components/droppable.h b/src/components/droppable.h index 1f5608b..83fcb9d 100644 --- a/src/components/droppable.h +++ b/src/components/droppable.h @@ -7,7 +7,7 @@ class DroppableComponent : public Component { public: void setDroppable(bool can); bool isDroppable() const; - + private: bool droppable = false; }; diff --git a/src/components/ponderable.h b/src/components/ponderable.h index 5aab4b3..c836d2a 100644 --- a/src/components/ponderable.h +++ b/src/components/ponderable.h @@ -13,7 +13,7 @@ class PonderableComponent : public Component { void setAccelX(double v); double getAccelY() const; void setAccelY(double v); - + private: double velocityX = 0.0; double velocityY = 0.0; diff --git a/src/components/transformable.cpp b/src/components/transformable.cpp index 0d6b67e..89b1e5d 100644 --- a/src/components/transformable.cpp +++ b/src/components/transformable.cpp @@ -3,7 +3,7 @@ TransformableComponent::TransformableComponent(double x, double y, int w, int h) : x(x), y(y), w(w), h(h) { - + } double TransformableComponent::getX() const diff --git a/src/components/transformable.h b/src/components/transformable.h index 87ba84d..69f4f0e 100644 --- a/src/components/transformable.h +++ b/src/components/transformable.h @@ -6,17 +6,17 @@ class TransformableComponent : public Component { public: TransformableComponent(double x, double y, int w, int h); - + double getX() const; double getY() const; int getW() const; int getH() const; - + void setX(double v); void setY(double v); void setW(int v); void setH(int v); - + private: double x; double y; diff --git a/src/entity_manager.cpp b/src/entity_manager.cpp index 4bdfe8a..9ad758b 100644 --- a/src/entity_manager.cpp +++ b/src/entity_manager.cpp @@ -10,13 +10,13 @@ std::set EntityManager::getEntitiesWithComponents<>(std::set& cache = cachedComponents[componentTypes]; for (auto& entity : entities) { EntityData& data = entity.second; bool cacheEntity = true; - + for (auto& componentType : componentTypes) { if (data.components.count(componentType) == 0) @@ -25,13 +25,13 @@ std::set EntityManager::getEntitiesWithComponents<>(std::set> components; }; - + std::map entities; std::map, std::set> cachedComponents; - + int nextEntityID = 0; - + template std::set getEntitiesWithComponentsHelper(std::set& componentTypes) { componentTypes.insert(typeid(T)); - + return getEntitiesWithComponents(componentTypes); } - + template std::set getEntitiesWithComponents(std::set& componentTypes) { return getEntitiesWithComponentsHelper(componentTypes); } - + public: EntityManager() = default; EntityManager(const EntityManager& copy) = delete; - + int emplaceEntity() { // Find a suitable entity ID @@ -44,76 +44,76 @@ class EntityManager { { nextEntityID++; } - + if (nextEntityID < 0) { nextEntityID = 0; - + while ((entities.count(nextEntityID) == 1) && (nextEntityID >= 0)) { nextEntityID++; } - + assert(nextEntityID >= 0); } - + // Initialize the data int id = nextEntityID++; entities[id]; - + return id; } - + void deleteEntity(int entity) { assert(entities.count(entity) == 1); - + // Uncache components for (auto& cache : cachedComponents) { cache.second.erase(entity); } - + // Destroy the data entities.erase(entity); } - + template T& emplaceComponent(int entity, Args&&... args) { assert(entities.count(entity) == 1); - + EntityData& data = entities[entity]; std::type_index componentType = typeid(T); - + assert(data.components.count(componentType) == 0); - + // Initialize the component std::unique_ptr ptr = std::unique_ptr(new T(std::forward(args)...)); T& component = *ptr; data.components[componentType] = std::move(ptr); - + // Invalidate related caches erase_if(cachedComponents, [&componentType] (std::pair, std::set>& cache) { return cache.first.count(componentType) == 1; }); - + return component; } - + template void removeComponent(int entity) { assert(entities.count(entity) == 1); - + EntityData& data = entities[entity]; std::type_index componentType = typeid(T); - + assert(data.components.count(componentType) == 1); - + // Destroy the component data.components.erase(componentType); - + // Uncache the component for (auto& cache : cachedComponents) { @@ -123,25 +123,25 @@ class EntityManager { } } } - + template T& getComponent(int entity) { assert(entities.count(entity) == 1); - + EntityData& data = entities[entity]; std::type_index componentType = typeid(T); - + assert(data.components.count(componentType) == 1); - + return *((T*)data.components[componentType].get()); } - + template std::set getEntitiesWithComponents() { std::set componentTypes; - + return getEntitiesWithComponentsHelper(componentTypes); } }; diff --git a/src/game.cpp b/src/game.cpp index b3fa9a8..5d1ec18 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -45,24 +45,24 @@ void Game::execute() double lastTime = glfwGetTime(); const double dt = 0.01; double accumulator = 0.0; - + while (!(shouldQuit || glfwWindowShouldClose(window))) { double currentTime = glfwGetTime(); double frameTime = currentTime - lastTime; lastTime = currentTime; - + glfwPollEvents(); - + accumulator += frameTime; while (accumulator >= dt) { systemManager.getSystem().tick(dt); systemManager.getSystem().tick(dt); - + accumulator -= dt; } - + systemManager.getSystem().tick(frameTime); } } diff --git a/src/game.h b/src/game.h index 3822700..ec667c8 100644 --- a/src/game.h +++ b/src/game.h @@ -8,12 +8,12 @@ class Game { public: Game(GLFWwindow* window); - + void execute(); EntityManager& getEntityManager(); - + friend void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); - + private: EntityManager entityManager; SystemManager systemManager; diff --git a/src/main.cpp b/src/main.cpp index 35749f5..d51da7d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -8,20 +8,20 @@ int main() { srand(time(NULL)); - + GLFWwindow* window = initRenderer(); glfwSwapInterval(1); - + initMuxer(); - + // Put this in a block so game goes out of scope before we destroy the renderer { Game game {window}; game.execute(); } - + destroyMuxer(); destroyRenderer(); - + return 0; } diff --git a/src/renderer.cpp b/src/renderer.cpp index 99d5389..d0d2b75 100644 --- a/src/renderer.cpp +++ b/src/renderer.cpp @@ -56,11 +56,11 @@ static GLuint mesh_normalbuffer; static int mesh_numvertices; GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) -{ +{ // Create the shaders GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); - + // Read the Vertex Shader code from the file std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); @@ -71,7 +71,7 @@ GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) VertexShaderCode += "\n" + Line; VertexShaderStream.close(); } - + // Read the Fragment Shader code from the file std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); @@ -81,53 +81,53 @@ GLuint LoadShaders(const char* vertex_file_path, const char* fragment_file_path) FragmentShaderCode += "\n" + Line; FragmentShaderStream.close(); } - + GLint Result = GL_FALSE; int InfoLogLength; - + // Compile Vertex Shader printf("Compiling shader : %s\n", vertex_file_path); char const * VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer , nullptr); glCompileShader(VertexShaderID); - + // Check Vertex Shader glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector VertexShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(VertexShaderID, InfoLogLength, nullptr, &VertexShaderErrorMessage[0]); fprintf(stdout, "%s\n", &VertexShaderErrorMessage[0]); - + // Compile Fragment Shader printf("Compiling shader : %s\n", fragment_file_path); char const * FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer , nullptr); glCompileShader(FragmentShaderID); - + // Check Fragment Shader glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector FragmentShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, nullptr, &FragmentShaderErrorMessage[0]); fprintf(stdout, "%s\n", &FragmentShaderErrorMessage[0]); - + // Link the program fprintf(stdout, "Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); - + // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector ProgramErrorMessage( glm::max(InfoLogLength, int(1)) ); glGetProgramInfoLog(ProgramID, InfoLogLength, nullptr, &ProgramErrorMessage[0]); fprintf(stdout, "%s\n", &ProgramErrorMessage[0]); - + glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); - + return ProgramID; } @@ -135,14 +135,14 @@ void flipImageData(unsigned char* data, int width, int height, int comps) { unsigned char* data_copy = (unsigned char*) malloc(width*height*comps*sizeof(unsigned char)); memcpy(data_copy, data, width*height*comps); - + int row_size = width * comps; - + for (int i=0;i& out_vertices, std::v fprintf(stderr, "Could not open mesh file %s\n", filename); exit(1); } - + std::vector temp_vertices; std::vector temp_uvs; std::vector temp_normals; - + for (;;) { char lineHeader[256]; @@ -167,7 +167,7 @@ void loadMesh(const char* filename, std::vector& out_vertices, std::v { break; } - + if (!strncmp(lineHeader, "v", 2)) { glm::vec3 vertex; @@ -187,7 +187,7 @@ void loadMesh(const char* filename, std::vector& out_vertices, std::v { int vertexIDs[3], uvIDs[3], normalIDs[3]; fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIDs[0], &uvIDs[0], &normalIDs[0], &vertexIDs[1], &uvIDs[1], &normalIDs[1], &vertexIDs[2], &uvIDs[2], &normalIDs[2]); - + for (int i=0; i<3; i++) { out_vertices.push_back(temp_vertices[vertexIDs[i] - 1]); @@ -202,24 +202,24 @@ void setFramebufferSize(GLFWwindow* w, int width, int height) { buffer_width = width; buffer_height = height; - + glDeleteFramebuffers(1, &bloom_framebuffer); glDeleteRenderbuffers(1, &bloom_depthbuffer); - + glGenFramebuffers(1, &bloom_framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, bloom_framebuffer); GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT1}; glDrawBuffers(1, DrawBuffers); - + glGenRenderbuffers(1, &bloom_depthbuffer); glBindRenderbuffer(GL_RENDERBUFFER, bloom_depthbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, bloom_depthbuffer); - + glDeleteTextures(1, &preBloomTex); glDeleteTextures(1, &bloomPassTex1); glDeleteTextures(1, &bloomPassTex2); - + glGenTextures(1, &preBloomTex); glBindTexture(GL_TEXTURE_2D, preBloomTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); @@ -227,7 +227,7 @@ void setFramebufferSize(GLFWwindow* w, int width, int height) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - + glGenTextures(1, &bloomPassTex1); glBindTexture(GL_TEXTURE_2D, bloomPassTex1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width/4, height/4, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); @@ -235,7 +235,7 @@ void setFramebufferSize(GLFWwindow* w, int width, int height) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - + glGenTextures(1, &bloomPassTex2); glBindTexture(GL_TEXTURE_2D, bloomPassTex2); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width/4, height/4, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); @@ -252,20 +252,20 @@ GLFWwindow* initRenderer() fprintf(stderr, "Renderer already initialized\n"); exit(-1); } - + // Initialize GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); exit(-1); } - + glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want version 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Mac requires this glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - + // Create a window window = glfwCreateWindow(1024, 768, "Aromatherapy", nullptr, nullptr); if (window == nullptr) @@ -274,7 +274,7 @@ GLFWwindow* initRenderer() glfwTerminate(); exit(-1); } - + glfwMakeContextCurrent(window); glewExperimental = true; // Needed in core profile if (glewInit() != GLEW_OK) @@ -282,37 +282,37 @@ GLFWwindow* initRenderer() fprintf(stderr, "Failed to initialize GLEW\n"); exit(-1); } - + glfwSetFramebufferSizeCallback(window, &setFramebufferSize); - + // Set up vertex array object glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); - + // Enable depth testing glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); - + // Enable blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - + // Set up the framebuffer glGenFramebuffers(1, &generic_framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, generic_framebuffer); GLenum DrawBuffers[1] = {GL_COLOR_ATTACHMENT0}; glDrawBuffers(1, DrawBuffers); - + glGenFramebuffers(1, &bloom_framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, bloom_framebuffer); GLenum DrawBuffers2[1] = {GL_COLOR_ATTACHMENT1}; glDrawBuffers(1, DrawBuffers2); - + glGenRenderbuffers(1, &bloom_depthbuffer); glBindRenderbuffer(GL_RENDERBUFFER, bloom_depthbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 1024, 768); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, bloom_depthbuffer); - + // Set up the NTSC rendering buffers glGenTextures(1, &renderedTex1); glBindTexture(GL_TEXTURE_2D, renderedTex1); @@ -322,7 +322,7 @@ GLFWwindow* initRenderer() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); renderedTexBufs[0] = renderedTex1; - + glGenTextures(1, &renderedTex2); glBindTexture(GL_TEXTURE_2D, renderedTex2); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, GAME_WIDTH, GAME_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); @@ -331,7 +331,7 @@ GLFWwindow* initRenderer() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); renderedTexBufs[1] = renderedTex2; - + // Set up bloom rendering buffers glGenTextures(1, &preBloomTex); glBindTexture(GL_TEXTURE_2D, preBloomTex); @@ -340,7 +340,7 @@ GLFWwindow* initRenderer() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - + glGenTextures(1, &bloomPassTex1); glBindTexture(GL_TEXTURE_2D, bloomPassTex1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024/4, 768/4, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); @@ -348,7 +348,7 @@ GLFWwindow* initRenderer() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - + glGenTextures(1, &bloomPassTex2); glBindTexture(GL_TEXTURE_2D, bloomPassTex2); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024/4, 768/4, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); @@ -356,31 +356,31 @@ GLFWwindow* initRenderer() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - + curBuf = 0; - + // Load the mesh! std::vector mesh_vertices; std::vector mesh_uvs; std::vector mesh_normals; loadMesh("res/monitor-fef.obj", mesh_vertices, mesh_uvs, mesh_normals); - + mesh_numvertices = mesh_vertices.size(); - + glGenBuffers(1, &mesh_vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, mesh_vertexbuffer); glBufferData(GL_ARRAY_BUFFER, mesh_vertices.size() * sizeof(glm::vec3), &mesh_vertices[0], GL_STATIC_DRAW); - + glGenBuffers(1, &mesh_uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, mesh_uvbuffer); glBufferData(GL_ARRAY_BUFFER, mesh_uvs.size() * sizeof(glm::vec3), &mesh_uvs[0], GL_STATIC_DRAW); - + glGenBuffers(1, &mesh_normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, mesh_normalbuffer); glBufferData(GL_ARRAY_BUFFER, mesh_normals.size() * sizeof(glm::vec3), &mesh_normals[0], GL_STATIC_DRAW); - + // Load the vertices of a flat surface - GLfloat g_quad_vertex_buffer_data[] = { + GLfloat g_quad_vertex_buffer_data[] = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, @@ -392,7 +392,7 @@ GLFWwindow* initRenderer() glGenBuffers(1, &quad_vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_quad_vertex_buffer_data), g_quad_vertex_buffer_data, GL_STATIC_DRAW); - + glGenTextures(1, &artifactsTex); glBindTexture(GL_TEXTURE_2D, artifactsTex); int atdw, atdh; @@ -403,7 +403,7 @@ GLFWwindow* initRenderer() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); glGenerateMipmap(GL_TEXTURE_2D); - + glGenTextures(1, &scanlinesTex); glBindTexture(GL_TEXTURE_2D, scanlinesTex); int stdw, stdh; @@ -414,7 +414,7 @@ GLFWwindow* initRenderer() glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); glGenerateMipmap(GL_TEXTURE_2D); - + // Load the shaders ntscShader = LoadShaders("shaders/ntsc.vertex", "shaders/ntsc.fragment"); finalShader = LoadShaders("shaders/final.vertex", "shaders/final.fragment"); @@ -422,9 +422,9 @@ GLFWwindow* initRenderer() fillShader = LoadShaders("shaders/fill.vertex", "shaders/fill.fragment"); bloom1Shader = LoadShaders("shaders/bloom1.vertex", "shaders/bloom1.fragment"); bloom2Shader = LoadShaders("shaders/bloom2.vertex", "shaders/bloom2.fragment"); - + rendererInitialized = true; - + return window; } @@ -435,13 +435,13 @@ void destroyRenderer() fprintf(stderr, "Renderer not initialized\n"); exit(-1); } - + // Delete the plane buffer glDeleteBuffers(1, &quad_vertexbuffer); glDeleteBuffers(1, &mesh_vertexbuffer); glDeleteBuffers(1, &mesh_uvbuffer); glDeleteBuffers(1, &mesh_normalbuffer); - + // Delete the shaders glDeleteProgram(ntscShader); glDeleteProgram(finalShader); @@ -449,7 +449,7 @@ void destroyRenderer() glDeleteProgram(fillShader); glDeleteProgram(bloom1Shader); glDeleteProgram(bloom2Shader); - + // Delete the NTSC rendering buffers glDeleteTextures(1, &renderedTex1); glDeleteTextures(1, &renderedTex2); @@ -458,18 +458,18 @@ void destroyRenderer() glDeleteTextures(1, &preBloomTex); glDeleteTextures(1, &bloomPassTex1); glDeleteTextures(1, &bloomPassTex2); - + // Delete the framebuffer glDeleteRenderbuffers(1, &bloom_depthbuffer); glDeleteFramebuffers(1, &bloom_framebuffer); glDeleteFramebuffers(1, &generic_framebuffer); - + // Delete the VAO glDeleteVertexArrays(1, &VertexArrayID); - + // Kill the window glfwTerminate(); - + rendererInitialized = false; } @@ -480,10 +480,10 @@ Texture::Texture(int width, int height) fprintf(stderr, "Renderer not initialized\n"); exit(-1); } - + this->width = width; this->height = height; - + glGenTextures(1, &texID); glBindTexture(GL_TEXTURE_2D, texID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); @@ -500,7 +500,7 @@ Texture::Texture(const char* filename) fprintf(stderr, "Renderer not initialized\n"); exit(-1); } - + glGenTextures(1, &texID); glBindTexture(GL_TEXTURE_2D, texID); unsigned char* data = stbi_load(filename, &width, &height, 0, 4); @@ -520,14 +520,14 @@ Texture::Texture(const Texture& tex) fprintf(stderr, "Renderer not initialized\n"); exit(-1); } - + width = tex.width; height = tex.height; - + unsigned char* data = (unsigned char*) malloc(4 * width * height); glBindTexture(GL_TEXTURE_2D, tex.texID); glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - + glGenTextures(1, &texID); glBindTexture(GL_TEXTURE_2D, texID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); @@ -535,7 +535,7 @@ Texture::Texture(const Texture& tex) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - + free(data); } @@ -551,14 +551,14 @@ Texture::~Texture() fprintf(stderr, "Renderer not initialized\n"); exit(-1); } - + glDeleteTextures(1, &texID); } Texture& Texture::operator= (Texture tex) { swap(*this, tex); - + return *this; } @@ -576,17 +576,17 @@ void Texture::fill(Rectangle dstrect, int r, int g, int b) fprintf(stderr, "Renderer not initialized\n"); exit(-1); } - + // Target the framebuffer glBindFramebuffer(GL_FRAMEBUFFER, generic_framebuffer); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texID, 0); - + // Set up the vertex attributes GLfloat minx = (GLfloat) dstrect.x / width * 2.0 - 1.0; GLfloat miny = -((GLfloat) dstrect.y / height * 2.0 - 1.0); GLfloat maxx = (GLfloat) (dstrect.x + dstrect.w) / width * 2.0 - 1.0; GLfloat maxy = -((GLfloat) (dstrect.y + dstrect.h) / height * 2.0 - 1.0); - + GLfloat vertexbuffer_data[] = { minx, miny, maxx, miny, @@ -601,14 +601,14 @@ void Texture::fill(Rectangle dstrect, int r, int g, int b) glBufferData(GL_ARRAY_BUFFER, sizeof(vertexbuffer_data), vertexbuffer_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); - + glViewport(0, 0, width, height); glClear(GL_DEPTH_BUFFER_BIT); glUseProgram(fillShader); glUniform3f(glGetUniformLocation(fillShader, "vecColor"), r / 255.0, g / 255.0, b / 255.0); - + glDrawArrays(GL_TRIANGLES, 0, 6); - + glDisableVertexAttribArray(0); glDeleteBuffers(1, &vertexbuffer); } @@ -620,19 +620,19 @@ void Texture::blit(const Texture& srctex, Rectangle srcrect, Rectangle dstrect, fprintf(stderr, "Renderer not initialized\n"); exit(-1); } - + alpha = glm::clamp(alpha, 0.0, 1.0); - + // Target the framebuffer glBindFramebuffer(GL_FRAMEBUFFER, generic_framebuffer); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texID, 0); - + // Set up the vertex attributes GLfloat minx = (GLfloat) dstrect.x / width * 2.0 - 1.0; GLfloat miny = -((GLfloat) dstrect.y / height * 2.0 - 1.0); GLfloat maxx = (GLfloat) (dstrect.x + dstrect.w) / width * 2.0 - 1.0; GLfloat maxy = -((GLfloat) (dstrect.y + dstrect.h) / height * 2.0 - 1.0); - + GLfloat vertexbuffer_data[] = { minx, miny, maxx, miny, @@ -645,12 +645,12 @@ void Texture::blit(const Texture& srctex, Rectangle srcrect, Rectangle dstrect, glBufferData(GL_ARRAY_BUFFER, sizeof(vertexbuffer_data), vertexbuffer_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); - + GLfloat minu = (GLfloat) srcrect.x / srctex.width; GLfloat minv = 1 - ((GLfloat) srcrect.y / srctex.height); GLfloat maxu = (GLfloat) (srcrect.x + srcrect.w) / srctex.width; GLfloat maxv = 1 - ((GLfloat) (srcrect.y + srcrect.h) / srctex.height); - + GLfloat texcoordbuffer_data[] = { minu, minv, maxu, minv, @@ -663,20 +663,20 @@ void Texture::blit(const Texture& srctex, Rectangle srcrect, Rectangle dstrect, glBufferData(GL_ARRAY_BUFFER, sizeof(texcoordbuffer_data), texcoordbuffer_data, GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); - + // Set up the shader glUseProgram(blitShader); glClear(GL_DEPTH_BUFFER_BIT); glViewport(0, 0, width, height); - + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, srctex.texID); glUniform1i(glGetUniformLocation(blitShader, "srctex"), 0); glUniform1f(glGetUniformLocation(blitShader, "alpha"), alpha); - + // Blit! glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - + // Unload everything glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); @@ -691,11 +691,11 @@ void bloomPass1(GLuint srcTex, GLuint dstTex, bool horizontal, glm::vec2 srcRes, glViewport(0,0,dstRes.x,dstRes.y); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(bloom1Shader); - + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, srcTex); glUniform1i(glGetUniformLocation(bloom1Shader, "inTex"), 0); - + glm::vec2 offset = glm::vec2(0.0); if (horizontal) { @@ -703,9 +703,9 @@ void bloomPass1(GLuint srcTex, GLuint dstTex, bool horizontal, glm::vec2 srcRes, } else { offset.y = 1.2/srcRes.y; } - + glUniform2f(glGetUniformLocation(bloom1Shader, "offset"), offset.x, offset.y); - + glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); @@ -720,17 +720,17 @@ void Texture::renderScreen() const fprintf(stderr, "Renderer not initialized\n"); exit(-1); } - + // First we're going to composite our frame with the previous frame // We start by setting up the framebuffer glBindFramebuffer(GL_FRAMEBUFFER, generic_framebuffer); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, renderedTexBufs[curBuf], 0); - + // Set up the shader glViewport(0,0,GAME_WIDTH,GAME_HEIGHT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(ntscShader); - + // Use the current frame texture, nearest neighbor and clamped to edge glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texID); @@ -739,7 +739,7 @@ void Texture::renderScreen() const glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glUniform1i(glGetUniformLocation(ntscShader, "curFrameSampler"), 0); - + // Use the previous frame composite texture, nearest neighbor and clamped to edge glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, renderedTexBufs[(curBuf + 1) % 2]); @@ -748,13 +748,13 @@ void Texture::renderScreen() const glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glUniform1i(glGetUniformLocation(ntscShader, "prevFrameSampler"), 1); - + // Load the NTSC artifact texture glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, artifactsTex); glUniform1i(glGetUniformLocation(ntscShader, "NTSCArtifactSampler"), 2); glUniform1f(glGetUniformLocation(ntscShader, "NTSCLerp"), curBuf * 1.0); - + if ((rand() % 60) == 0) { // Change the 0.0 to a 1.0 or a 10.0 for a glitchy effect! @@ -762,7 +762,7 @@ void Texture::renderScreen() const } else { glUniform1f(glGetUniformLocation(ntscShader, "Tuning_NTSC"), 0.0); } - + // Render our composition glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); @@ -776,7 +776,7 @@ void Texture::renderScreen() const glViewport(0,0,buffer_width,buffer_height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(finalShader); - + // Use the composited frame texture, linearly filtered and filling in black for the border glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, renderedTexBufs[curBuf]); @@ -788,69 +788,69 @@ void Texture::renderScreen() const glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border_color); glGenerateMipmap(GL_TEXTURE_2D); glUniform1i(glGetUniformLocation(finalShader, "rendertex"), 0); - + // Use the scanlines texture glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, scanlinesTex); glUniform1i(glGetUniformLocation(finalShader, "scanlinestex"), 1); - + // Initialize the MVP matrices glm::mat4 p_matrix = glm::perspective(42.5f, (float) buffer_width / (float) buffer_height, 0.1f, 100.0f); glm::mat4 v_matrix = glm::lookAt(glm::vec3(2,0,0), glm::vec3(0,0,0), glm::vec3(0,1,0)); glm::mat4 m_matrix = glm::mat4(1.0); glm::mat4 mvp_matrix = p_matrix * v_matrix * m_matrix; - + glUniformMatrix4fv(glGetUniformLocation(finalShader, "MVP"), 1, GL_FALSE, &mvp_matrix[0][0]); glUniformMatrix4fv(glGetUniformLocation(finalShader, "worldMat"), 1, GL_FALSE, &m_matrix[0][0]); glUniform2f(glGetUniformLocation(finalShader, "resolution"), buffer_width, buffer_height); glUniform1f(glGetUniformLocation(finalShader, "iGlobalTime"), glfwGetTime()); - + glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, mesh_vertexbuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); - + glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, mesh_normalbuffer); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); - + glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, mesh_uvbuffer); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); - + glDrawArrays(GL_TRIANGLES, 0, mesh_numvertices); glDisableVertexAttribArray(2); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); - + // First pass of bloom! glm::vec2 buffer_size = glm::vec2(buffer_width, buffer_height); bloomPass1(preBloomTex, bloomPassTex1, true, buffer_size, buffer_size / 4.0f); bloomPass1(bloomPassTex1, bloomPassTex2, false, buffer_size / 4.0f, buffer_size / 4.0f); - + // Do the second pass of bloom and render to screen glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, buffer_width, buffer_height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(bloom2Shader); - + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, preBloomTex); glUniform1i(glGetUniformLocation(bloom2Shader, "clearTex"), 0); - + glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, bloomPassTex2); glUniform1i(glGetUniformLocation(bloom2Shader, "blurTex"), 1); - + glUniform1f(glGetUniformLocation(bloom2Shader, "iGlobalTime"), glfwGetTime()); - + glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(0); - + glfwSwapBuffers(window); - + curBuf = (curBuf + 1) % 2; } diff --git a/src/renderer.h b/src/renderer.h index 84ad688..6dccf7a 100644 --- a/src/renderer.h +++ b/src/renderer.h @@ -24,7 +24,7 @@ class Texture { void blit(const Texture& src, Rectangle srcrect, Rectangle dstrect, double alpha = 1.0); void renderScreen() const; Rectangle entirety() const; - + private: GLuint texID; int width; diff --git a/src/system.h b/src/system.h index e08db0a..af3fb77 100644 --- a/src/system.h +++ b/src/system.h @@ -7,9 +7,9 @@ class System { public: System(Game& game) : game(game) {} - + virtual void tick(double dt) = 0; - + protected: Game& game; }; diff --git a/src/system_manager.h b/src/system_manager.h index 8f76db2..087b71c 100644 --- a/src/system_manager.h +++ b/src/system_manager.h @@ -18,18 +18,18 @@ class SystemManager { { std::unique_ptr ptr = std::unique_ptr(new T(game, std::forward(args)...)); std::type_index systemType = typeid(T); - + systems[systemType] = ptr.get(); loop.push_back(std::move(ptr)); } - + template T& getSystem() { std::type_index systemType = typeid(T); - + assert(systems.count(systemType) == 1); - + return *((T*)systems[systemType]); } }; diff --git a/src/systems/controlling.cpp b/src/systems/controlling.cpp index b1e73ad..456da3b 100644 --- a/src/systems/controlling.cpp +++ b/src/systems/controlling.cpp @@ -14,12 +14,12 @@ void ControllingSystem::tick(double dt) { int key = actions.front().first; int action = actions.front().second; - + auto entities = game.getEntityManager().getEntitiesWithComponents(); for (auto entity : entities) { auto& controllable = game.getEntityManager().getComponent(entity); - + if (action == GLFW_PRESS) { if (key == controllable.getLeftKey()) @@ -33,7 +33,7 @@ void ControllingSystem::tick(double dt) } else if (key == controllable.getRightKey()) { controllable.setHoldingRight(true); - + if (!controllable.isFrozen()) { walkRight(entity); @@ -56,7 +56,7 @@ void ControllingSystem::tick(double dt) if (key == controllable.getLeftKey()) { controllable.setHoldingLeft(false); - + if (!controllable.isFrozen()) { if (controllable.isHoldingRight()) @@ -69,7 +69,7 @@ void ControllingSystem::tick(double dt) } else if (key == controllable.getRightKey()) { controllable.setHoldingRight(false); - + if (!controllable.isFrozen()) { if (controllable.isHoldingRight()) @@ -94,7 +94,7 @@ void ControllingSystem::tick(double dt) } } } - + actions.pop(); } } diff --git a/src/systems/controlling.h b/src/systems/controlling.h index 61f86eb..30210b3 100644 --- a/src/systems/controlling.h +++ b/src/systems/controlling.h @@ -8,10 +8,10 @@ class ControllingSystem : public System { public: ControllingSystem(Game& game) : System(game) {} - + void tick(double dt); void input(int key, int action); - + private: void walkLeft(int entity); void walkRight(int entity); @@ -19,7 +19,7 @@ class ControllingSystem : public System { void jump(int entity); void stopJumping(int entity); void drop(int entity, bool start); - + std::queue> actions; }; diff --git a/src/systems/pondering.cpp b/src/systems/pondering.cpp index 96775d0..50a8bc8 100644 --- a/src/systems/pondering.cpp +++ b/src/systems/pondering.cpp @@ -6,16 +6,16 @@ void PonderingSystem::tick(double dt) { auto entities = game.getEntityManager().getEntitiesWithComponents(); - + for (auto entity : entities) { auto& transformable = game.getEntityManager().getComponent(entity); auto& ponderable = game.getEntityManager().getComponent(entity); - + // Accelerate ponderable.setVelocityX(ponderable.getVelocityX() + ponderable.getAccelX() * dt); ponderable.setVelocityY(ponderable.getVelocityY() + ponderable.getAccelY() * dt); - + // Move transformable.setX(transformable.getX() + ponderable.getVelocityX() * dt); transformable.setY(transformable.getY() + ponderable.getVelocityY() * dt); diff --git a/src/systems/pondering.h b/src/systems/pondering.h index ad01a22..3fe5473 100644 --- a/src/systems/pondering.h +++ b/src/systems/pondering.h @@ -7,7 +7,7 @@ class PonderingSystem : public System { public: PonderingSystem(Game& game) : System(game) {} - + void tick(double dt); }; diff --git a/src/systems/rendering.h b/src/systems/rendering.h index 9b6e27e..cec72e2 100644 --- a/src/systems/rendering.h +++ b/src/systems/rendering.h @@ -9,9 +9,9 @@ class RenderingSystem : public System { public: RenderingSystem(Game& game) : System(game) {} - + void tick(double dt); - + private: Texture texture {GAME_WIDTH, GAME_HEIGHT}; }; -- cgit 1.4.1 From f9448d36db7c076f5091f70b7921dceddf63fdf9 Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Wed, 7 Feb 2018 15:18:48 -0500 Subject: Inlined some components --- CMakeLists.txt | 5 +- src/components/controllable.cpp | 71 ------------------------- src/components/controllable.h | 108 +++++++++++++++++++++++++++++---------- src/components/droppable.cpp | 11 ---- src/components/droppable.h | 19 +++++-- src/components/ponderable.cpp | 41 --------------- src/components/ponderable.h | 68 ++++++++++++++++++------ src/components/transformable.cpp | 47 ----------------- src/components/transformable.h | 78 +++++++++++++++++++++------- 9 files changed, 210 insertions(+), 238 deletions(-) delete mode 100644 src/components/controllable.cpp delete mode 100644 src/components/droppable.cpp delete mode 100644 src/components/ponderable.cpp delete mode 100644 src/components/transformable.cpp (limited to 'src/components/transformable.h') diff --git a/CMakeLists.txt b/CMakeLists.txt index 12d2551..e43b056 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -60,10 +60,7 @@ add_executable(Aromatherapy src/muxer.cpp src/entity_manager.cpp src/game.cpp - src/components/transformable.cpp - src/components/droppable.cpp - src/components/controllable.cpp - src/components/ponderable.cpp + src/animation.cpp src/components/animatable.cpp src/systems/rendering.cpp src/systems/controlling.cpp diff --git a/src/components/controllable.cpp b/src/components/controllable.cpp deleted file mode 100644 index a4d45f2..0000000 --- a/src/components/controllable.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "controllable.h" - -int ControllableComponent::getLeftKey() const -{ - return leftKey; -} - -void ControllableComponent::setLeftKey(int k) -{ - leftKey = k; -} - -int ControllableComponent::getRightKey() const -{ - return rightKey; -} - -void ControllableComponent::setRightKey(int k) -{ - rightKey = k; -} - -int ControllableComponent::getJumpKey() const -{ - return jumpKey; -} - -void ControllableComponent::setJumpKey(int k) -{ - jumpKey = k; -} - -int ControllableComponent::getDropKey() const -{ - return dropKey; -} - -void ControllableComponent::setDropKey(int k) -{ - dropKey = k; -} - -bool ControllableComponent::isFrozen() const -{ - return frozen; -} - -void ControllableComponent::setFrozen(bool f) -{ - frozen = f; -} - -bool ControllableComponent::isHoldingLeft() const -{ - return holdingLeft; -} - -void ControllableComponent::setHoldingLeft(bool f) -{ - holdingLeft = f; -} - -bool ControllableComponent::isHoldingRight() const -{ - return holdingRight; -} - -void ControllableComponent::setHoldingRight(bool f) -{ - holdingRight = f; -} diff --git a/src/components/controllable.h b/src/components/controllable.h index baccf13..fa78c8b 100644 --- a/src/components/controllable.h +++ b/src/components/controllable.h @@ -5,32 +5,88 @@ #include "renderer.h" class ControllableComponent : public Component { - public: - int getLeftKey() const; - void setLeftKey(int k); - int getRightKey() const; - void setRightKey(int k); - int getJumpKey() const; - void setJumpKey(int k); - int getDropKey() const; - void setDropKey(int k); - - bool isFrozen() const; - void setFrozen(bool f); - bool isHoldingLeft() const; - void setHoldingLeft(bool f); - bool isHoldingRight() const; - void setHoldingRight(bool f); - - private: - int leftKey = GLFW_KEY_LEFT; - int rightKey = GLFW_KEY_RIGHT; - int jumpKey = GLFW_KEY_UP; - int dropKey = GLFW_KEY_DOWN; - - bool frozen = false; - bool holdingLeft = false; - bool holdingRight = false; +public: + + inline int getLeftKey() const + { + return leftKey_; + } + + inline void setLeftKey(int k) + { + leftKey_ = k; + } + + inline int getRightKey() const + { + return rightKey_; + } + + inline void setRightKey(int k) + { + rightKey_ = k; + } + + inline int getJumpKey() const + { + return jumpKey_; + } + + inline void setJumpKey(int k) + { + jumpKey_ = k; + } + + inline int getDropKey() const + { + return dropKey_; + } + + inline void setDropKey(int k) + { + dropKey_ = k; + } + + inline bool isFrozen() const + { + return frozen_; + } + + inline void setFrozen(bool f) + { + frozen_ = f; + } + + inline bool isHoldingLeft() const + { + return holdingLeft_; + } + + inline void setHoldingLeft(bool f) + { + holdingLeft_ = f; + } + + inline bool isHoldingRight() const + { + return holdingRight_; + } + + inline void setHoldingRight(bool f) + { + holdingRight_ = f; + } + +private: + + int leftKey_ = GLFW_KEY_LEFT; + int rightKey_ = GLFW_KEY_RIGHT; + int jumpKey_ = GLFW_KEY_UP; + int dropKey_ = GLFW_KEY_DOWN; + + bool frozen_ = false; + bool holdingLeft_ = false; + bool holdingRight_ = false; }; #endif /* end of include guard: CONTROLLABLE_H_4E0B85B4 */ diff --git a/src/components/droppable.cpp b/src/components/droppable.cpp deleted file mode 100644 index 534fd9a..0000000 --- a/src/components/droppable.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "droppable.h" - -void DroppableComponent::setDroppable(bool can) -{ - droppable = can; -} - -bool DroppableComponent::isDroppable() const -{ - return droppable; -} diff --git a/src/components/droppable.h b/src/components/droppable.h index 83fcb9d..722c139 100644 --- a/src/components/droppable.h +++ b/src/components/droppable.h @@ -4,12 +4,21 @@ #include "component.h" class DroppableComponent : public Component { - public: - void setDroppable(bool can); - bool isDroppable() const; +public: - private: - bool droppable = false; + inline bool isDroppable() const + { + return droppable_; + } + + inline void setDroppable(bool can) + { + droppable_ = can; + } + +private: + + bool droppable_ = false; }; #endif /* end of include guard: DROPPABLE_H_5DB254EF */ diff --git a/src/components/ponderable.cpp b/src/components/ponderable.cpp deleted file mode 100644 index 2cfa6a6..0000000 --- a/src/components/ponderable.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "ponderable.h" - -double PonderableComponent::getVelocityX() const -{ - return velocityX; -} - -void PonderableComponent::setVelocityX(double v) -{ - velocityX = v; -} - -double PonderableComponent::getVelocityY() const -{ - return velocityY; -} - -void PonderableComponent::setVelocityY(double v) -{ - velocityY = v; -} - -double PonderableComponent::getAccelX() const -{ - return accelX; -} - -void PonderableComponent::setAccelX(double v) -{ - accelX = v; -} - -double PonderableComponent::getAccelY() const -{ - return accelY; -} - -void PonderableComponent::setAccelY(double v) -{ - accelY = v; -} diff --git a/src/components/ponderable.h b/src/components/ponderable.h index c836d2a..80100d7 100644 --- a/src/components/ponderable.h +++ b/src/components/ponderable.h @@ -4,21 +4,59 @@ #include "component.h" class PonderableComponent : public Component { - public: - double getVelocityX() const; - void setVelocityX(double v); - double getVelocityY() const; - void setVelocityY(double v); - double getAccelX() const; - void setAccelX(double v); - double getAccelY() const; - void setAccelY(double v); - - private: - double velocityX = 0.0; - double velocityY = 0.0; - double accelX = 0.0; - double accelY = 0.0; +public: + + inline double getVelocityX() const + { + return velX_; + } + + inline void setVelocityX(double v) + { + velX_ = v; + } + + inline double getVelocityY() const + { + return velY_; + } + + inline void setVelocityY(double v) + { + velY_ = v; + } + + inline double getAccelX() const + { + return accelX_; + } + + inline void setAccelX(double v) + { + accelX_ = v; + } + + inline double getAccelY() const + { + return accelY_; + } + + inline void setAccelY(double v) + { + accelY_ = v; + } + + inline state getState() const + { + return state_; + } + +private: + + double velX_ = 0.0; + double velY_ = 0.0; + double accelX_ = 0.0; + double accelY_ = 0.0; }; #endif /* end of include guard: TANGIBLE_H_746DB3EE */ diff --git a/src/components/transformable.cpp b/src/components/transformable.cpp deleted file mode 100644 index 89b1e5d..0000000 --- a/src/components/transformable.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include "transformable.h" - -TransformableComponent::TransformableComponent(double x, double y, int w, int h) - : x(x), y(y), w(w), h(h) -{ - -} - -double TransformableComponent::getX() const -{ - return x; -} - -double TransformableComponent::getY() const -{ - return y; -} - -int TransformableComponent::getW() const -{ - return w; -} - -int TransformableComponent::getH() const -{ - return h; -} - -void TransformableComponent::setX(double v) -{ - x = v; -} - -void TransformableComponent::setY(double v) -{ - y = v; -} - -void TransformableComponent::setW(int v) -{ - w = v; -} - -void TransformableComponent::setH(int v) -{ - h = v; -} diff --git a/src/components/transformable.h b/src/components/transformable.h index 69f4f0e..6ed2637 100644 --- a/src/components/transformable.h +++ b/src/components/transformable.h @@ -4,24 +4,66 @@ #include "component.h" class TransformableComponent : public Component { - public: - TransformableComponent(double x, double y, int w, int h); - - double getX() const; - double getY() const; - int getW() const; - int getH() const; - - void setX(double v); - void setY(double v); - void setW(int v); - void setH(int v); - - private: - double x; - double y; - int w; - int h; +public: + + TransformableComponent( + double x, + double y, + int w, + int h) : + x_(x), + y_(y), + w_(w), + h_(h) + { + } + + inline double getX() const + { + return x_; + } + + inline void setX(double v) + { + x_ = v; + } + + inline double getY() const + { + return y_; + } + + inline void setY(double v) + { + y_ = v; + } + + inline int getW() const + { + return w_; + } + + inline void setW(int v) + { + w_ = v; + } + + inline int getH() const + { + return h_; + } + + inline void setH(int v) + { + h_ = v; + } + +private: + + double x_; + double y_; + int w_; + int h_; }; #endif /* end of include guard: LOCATABLE_H_39E526CA */ -- cgit 1.4.1 From 8016a7146fec3f6f43ca05723441750e5aae3d4d Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Sat, 28 Apr 2018 09:22:44 -0400 Subject: Restructured the way the world is loaded The World class was removed and replaced by the RealizingSystem and RealizableComponent. The realizable entity is intended to be a singleton and to represent the world. The Map class was also removed and integrated into the MappableComponent. These changes are to facilitate implementation of map objects without needing special intermediary objects (including the Map class). Now, map entities are created as soon as the world is created, and map object entities will be as well. They will simply be deactivated while the map is not active. Multiple players are now slightly better supported, which will be important in the future. This will likely become inefficient as the world becomes bigger, and some sort of sector-loading process will have to be designed. This also reduces the usefulness of EntityManager's entity-searching capabilities (which are not the most efficiently implemented currently anyway), and will likely in the future require some added functionality to better search subsets of entities. A lot of the components were also rewritten to use bare member variables instead of accessor methods, as they never had special functionality and just took up space. These components were also documented. --- CMakeLists.txt | 2 +- src/components/animatable.h | 146 +++++++++-------- src/components/mappable.h | 208 ++++++++++++------------ src/components/playable.h | 28 ++-- src/components/ponderable.h | 151 ++++++++---------- src/components/realizable.h | 67 ++++++++ src/components/transformable.h | 79 +++------ src/game.cpp | 6 +- src/game.h | 7 - src/map.h | 111 ------------- src/systems/animating.cpp | 93 ++++++----- src/systems/animating.h | 2 + src/systems/mapping.cpp | 127 +++++++-------- src/systems/mapping.h | 2 +- src/systems/orienting.cpp | 22 +-- src/systems/playing.cpp | 220 ++++++++++++------------- src/systems/playing.h | 9 +- src/systems/pondering.cpp | 354 +++++++++++++++++++++++------------------ src/systems/pondering.h | 2 + src/systems/realizing.cpp | 321 +++++++++++++++++++++++++++++++++++++ src/systems/realizing.h | 43 +++++ src/world.cpp | 155 ------------------ src/world.h | 41 ----- 23 files changed, 1155 insertions(+), 1041 deletions(-) create mode 100644 src/components/realizable.h delete mode 100644 src/map.h create mode 100644 src/systems/realizing.cpp create mode 100644 src/systems/realizing.h delete mode 100644 src/world.cpp delete mode 100644 src/world.h (limited to 'src/components/transformable.h') diff --git a/CMakeLists.txt b/CMakeLists.txt index 34246ad..81365c9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -53,7 +53,6 @@ add_executable(Aromatherapy src/entity_manager.cpp src/game.cpp src/animation.cpp - src/world.cpp src/util.cpp src/collision.cpp src/renderer/renderer.cpp @@ -67,6 +66,7 @@ add_executable(Aromatherapy src/systems/orienting.cpp src/systems/playing.cpp src/systems/scheduling.cpp + src/systems/realizing.cpp ) set_property(TARGET Aromatherapy PROPERTY CXX_STANDARD 11) diff --git a/src/components/animatable.h b/src/components/animatable.h index ec72be0..1a678ba 100644 --- a/src/components/animatable.h +++ b/src/components/animatable.h @@ -8,88 +8,86 @@ class AnimatableComponent : public Component { public: + /** + * Constructor for initializing the animation set, because it is not default + * constructible. + */ AnimatableComponent( - AnimationSet animationSet, - std::string animation) : - animationSet_(std::move(animationSet)), - animation_(std::move(animation)) + AnimationSet animationSet) : + animationSet(std::move(animationSet)) { } - inline size_t getFrame() const - { - return frame_; - } - - inline void setFrame(size_t v) - { - frame_ = v; - } - - inline size_t getCountdown() const - { - return countdown_; - } - - inline void setCountdown(size_t v) - { - countdown_ = v; - } - - inline const AnimationSet& getAnimationSet() const - { - return animationSet_; - } - + /** + * The animation set that this entity will use -- an object describing the + * different animations that can be used to render the entity. + * + * @managed_by RealizingSystem + */ + AnimationSet animationSet; + + /** + * The name of the currently active animation. + * + * @managed_by AnimatingSystem + */ + std::string animation; + + /** + * For prototypes, the name of the original animation. + * + * @managed_by RealizingSystem + */ + std::string origAnimation; + + /** + * Helper method for accessing the currently active animation. + */ inline const Animation& getAnimation() const { - return animationSet_.getAnimation(animation_); + return animationSet.getAnimation(animation); } - inline void setAnimation(std::string animation) - { - animation_ = std::move(animation); - } - - inline bool isFlickering() const - { - return flickering_; - } - - inline void setFlickering(bool v) - { - flickering_ = v; - } - - inline size_t getFlickerTimer() const - { - return flickerTimer_; - } - - inline void setFlickerTimer(size_t v) - { - flickerTimer_ = v; - } - - inline bool isFrozen() const - { - return frozen_; - } - - inline void setFrozen(bool v) - { - frozen_ = v; - } - -private: - - AnimationSet animationSet_; - std::string animation_; - size_t frame_ = 0; - size_t countdown_ = 0; - bool flickering_ = false; - size_t flickerTimer_ = 0; - bool frozen_ = false; + /** + * The frame of animation that is currently being rendered. + * + * @managed_by AnimatingSystem + */ + size_t frame = 0; + + /** + * The amount of time (in game frames) before the animation is advanced. + * + * @managed_by AnimatingSystem + */ + size_t countdown = 0; + + /** + * This option allows to give the sprite a "flickering" effect (as in, it is + * not rendered in some frames). + */ + bool flickering = false; + + /** + * Used for the flickering effect. + * + * @managed_by AnimatingSystem + */ + size_t flickerTimer = 0; + + /** + * If enabled, this will prevent the sprite's animation from progressing (but + * will not affect things such as placement on screen and flickering). + */ + bool frozen = false; + + /** + * If this flag is disabled, the entity will be ignored by the animating + * system. + * + * @managed_by RealizingSystem + */ + bool active = false; }; #endif /* end of include guard: SPRITE_RENDERABLE_H_D3AACBBF */ diff --git a/src/components/mappable.h b/src/components/mappable.h index 633cdf4..6f3d38e 100644 --- a/src/components/mappable.h +++ b/src/components/mappable.h @@ -2,14 +2,47 @@ #define MAPPABLE_H_0B0316FB #include +#include +#include +#include #include "component.h" #include "renderer/texture.h" #include "collision.h" -#include "map.h" +#include "entity_manager.h" class MappableComponent : public Component { public: + using id_type = EntityManager::id_type; + + /** + * Helper type that stores information about map adjacency. + */ + class Adjacent { + public: + + enum class Type { + wall, + wrap, + warp, + reverse + }; + + Adjacent( + Type type = Type::wall, + size_t mapId = 0) : + type(type), + mapId(mapId) + { + } + + Type type; + size_t mapId; + }; + + /** + * Helper type that stores information about collision boundaries. + */ class Boundary { public: @@ -20,121 +53,100 @@ public: double lower, double upper, Type type) : - axis_(axis), - lower_(lower), - upper_(upper), - type_(type) - { - } - - inline double getAxis() const - { - return axis_; - } - - inline double getLower() const - { - return lower_; - } - - inline double getUpper() const - { - return upper_; - } - - inline Type getType() const + axis(axis), + lower(lower), + upper(upper), + type(type) { - return type_; } - private: - - double axis_; - double lower_; - double upper_; - Type type_; + double axis; + double lower; + double upper; + Type type; }; - MappableComponent( - Texture tileset, - Texture font) : - tileset_(std::move(tileset)), - font_(std::move(font)) - { - } - + /** + * Helper types for efficient storage and lookup of collision boundaries. + */ using asc_boundaries_type = std::multimap< double, - Boundary, + const Boundary, std::less>; using desc_boundaries_type = std::multimap< double, - Boundary, + const Boundary, std::greater>; - inline size_t getMapId() const - { - return mapId_; - } - - inline void setMapId(size_t v) - { - mapId_ = v; - } - - inline desc_boundaries_type& getLeftBoundaries() - { - return leftBoundaries_; - } - - inline asc_boundaries_type& getRightBoundaries() - { - return rightBoundaries_; - } - - inline desc_boundaries_type& getUpBoundaries() - { - return upBoundaries_; - } - - inline asc_boundaries_type& getDownBoundaries() - { - return downBoundaries_; - } - - inline const Texture& getTileset() const - { - return tileset_; - } - - inline void setTileset(Texture v) - { - tileset_ = std::move(v); - } - - inline const Texture& getFont() const - { - return font_; - } - - inline void setFont(Texture v) + /** + * Constructor for initializing the tileset and font attributes, as they are + * not default constructible. + */ + MappableComponent( + Texture tileset, + Texture font) : + tileset(std::move(tileset)), + font(std::move(font)) { - font_ = std::move(v); } -private: - - size_t mapId_ = -1; - - desc_boundaries_type leftBoundaries_; - asc_boundaries_type rightBoundaries_; - desc_boundaries_type upBoundaries_; - asc_boundaries_type downBoundaries_; - Texture tileset_; - Texture font_; + /** + * The ID of the map in the world definition that this entity represents. + * + * @managed_by RealizingSystem + */ + size_t mapId; + + /** + * The title of the map, which is displayed at the bottom of the screen. + */ + std::string title; + + /** + * The map data. + * + * @managed_by RealizingSystem + */ + std::vector tiles; + + /** + * These objects describe the behavior of the four edges of the map. + * + * @managed_by RealizingSystem + */ + Adjacent leftAdjacent; + Adjacent rightAdjacent; + Adjacent upAdjacent; + Adjacent downAdjacent; + + /** + * Collision boundaries, for detecting when a ponderable entity is colliding + * with the environment. + * + * @managed_by MappingSystem + */ + desc_boundaries_type leftBoundaries; + asc_boundaries_type rightBoundaries; + desc_boundaries_type upBoundaries; + asc_boundaries_type downBoundaries; + + /** + * The list of entities representing the objects owned by the map. + * + * @managed_by RealizingSystem + */ + std::list objects; + + /** + * The tilesets for the map and the map name. + * + * TODO: These probably do not belong here. + */ + Texture tileset; + Texture font; }; #endif /* end of include guard: MAPPABLE_H_0B0316FB */ diff --git a/src/components/playable.h b/src/components/playable.h index 86a7ee7..94d4326 100644 --- a/src/components/playable.h +++ b/src/components/playable.h @@ -2,22 +2,30 @@ #define PLAYABLE_H_DDC566C3 #include "component.h" -#include +#include "entity_manager.h" class PlayableComponent : public Component { public: - using MapChangeCallback = std::function; + using id_type = EntityManager::id_type; - bool changingMap = false; - int newMapId = -1; - double newMapX = 0; - double newMapY = 0; - MapChangeCallback newMapCallback; + /** + * The entity ID of the map that the player is on. + * + * @managed_by PlayingSystem + */ + id_type mapId; - int checkpointMapId = -1; - double checkpointX = 0; - double checkpointY = 0; + /** + * The map ID and coordinates of the location that the player will spawn after + * dying. Note that the map ID here is a world description map ID, not an + * entity ID. + * + * @managed_by PlayingSystem + */ + size_t checkpointMapId; + double checkpointX; + double checkpointY; }; diff --git a/src/components/ponderable.h b/src/components/ponderable.h index 78af25f..fd7e775 100644 --- a/src/components/ponderable.h +++ b/src/components/ponderable.h @@ -6,100 +6,73 @@ class PonderableComponent : public Component { public: + /** + * List of different types of physical bodies. + * + * vacuumed - Default. + * freefalling - The body will be treated as if there were a downward force + * of gravity being exerted onto it. The body will also exhibit + * terminal velocity (that is, its downward velocity will be + * capped at a constant value). + */ enum class Type { vacuumed, freefalling }; - PonderableComponent(Type type) : type_(type) - { - } - - inline Type getType() const - { - return type_; - } - - inline double getVelocityX() const - { - return velX_; - } - - inline void setVelocityX(double v) - { - velX_ = v; - } - - inline double getVelocityY() const - { - return velY_; - } - - inline void setVelocityY(double v) - { - velY_ = v; - } - - inline double getAccelX() const - { - return accelX_; - } - - inline void setAccelX(double v) - { - accelX_ = v; - } - - inline double getAccelY() const - { - return accelY_; - } - - inline void setAccelY(double v) - { - accelY_ = v; - } - - inline bool isGrounded() const - { - return grounded_; - } - - inline void setGrounded(bool v) - { - grounded_ = v; - } - - inline bool isFrozen() const - { - return frozen_; - } - - inline void setFrozen(bool v) - { - frozen_ = v; - } - - inline bool isCollidable() const - { - return collidable_; - } - - inline void setCollidable(bool v) - { - collidable_ = v; - } - -private: - - double velX_ = 0.0; - double velY_ = 0.0; - double accelX_ = 0.0; - double accelY_ = 0.0; - Type type_ = Type::vacuumed; - bool grounded_ = false; - bool frozen_ = false; - bool collidable_ = true; + /** + * Constructor for initializing the body type, which is a constant. + */ + PonderableComponent(Type type) : type(type) + { + } + + /** + * The velocity of the body. + */ + double velX = 0.0; + double velY = 0.0; + + /** + * The acceleration of the body. + */ + double accelX = 0.0; + double accelY = 0.0; + + /** + * The type of physical body that the entity is meant to assume. The body will + * be acted upon differently based on this. See the enumeration above for more + * details. + * + * @managed_by PonderingSystem + */ + const Type type; + + /** + * Whether or not a freefalling body is in contact with the ground. + * + * @managed_by PonderingSystem + */ + bool grounded = false; + + /** + * If enabled, this will prevent the body from moving. + */ + bool frozen = false; + + /** + * If disabled, collision detection for this body will not be performed and + * other bodies will ignore it. + */ + bool collidable = true; + + /** + * If this flag is disabled, the entity will be ignored by the pondering + * system. + * + * @managed_by RealizingSystem + */ + bool active = false; }; #endif /* end of include guard: TANGIBLE_H_746DB3EE */ diff --git a/src/components/realizable.h b/src/components/realizable.h new file mode 100644 index 0000000..f6a7eb4 --- /dev/null +++ b/src/components/realizable.h @@ -0,0 +1,67 @@ +#ifndef REALIZABLE_H_36D8D71E +#define REALIZABLE_H_36D8D71E + +#include "component.h" +#include +#include +#include "entity_manager.h" + +class RealizableComponent : public Component { +public: + + using id_type = EntityManager::id_type; + + /** + * Path to the XML file containing the world definition. + * + * @managed_by RealizingSystem + */ + std::string worldFile; + + /** + * Starting map and player location for a new game. + * + * @managed_by RealizingSystem + */ + int startingMapId; + int startingX; + int startingY; + + /** + * The set of map entities loaded by this entity. It is only intended for + * there to be one realizable entity, so this should contain all loaded maps. + * The realizable entity has ownership of the loaded maps. + * + * @managed_by RealizingSystem + */ + std::set maps; + + /** + * A lookup table that translates a map ID to the entity representing that + * loaded map. + * + * @managed_by RealizingSystem + */ + std::map entityByMapId; + + /** + * The entity ID of the currently active map. + * + * @managed_by RealizingSystem + */ + id_type activeMap; + + /** + * Whether or not a map has been activated yet. + * + * @managed_by RealizingSystem + */ + bool hasActiveMap = false; + + /** + * The entity ID of the currently active player. + */ + id_type activePlayer; +}; + +#endif /* end of include guard: REALIZABLE_H_36D8D71E */ diff --git a/src/components/transformable.h b/src/components/transformable.h index 6ed2637..3296e49 100644 --- a/src/components/transformable.h +++ b/src/components/transformable.h @@ -6,64 +6,27 @@ class TransformableComponent : public Component { public: - TransformableComponent( - double x, - double y, - int w, - int h) : - x_(x), - y_(y), - w_(w), - h_(h) - { - } - - inline double getX() const - { - return x_; - } - - inline void setX(double v) - { - x_ = v; - } - - inline double getY() const - { - return y_; - } - - inline void setY(double v) - { - y_ = v; - } - - inline int getW() const - { - return w_; - } - - inline void setW(int v) - { - w_ = v; - } - - inline int getH() const - { - return h_; - } - - inline void setH(int v) - { - h_ = v; - } - -private: - - double x_; - double y_; - int w_; - int h_; + /** + * The coordinates of the entity. + */ + double x; + double y; + + /** + * The size of the entity. + */ + int w; + int h; + + /** + * For prototypes, the original coordinates and size of the entity. + * + * @managed_by RealizingSystem + */ + double origX; + double origY; + int origW; + int origH; }; #endif /* end of include guard: LOCATABLE_H_39E526CA */ diff --git a/src/game.cpp b/src/game.cpp index 3da23a3..b7dd200 100644 --- a/src/game.cpp +++ b/src/game.cpp @@ -11,6 +11,7 @@ #include "systems/orienting.h" #include "systems/playing.h" #include "systems/scheduling.h" +#include "systems/realizing.h" #include "animation.h" #include "consts.h" @@ -28,8 +29,9 @@ void key_callback(GLFWwindow* window, int key, int, int action, int) game.systemManager_.input(key, action); } -Game::Game() : world_("res/maps.xml") +Game::Game() { + systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); @@ -38,8 +40,8 @@ Game::Game() : world_("res/maps.xml") systemManager_.emplaceSystem(*this); systemManager_.emplaceSystem(*this); + systemManager_.getSystem().initSingleton("res/maps.xml"); systemManager_.getSystem().initPlayer(); - systemManager_.getSystem().loadMap(world_.getStartingMapId()); glfwSwapInterval(1); glfwSetWindowUserPointer(renderer_.getWindow().getHandle(), this); diff --git a/src/game.h b/src/game.h index 43e08da..92a67d9 100644 --- a/src/game.h +++ b/src/game.h @@ -3,7 +3,6 @@ #include "entity_manager.h" #include "system_manager.h" -#include "world.h" #include "renderer/renderer.h" class Game { @@ -28,11 +27,6 @@ public: return systemManager_; } - inline const World& getWorld() - { - return world_; - } - friend void key_callback( GLFWwindow* window, int key, @@ -45,7 +39,6 @@ private: Renderer renderer_; EntityManager entityManager_; SystemManager systemManager_; - World world_; bool shouldQuit_ = false; }; diff --git a/src/map.h b/src/map.h deleted file mode 100644 index 6fe1e62..0000000 --- a/src/map.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef MAP_H_74055FC0 -#define MAP_H_74055FC0 - -#include -#include -#include -#include -#include - -class Map { -public: - - class Adjacent { - public: - - enum class Type { - wall, - wrap, - warp, - reverse - }; - - Adjacent( - Type type = Type::wall, - int mapId = -1) : - type_(type), - mapId_(mapId) - { - } - - inline Type getType() const - { - return type_; - } - - inline int getMapId() const - { - return mapId_; - } - - private: - - Type type_; - int mapId_; - }; - - Map( - int id, - std::vector tiles, - std::string title, - Adjacent leftAdjacent, - Adjacent rightAdjacent, - Adjacent upAdjacent, - Adjacent downAdjacent) : - id_(id), - tiles_(std::move(tiles)), - title_(std::move(title)), - leftAdjacent_(std::move(leftAdjacent)), - rightAdjacent_(std::move(rightAdjacent)), - upAdjacent_(std::move(upAdjacent)), - downAdjacent_(std::move(downAdjacent)) - { - } - - inline size_t getId() const - { - return id_; - } - - inline const std::vector& getTiles() const - { - return tiles_; - } - - inline const std::string& getTitle() const - { - return title_; - } - - inline const Adjacent& getLeftAdjacent() const - { - return leftAdjacent_; - } - - inline const Adjacent& getRightAdjacent() const - { - return rightAdjacent_; - } - - inline const Adjacent& getUpAdjacent() const - { - return upAdjacent_; - } - - inline const Adjacent& getDownAdjacent() const - { - return downAdjacent_; - } - -private: - - int id_; - std::vector tiles_; - std::string title_; - Adjacent leftAdjacent_; - Adjacent rightAdjacent_; - Adjacent upAdjacent_; - Adjacent downAdjacent_; -}; - -#endif /* end of include guard: MAP_H_74055FC0 */ diff --git a/src/systems/animating.cpp b/src/systems/animating.cpp index 634af67..8543ba2 100644 --- a/src/systems/animating.cpp +++ b/src/systems/animating.cpp @@ -13,26 +13,29 @@ void AnimatingSystem::tick(double) auto& sprite = game_.getEntityManager(). getComponent(entity); - if (!sprite.isFrozen()) + if (sprite.active) { - sprite.setCountdown(sprite.getCountdown() + 1); - } - - const Animation& anim = sprite.getAnimation(); - if (sprite.getCountdown() >= anim.getDelay()) - { - sprite.setFrame(sprite.getFrame() + 1); - sprite.setCountdown(0); + if (!sprite.frozen) + { + sprite.countdown++; + } - if (sprite.getFrame() >= anim.getFirstFrame() + anim.getNumFrames()) + const Animation& anim = sprite.getAnimation(); + if (sprite.countdown >= anim.getDelay()) { - sprite.setFrame(anim.getFirstFrame()); + sprite.frame++; + sprite.countdown = 0; + + if (sprite.frame >= anim.getFirstFrame() + anim.getNumFrames()) + { + sprite.frame = anim.getFirstFrame(); + } } - } - if (sprite.isFlickering()) - { - sprite.setFlickerTimer((sprite.getFlickerTimer() + 1) % 6); + if (sprite.flickering) + { + sprite.flickerTimer = (sprite.flickerTimer + 1) % 6; + } } } } @@ -49,36 +52,52 @@ void AnimatingSystem::render(Texture& texture) auto& sprite = game_.getEntityManager(). getComponent(entity); - auto& transform = game_.getEntityManager(). - getComponent(entity); - - double alpha = 1.0; - if (sprite.isFlickering() && (sprite.getFlickerTimer() < 3)) + if (sprite.active) { - alpha = 0.0; - } + auto& transform = game_.getEntityManager(). + getComponent(entity); - Rectangle dstrect { - static_cast(transform.getX()), - static_cast(transform.getY()), - transform.getW(), - transform.getH()}; - - const AnimationSet& aset = sprite.getAnimationSet(); - game_.getRenderer().blit( - aset.getTexture(), - texture, - aset.getFrameRect(sprite.getFrame()), - dstrect, - alpha); + double alpha = 1.0; + if (sprite.flickering && (sprite.flickerTimer < 3)) + { + alpha = 0.0; + } + + Rectangle dstrect { + static_cast(transform.x), + static_cast(transform.y), + transform.w, + transform.h}; + + const AnimationSet& aset = sprite.animationSet; + game_.getRenderer().blit( + aset.getTexture(), + texture, + aset.getFrameRect(sprite.frame), + dstrect, + alpha); + } } } +void AnimatingSystem::initPrototype(id_type entity) +{ + auto& sprite = game_.getEntityManager(). + getComponent(entity); + + startAnimation(entity, sprite.origAnimation); + + sprite.countdown = 0; + sprite.flickering = false; + sprite.flickerTimer = 0; + sprite.frozen = false; +} + void AnimatingSystem::startAnimation(id_type entity, std::string animation) { auto& sprite = game_.getEntityManager(). getComponent(entity); - sprite.setAnimation(animation); - sprite.setFrame(sprite.getAnimation().getFirstFrame()); + sprite.animation = std::move(animation); + sprite.frame = sprite.getAnimation().getFirstFrame(); } diff --git a/src/systems/animating.h b/src/systems/animating.h index 548bff1..acc6191 100644 --- a/src/systems/animating.h +++ b/src/systems/animating.h @@ -16,6 +16,8 @@ public: void render(Texture& texture); + void initPrototype(id_type entity); + void startAnimation(id_type entity, std::string animation); }; diff --git a/src/systems/mapping.cpp b/src/systems/mapping.cpp index a3a17ec..af67aed 100644 --- a/src/systems/mapping.cpp +++ b/src/systems/mapping.cpp @@ -1,5 +1,7 @@ #include "mapping.h" #include "components/mappable.h" +#include "components/realizable.h" +#include "systems/realizing.h" #include "game.h" #include "consts.h" @@ -18,104 +20,95 @@ inline void addBoundary( void MappingSystem::render(Texture& texture) { - auto entities = game_.getEntityManager().getEntitiesWithComponents< - MappableComponent>(); + auto& realizable = game_.getEntityManager(). + getComponent( + game_.getSystemManager().getSystem().getSingleton()); - for (id_type entity : entities) - { - auto& mappable = game_.getEntityManager(). - getComponent(entity); + id_type map = realizable.activeMap; - const Map& map = game_.getWorld().getMap(mappable.getMapId()); + auto& mappable = game_.getEntityManager(). + getComponent(map); - for (int i = 0; i < MAP_WIDTH * MAP_HEIGHT; i++) - { - int x = i % MAP_WIDTH; - int y = i / MAP_WIDTH; - int tile = map.getTiles()[i]; - - if (tile > 0) - { - Rectangle dst { - x * TILE_WIDTH, - y * TILE_HEIGHT, - TILE_WIDTH, - TILE_HEIGHT}; - - Rectangle src { - (tile % TILESET_COLS) * TILE_WIDTH, - (tile / TILESET_COLS) * TILE_HEIGHT, - TILE_WIDTH, - TILE_HEIGHT}; - - game_.getRenderer().blit( - mappable.getTileset(), - texture, - std::move(src), - std::move(dst)); - } - } + for (int i = 0; i < MAP_WIDTH * MAP_HEIGHT; i++) + { + int x = i % MAP_WIDTH; + int y = i / MAP_WIDTH; + int tile = mappable.tiles[i]; - int startX = ((GAME_WIDTH / TILE_WIDTH) / 2) - (map.getTitle().size() / 2); - for (size_t i = 0; i < map.getTitle().size(); i++) + if (tile > 0) { - Rectangle src { - (map.getTitle()[i] % FONT_COLS) * TILE_WIDTH, - (map.getTitle()[i] / FONT_COLS) * TILE_HEIGHT, + Rectangle dst { + x * TILE_WIDTH, + y * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT}; - Rectangle dst { - (startX + static_cast(i)) * TILE_WIDTH, - 24 * TILE_HEIGHT, + Rectangle src { + (tile % TILESET_COLS) * TILE_WIDTH, + (tile / TILESET_COLS) * TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT}; game_.getRenderer().blit( - mappable.getFont(), + mappable.tileset, texture, std::move(src), std::move(dst)); } } + + int startX = ((GAME_WIDTH / TILE_WIDTH) / 2) - (mappable.title.size() / 2); + + for (size_t i = 0; i < mappable.title.size(); i++) + { + Rectangle src { + (mappable.title[i] % FONT_COLS) * TILE_WIDTH, + (mappable.title[i] / FONT_COLS) * TILE_HEIGHT, + TILE_WIDTH, + TILE_HEIGHT}; + + Rectangle dst { + (startX + static_cast(i)) * TILE_WIDTH, + 24 * TILE_HEIGHT, + TILE_WIDTH, + TILE_HEIGHT}; + + game_.getRenderer().blit( + mappable.font, + texture, + std::move(src), + std::move(dst)); + } } -void MappingSystem::loadMap(size_t mapId) +void MappingSystem::generateBoundaries(id_type mapEntity) { - id_type mapEntity = game_.getEntityManager().emplaceEntity(); - auto& mappable = game_.getEntityManager(). - emplaceComponent(mapEntity, - Texture("res/tiles.png"), - Texture("res/font.bmp")); - - mappable.setMapId(mapId); - - const Map& map = game_.getWorld().getMap(mappable.getMapId()); + getComponent(mapEntity); addBoundary( - mappable.getLeftBoundaries(), + mappable.leftBoundaries, -WALL_GAP, 0, MAP_HEIGHT * TILE_HEIGHT, MappableComponent::Boundary::Type::adjacency); addBoundary( - mappable.getRightBoundaries(), + mappable.rightBoundaries, GAME_WIDTH + WALL_GAP, 0, MAP_HEIGHT * TILE_HEIGHT, MappableComponent::Boundary::Type::adjacency); addBoundary( - mappable.getUpBoundaries(), + mappable.upBoundaries, -WALL_GAP, 0, GAME_WIDTH, MappableComponent::Boundary::Type::adjacency); addBoundary( - mappable.getDownBoundaries(), + mappable.downBoundaries, MAP_HEIGHT * TILE_HEIGHT + WALL_GAP, 0, GAME_WIDTH, @@ -125,12 +118,12 @@ void MappingSystem::loadMap(size_t mapId) { size_t x = i % MAP_WIDTH; size_t y = i / MAP_WIDTH; - int tile = map.getTiles()[i]; + int tile = mappable.tiles[i]; if ((tile >= 5) && (tile <= 7)) { addBoundary( - mappable.getDownBoundaries(), + mappable.downBoundaries, y * TILE_HEIGHT, x * TILE_WIDTH, (x + 1) * TILE_WIDTH, @@ -138,28 +131,28 @@ void MappingSystem::loadMap(size_t mapId) } else if ((tile > 0) && (tile < 28)) { addBoundary( - mappable.getRightBoundaries(), + mappable.rightBoundaries, x * TILE_WIDTH, y * TILE_HEIGHT, (y+1) * TILE_HEIGHT, MappableComponent::Boundary::Type::wall); addBoundary( - mappable.getLeftBoundaries(), + mappable.leftBoundaries, (x+1) * TILE_WIDTH, y * TILE_HEIGHT, (y+1) * TILE_HEIGHT, MappableComponent::Boundary::Type::wall); addBoundary( - mappable.getDownBoundaries(), + mappable.downBoundaries, y * TILE_HEIGHT, x * TILE_WIDTH, (x+1) * TILE_WIDTH, MappableComponent::Boundary::Type::wall); addBoundary( - mappable.getUpBoundaries(), + mappable.upBoundaries, (y+1) * TILE_HEIGHT, x * TILE_WIDTH, (x+1) * TILE_WIDTH, @@ -167,28 +160,28 @@ void MappingSystem::loadMap(size_t mapId) } else if (tile == 42) { addBoundary( - mappable.getRightBoundaries(), + mappable.rightBoundaries, x * TILE_WIDTH, y * TILE_HEIGHT, (y+1) * TILE_HEIGHT, MappableComponent::Boundary::Type::danger); addBoundary( - mappable.getLeftBoundaries(), + mappable.leftBoundaries, (x+1) * TILE_WIDTH, y * TILE_HEIGHT, (y+1) * TILE_HEIGHT, MappableComponent::Boundary::Type::danger); addBoundary( - mappable.getDownBoundaries(), + mappable.downBoundaries, y * TILE_HEIGHT, x * TILE_WIDTH, (x+1) * TILE_WIDTH, MappableComponent::Boundary::Type::danger); addBoundary( - mappable.getUpBoundaries(), + mappable.upBoundaries, (y+1) * TILE_HEIGHT, x * TILE_WIDTH, (x+1) * TILE_WIDTH, diff --git a/src/systems/mapping.h b/src/systems/mapping.h index 53d054b..3c47419 100644 --- a/src/systems/mapping.h +++ b/src/systems/mapping.h @@ -12,7 +12,7 @@ public: void render(Texture& texture); - void loadMap(size_t mapId); + void generateBoundaries(id_type mapEntity); }; diff --git a/src/systems/orienting.cpp b/src/systems/orienting.cpp index 2df8f87..206ebf6 100644 --- a/src/systems/orienting.cpp +++ b/src/systems/orienting.cpp @@ -24,27 +24,27 @@ void OrientingSystem::tick(double) { case OrientableComponent::WalkState::still: { - ponderable.setVelocityX(0); + ponderable.velX = 0.0; break; } case OrientableComponent::WalkState::left: { - ponderable.setVelocityX(-WALK_SPEED); + ponderable.velX = -WALK_SPEED; break; } case OrientableComponent::WalkState::right: { - ponderable.setVelocityX(WALK_SPEED); + ponderable.velX = WALK_SPEED; break; } } - if (orientable.isJumping() && (ponderable.getVelocityY() > 0)) + if (orientable.isJumping() && (ponderable.velY > 0)) { orientable.setJumping(false); } @@ -63,7 +63,7 @@ void OrientingSystem::moveLeft(id_type entity) orientable.setWalkState(OrientableComponent::WalkState::left); auto& animating = game_.getSystemManager().getSystem(); - if (ponderable.isGrounded()) + if (ponderable.grounded) { animating.startAnimation(entity, "walkingLeft"); } else { @@ -83,7 +83,7 @@ void OrientingSystem::moveRight(id_type entity) orientable.setWalkState(OrientableComponent::WalkState::right); auto& animating = game_.getSystemManager().getSystem(); - if (ponderable.isGrounded()) + if (ponderable.grounded) { animating.startAnimation(entity, "walkingRight"); } else { @@ -113,7 +113,7 @@ void OrientingSystem::jump(id_type entity) auto& ponderable = game_.getEntityManager(). getComponent(entity); - if (ponderable.isGrounded()) + if (ponderable.grounded) { auto& orientable = game_.getEntityManager(). getComponent(entity); @@ -122,8 +122,8 @@ void OrientingSystem::jump(id_type entity) playSound("res/Randomize87.wav", 0.25); - ponderable.setVelocityY(JUMP_VELOCITY); - ponderable.setAccelY(JUMP_GRAVITY); + ponderable.velY = JUMP_VELOCITY; + ponderable.accelY = JUMP_GRAVITY; auto& animating = game_.getSystemManager().getSystem(); if (orientable.isFacingRight()) @@ -147,7 +147,7 @@ void OrientingSystem::stopJumping(id_type entity) auto& ponderable = game_.getEntityManager(). getComponent(entity); - ponderable.setAccelY(NORMAL_GRAVITY); + ponderable.accelY = NORMAL_GRAVITY; } } @@ -211,7 +211,7 @@ void OrientingSystem::drop(id_type entity) auto& ponderable = game_.getEntityManager(). getComponent(entity); - if (ponderable.isGrounded() + if (ponderable.grounded && (orientable.getDropState() == OrientableComponent::DropState::none)) { orientable.setDropState(OrientableComponent::DropState::ready); diff --git a/src/systems/playing.cpp b/src/systems/playing.cpp index 40d9706..b04f0cb 100644 --- a/src/systems/playing.cpp +++ b/src/systems/playing.cpp @@ -5,61 +5,17 @@ #include "components/playable.h" #include "components/controllable.h" #include "components/orientable.h" +#include "components/realizable.h" #include "systems/mapping.h" #include "systems/pondering.h" #include "systems/orienting.h" #include "systems/scheduling.h" #include "systems/controlling.h" +#include "systems/animating.h" +#include "systems/realizing.h" #include "animation.h" #include "muxer.h" -void PlayingSystem::tick(double) -{ - // Check if we need to change the map - auto players = game_.getEntityManager().getEntitiesWithComponents< - PlayableComponent, - TransformableComponent>(); - - for (id_type player : players) - { - auto& playable = game_.getEntityManager(). - getComponent(player); - - if (playable.changingMap) - { - // Change the map! - auto entities = game_.getEntityManager().getEntities(); - - for (id_type entity : entities) - { - if (entity != player) - { - game_.getEntityManager().deleteEntity(entity); - } - } - - game_.getSystemManager().getSystem(). - loadMap(playable.newMapId); - - auto& transformable = game_.getEntityManager(). - getComponent(player); - - transformable.setX(playable.newMapX); - transformable.setY(playable.newMapY); - - playable.changingMap = false; - - if (playable.newMapCallback) - { - playable.newMapCallback(); - playable.newMapCallback = nullptr; - } - - break; - } - } -} - void PlayingSystem::initPlayer() { id_type player = game_.getEntityManager().emplaceEntity(); @@ -72,15 +28,24 @@ void PlayingSystem::initPlayer() game_.getEntityManager().emplaceComponent( player, - std::move(playerGraphics), - "stillLeft"); + std::move(playerGraphics)); - game_.getEntityManager().emplaceComponent( + game_.getSystemManager().getSystem().startAnimation( player, - game_.getWorld().getStartingX(), - game_.getWorld().getStartingY(), - 10, - 12); + "stillLeft"); + + auto& realizing = game_.getSystemManager().getSystem(); + + auto& realizable = game_.getEntityManager(). + getComponent(realizing.getSingleton()); + + auto& transformable = game_.getEntityManager(). + emplaceComponent(player); + + transformable.x = realizable.startingX; + transformable.y = realizable.startingY; + transformable.w = 10; + transformable.h = 12; game_.getSystemManager().getSystem().initializeBody( player, @@ -92,84 +57,103 @@ void PlayingSystem::initPlayer() auto& playable = game_.getEntityManager(). emplaceComponent(player); - playable.checkpointMapId = game_.getWorld().getStartingMapId(); - playable.checkpointX = game_.getWorld().getStartingX(); - playable.checkpointY = game_.getWorld().getStartingY(); + playable.mapId = realizable.activeMap; + playable.checkpointMapId = realizable.startingMapId; + playable.checkpointX = realizable.startingX; + playable.checkpointY = realizable.startingY; + + realizing.enterActiveMap(player); + + realizable.activePlayer = player; } void PlayingSystem::changeMap( + id_type player, size_t mapId, double x, - double y, - PlayableComponent::MapChangeCallback callback) + double y) { - auto players = game_.getEntityManager().getEntitiesWithComponents< - PlayableComponent>(); + auto& playable = game_.getEntityManager(). + getComponent(player); - for (id_type player : players) + auto& transformable = game_.getEntityManager(). + getComponent(player); + + auto& animatable = game_.getEntityManager(). + getComponent(player); + + auto& ponderable = game_.getEntityManager(). + getComponent(player); + + auto& realizing = game_.getSystemManager().getSystem(); + + auto& realizable = game_.getEntityManager(). + getComponent(realizing.getSingleton()); + + id_type newMapEntity = realizable.entityByMapId[mapId]; + + if (playable.mapId != newMapEntity) { - auto& playable = game_.getEntityManager(). - getComponent(player); + if (playable.mapId == realizable.activeMap) + { + realizing.leaveActiveMap(player); + } else if (newMapEntity == realizable.activeMap) + { + realizing.enterActiveMap(player); + } - playable.changingMap = true; - playable.newMapId = mapId; - playable.newMapX = x; - playable.newMapY = y; - playable.newMapCallback = std::move(callback); + playable.mapId = newMapEntity; + } + + transformable.x = x; + transformable.y = y; + + if (realizable.activePlayer == player) + { + realizing.loadMap(newMapEntity); } } -void PlayingSystem::die() +void PlayingSystem::die(id_type player) { playSound("res/Hit_Hurt5.wav", 0.25); - auto players = game_.getEntityManager().getEntitiesWithComponents< - OrientableComponent, - ControllableComponent, - AnimatableComponent, - PonderableComponent, - PlayableComponent>(); + auto& animatable = game_.getEntityManager(). + getComponent(player); - for (id_type player : players) - { - auto& animatable = game_.getEntityManager(). - getComponent(player); - - auto& ponderable = game_.getEntityManager(). - getComponent(player); - - auto& controlling = game_.getSystemManager().getSystem(); - controlling.freeze(player); - - animatable.setFrozen(true); - animatable.setFlickering(true); - ponderable.setFrozen(true); - ponderable.setCollidable(false); - - auto& scheduling = game_.getSystemManager().getSystem(); - - scheduling.schedule(player, 0.75, [&] (id_type player) { - auto& playable = game_.getEntityManager(). - getComponent(player); - - changeMap( - playable.checkpointMapId, - playable.checkpointX, - playable.checkpointY, - [&, player] () { - animatable.setFrozen(false); - animatable.setFlickering(false); - ponderable.setFrozen(false); - ponderable.setCollidable(true); - - // Reset the walk state, and then potentially let the - // ControllingSystem set it again. - auto& orienting = game_.getSystemManager(). - getSystem(); - orienting.stopWalking(player); - - controlling.unfreeze(player); - }); - }); - } + auto& ponderable = game_.getEntityManager(). + getComponent(player); + + auto& controlling = game_.getSystemManager().getSystem(); + controlling.freeze(player); + + animatable.frozen = true; + animatable.flickering = true; + ponderable.frozen = true; + ponderable.collidable = false; + + auto& scheduling = game_.getSystemManager().getSystem(); + + scheduling.schedule(player, 0.75, [&] (id_type player) { + auto& playable = game_.getEntityManager(). + getComponent(player); + + changeMap( + player, + playable.checkpointMapId, + playable.checkpointX, + playable.checkpointY); + + animatable.frozen = false; + animatable.flickering = false; + ponderable.frozen = false; + ponderable.collidable = true; + + // Reset the walk state, and then potentially let the + // ControllingSystem set it again. + auto& orienting = game_.getSystemManager().getSystem(); + orienting.stopWalking(player); + + controlling.unfreeze(player); + }); } diff --git a/src/systems/playing.h b/src/systems/playing.h index ff16808..9ba403b 100644 --- a/src/systems/playing.h +++ b/src/systems/playing.h @@ -2,7 +2,6 @@ #define PLAYING_H_70A54F7D #include "system.h" -#include "components/playable.h" class PlayingSystem : public System { public: @@ -11,17 +10,15 @@ public: { } - void tick(double dt); - void initPlayer(); void changeMap( + id_type player, size_t mapId, double x, - double y, - PlayableComponent::MapChangeCallback callback = nullptr); + double y); - void die(); + void die(id_type player); }; diff --git a/src/systems/pondering.cpp b/src/systems/pondering.cpp index 02d5cfc..4ae6176 100644 --- a/src/systems/pondering.cpp +++ b/src/systems/pondering.cpp @@ -5,149 +5,153 @@ #include "components/transformable.h" #include "components/orientable.h" #include "components/mappable.h" +#include "components/realizable.h" +#include "components/playable.h" #include "systems/orienting.h" #include "systems/playing.h" +#include "systems/realizing.h" #include "consts.h" #include "collision.h" void PonderingSystem::tick(double dt) { + auto& realizable = game_.getEntityManager(). + getComponent( + game_.getSystemManager().getSystem().getSingleton()); + + id_type mapEntity = realizable.activeMap; + + auto& mappable = game_.getEntityManager(). + getComponent(mapEntity); + auto entities = game_.getEntityManager().getEntitiesWithComponents< PonderableComponent, TransformableComponent>(); - auto maps = game_.getEntityManager().getEntitiesWithComponents< - MappableComponent>(); - for (id_type entity : entities) { - auto& transformable = game_.getEntityManager(). - getComponent(entity); - auto& ponderable = game_.getEntityManager(). getComponent(entity); - if (ponderable.isFrozen()) + if (!ponderable.active || ponderable.frozen) { continue; } - // Accelerate - ponderable.setVelocityX( - ponderable.getVelocityX() + ponderable.getAccelX() * dt); + auto& transformable = game_.getEntityManager(). + getComponent(entity); - ponderable.setVelocityY( - ponderable.getVelocityY() + ponderable.getAccelY() * dt); + // Accelerate + ponderable.velX += ponderable.accelX * dt; + ponderable.velY += ponderable.accelY * dt; - if ((ponderable.getType() == PonderableComponent::Type::freefalling) - && (ponderable.getVelocityY() > TERMINAL_VELOCITY)) + if ((ponderable.type == PonderableComponent::Type::freefalling) + && (ponderable.velY > TERMINAL_VELOCITY)) { - ponderable.setVelocityY(TERMINAL_VELOCITY); + ponderable.velY = TERMINAL_VELOCITY; } - const double oldX = transformable.getX(); - const double oldY = transformable.getY(); - const double oldRight = oldX + transformable.getW(); - const double oldBottom = oldY + transformable.getH(); + const double oldX = transformable.x; + const double oldY = transformable.y; + const double oldRight = oldX + transformable.w; + const double oldBottom = oldY + transformable.h; - double newX = oldX + ponderable.getVelocityX() * dt; - double newY = oldY + ponderable.getVelocityY() * dt; + double newX = oldX + ponderable.velX * dt; + double newY = oldY + ponderable.velY * dt; - bool oldGrounded = ponderable.isGrounded(); - ponderable.setGrounded(false); + bool oldGrounded = ponderable.grounded; + ponderable.grounded = false; std::priority_queue collisions; // Find collisions - for (id_type mapEntity : maps) + if (newX < oldX) { - auto& mappable = game_.getEntityManager(). - getComponent(mapEntity); - - if (newX < oldX) + for (auto it = mappable.leftBoundaries.lower_bound(oldX); + (it != std::end(mappable.leftBoundaries)) && (it->first >= newX); + it++) { - for (auto it = mappable.getLeftBoundaries().lower_bound(oldX); - (it != std::end(mappable.getLeftBoundaries())) && (it->first >= newX); - it++) + if ((oldBottom > it->second.lower) + && (oldY < it->second.upper)) { - if ((oldBottom > it->second.getLower()) - && (oldY < it->second.getUpper())) - { - // We have a collision! - collisions.emplace( - mapEntity, - Direction::left, - it->second.getType(), - it->first, - it->second.getLower(), - it->second.getUpper()); - } + // We have a collision! + collisions.emplace( + mapEntity, + Direction::left, + it->second.type, + it->first, + it->second.lower, + it->second.upper); } - } else if (newX > oldX) + } + } else if (newX > oldX) + { + for (auto it = mappable.rightBoundaries.lower_bound(oldRight); + (it != std::end(mappable.rightBoundaries)) + && (it->first <= (newX + transformable.w)); + it++) { - for (auto it = mappable.getRightBoundaries().lower_bound(oldRight); - (it != std::end(mappable.getRightBoundaries())) - && (it->first <= (newX + transformable.getW())); - it++) + if ((oldBottom > it->second.lower) + && (oldY < it->second.upper)) { - if ((oldBottom > it->second.getLower()) - && (oldY < it->second.getUpper())) - { - // We have a collision! - collisions.emplace( - mapEntity, - Direction::right, - it->second.getType(), - it->first, - it->second.getLower(), - it->second.getUpper()); - } + // We have a collision! + collisions.emplace( + mapEntity, + Direction::right, + it->second.type, + it->first, + it->second.lower, + it->second.upper); } } + } - if (newY < oldY) + if (newY < oldY) + { + for (auto it = mappable.upBoundaries.lower_bound(oldY); + (it != std::end(mappable.upBoundaries)) && (it->first >= newY); + it++) { - for (auto it = mappable.getUpBoundaries().lower_bound(oldY); - (it != std::end(mappable.getUpBoundaries())) && (it->first >= newY); - it++) + if ((oldRight > it->second.lower) + && (oldX < it->second.upper)) { - if ((oldRight > it->second.getLower()) - && (oldX < it->second.getUpper())) - { - // We have a collision! - collisions.emplace( - mapEntity, - Direction::up, - it->second.getType(), - it->first, - it->second.getLower(), - it->second.getUpper()); - } + // We have a collision! + collisions.emplace( + mapEntity, + Direction::up, + it->second.type, + it->first, + it->second.lower, + it->second.upper); } - } else if (newY > oldY) + } + } else if (newY > oldY) + { + for (auto it = mappable.downBoundaries.lower_bound(oldBottom); + (it != std::end(mappable.downBoundaries)) + && (it->first <= (newY + transformable.h)); + it++) { - for (auto it = mappable.getDownBoundaries().lower_bound(oldBottom); - (it != std::end(mappable.getDownBoundaries())) - && (it->first <= (newY + transformable.getH())); - it++) + if ((oldRight > it->second.lower) + && (oldX < it->second.upper)) { - if ((oldRight > it->second.getLower()) - && (oldX < it->second.getUpper())) - { - // We have a collision! - collisions.emplace( - mapEntity, - Direction::down, - it->second.getType(), - it->first, - it->second.getLower(), - it->second.getUpper()); - } + // We have a collision! + collisions.emplace( + mapEntity, + Direction::down, + it->second.type, + it->first, + it->second.lower, + it->second.upper); } } } // Process collisions in order of priority + bool adjacentlyWarping = false; + Direction adjWarpDir; + size_t adjWarpMapId; + while (!collisions.empty()) { Collision collision = collisions.top(); @@ -157,8 +161,8 @@ void PonderingSystem::tick(double dt) if (!collision.isColliding( newX, newY, - transformable.getW(), - transformable.getH())) + transformable.w, + transformable.h)) { continue; } @@ -201,33 +205,33 @@ void PonderingSystem::tick(double dt) { auto& mappable = game_.getEntityManager(). getComponent(collision.getCollider()); - const Map& map = game_.getWorld().getMap(mappable.getMapId()); - auto& adj = [&] () -> const Map::Adjacent& { + + auto& adj = [&] () -> const MappableComponent::Adjacent& { switch (collision.getDirection()) { - case Direction::left: return map.getLeftAdjacent(); - case Direction::right: return map.getRightAdjacent(); - case Direction::up: return map.getUpAdjacent(); - case Direction::down: return map.getDownAdjacent(); + case Direction::left: return mappable.leftAdjacent; + case Direction::right: return mappable.rightAdjacent; + case Direction::up: return mappable.upAdjacent; + case Direction::down: return mappable.downAdjacent; } }(); - switch (adj.getType()) + switch (adj.type) { - case Map::Adjacent::Type::wall: + case MappableComponent::Adjacent::Type::wall: { touchedWall = true; break; } - case Map::Adjacent::Type::wrap: + case MappableComponent::Adjacent::Type::wrap: { switch (collision.getDirection()) { case Direction::left: { - newX = GAME_WIDTH + WALL_GAP - transformable.getW(); + newX = GAME_WIDTH + WALL_GAP - transformable.w; break; } @@ -241,8 +245,7 @@ void PonderingSystem::tick(double dt) case Direction::up: { - newY = MAP_HEIGHT * TILE_HEIGHT + WALL_GAP - - transformable.getH(); + newY = MAP_HEIGHT * TILE_HEIGHT + WALL_GAP - transformable.h; break; } @@ -256,46 +259,22 @@ void PonderingSystem::tick(double dt) } } - case Map::Adjacent::Type::warp: + case MappableComponent::Adjacent::Type::warp: { - double warpX = newX; - double warpY = newY; - - switch (collision.getDirection()) + if (game_.getEntityManager(). + hasComponent(entity)) { - case Direction::left: - { - warpX = GAME_WIDTH + WALL_GAP - transformable.getW(); - - break; - } - - case Direction::right: - { - warpX = -WALL_GAP; - - break; - } - - case Direction::up: - { - warpY = MAP_HEIGHT * TILE_HEIGHT - transformable.getH(); - - break; - } - - case Direction::down: - { - warpY = -WALL_GAP; - - break; - } + adjacentlyWarping = true; + adjWarpDir = collision.getDirection(); + adjWarpMapId = adj.mapId; } - game_.getSystemManager().getSystem(). - changeMap(adj.getMapId(), warpX, warpY); + break; + } - stopProcessing = true; + case MappableComponent::Adjacent::Type::reverse: + { + // TODO: not yet implemented. break; } @@ -306,7 +285,13 @@ void PonderingSystem::tick(double dt) case Collision::Type::danger: { - game_.getSystemManager().getSystem().die(); + if (game_.getEntityManager(). + hasComponent(entity)) + { + game_.getSystemManager().getSystem().die(entity); + + adjacentlyWarping = false; + } stopProcessing = true; @@ -333,15 +318,15 @@ void PonderingSystem::tick(double dt) case Direction::left: { newX = collision.getAxis(); - ponderable.setVelocityX(0.0); + ponderable.velX = 0.0; break; } case Direction::right: { - newX = collision.getAxis() - transformable.getW(); - ponderable.setVelocityX(0.0); + newX = collision.getAxis() - transformable.w; + ponderable.velX = 0.0; break; } @@ -349,16 +334,16 @@ void PonderingSystem::tick(double dt) case Direction::up: { newY = collision.getAxis(); - ponderable.setVelocityY(0.0); + ponderable.velY = 0.0; break; } case Direction::down: { - newY = collision.getAxis() - transformable.getH(); - ponderable.setVelocityY(0.0); - ponderable.setGrounded(true); + newY = collision.getAxis() - transformable.h; + ponderable.velY = 0.0; + ponderable.grounded = true; break; } @@ -367,8 +352,8 @@ void PonderingSystem::tick(double dt) } // Move - transformable.setX(newX); - transformable.setY(newY); + transformable.x = newX; + transformable.y = newY; // Perform cleanup for orientable entites if (game_.getEntityManager().hasComponent(entity)) @@ -377,9 +362,9 @@ void PonderingSystem::tick(double dt) getComponent(entity); // Handle changes in groundedness - if (ponderable.isGrounded() != oldGrounded) + if (ponderable.grounded != oldGrounded) { - if (ponderable.isGrounded()) + if (ponderable.grounded) { game_.getSystemManager().getSystem().land(entity); } else { @@ -394,6 +379,51 @@ void PonderingSystem::tick(double dt) orientable.setDropState(OrientableComponent::DropState::none); } } + + // Move to an adjacent map, if necessary + if (adjacentlyWarping) + { + double warpX = newX; + double warpY = newY; + + switch (adjWarpDir) + { + case Direction::left: + { + warpX = GAME_WIDTH + WALL_GAP - transformable.w; + + break; + } + + case Direction::right: + { + warpX = -WALL_GAP; + + break; + } + + case Direction::up: + { + warpY = MAP_HEIGHT * TILE_HEIGHT - transformable.h; + + break; + } + + case Direction::down: + { + warpY = -WALL_GAP; + + break; + } + } + + game_.getSystemManager().getSystem(). + changeMap( + entity, + adjWarpMapId, + warpX, + warpY); + } } } @@ -406,6 +436,20 @@ void PonderingSystem::initializeBody( if (type == PonderableComponent::Type::freefalling) { - ponderable.setAccelY(NORMAL_GRAVITY); + ponderable.accelY = NORMAL_GRAVITY; } } + +void PonderingSystem::initPrototype(id_type prototype) +{ + auto& ponderable = game_.getEntityManager(). + getComponent(prototype); + + ponderable.velX = 0.0; + ponderable.velY = 0.0; + ponderable.accelX = 0.0; + ponderable.accelY = 0.0; + ponderable.grounded = false; + ponderable.frozen = false; + ponderable.collidable = true; +} diff --git a/src/systems/pondering.h b/src/systems/pondering.h index d70525b..58e6496 100644 --- a/src/systems/pondering.h +++ b/src/systems/pondering.h @@ -16,6 +16,8 @@ public: void initializeBody(id_type entity, PonderableComponent::Type type); + void initPrototype(id_type prototype); + }; #endif /* end of include guard: PONDERING_H_F2530E0E */ diff --git a/src/systems/realizing.cpp b/src/systems/realizing.cpp new file mode 100644 index 0000000..09c38f3 --- /dev/null +++ b/src/systems/realizing.cpp @@ -0,0 +1,321 @@ +#include "realizing.h" +#include +#include +#include +#include "game.h" +#include "consts.h" +#include "components/realizable.h" +#include "components/mappable.h" +#include "components/animatable.h" +#include "components/playable.h" +#include "components/ponderable.h" +#include "components/transformable.h" +#include "systems/mapping.h" +#include "systems/animating.h" +#include "systems/pondering.h" + +inline xmlChar* getProp(xmlNodePtr node, const char* attr) +{ + xmlChar* key = xmlGetProp(node, reinterpret_cast(attr)); + if (key == nullptr) + { + throw std::invalid_argument("Error parsing world file"); + } + + return key; +} + +// TODO: neither the XML doc nor any of the emplaced entities are properly +// destroyed if this method throws an exception. +EntityManager::id_type RealizingSystem::initSingleton(std::string filename) +{ + id_type world = game_.getEntityManager().emplaceEntity(); + + auto& realizable = game_.getEntityManager(). + emplaceComponent(world); + + auto& mapping = game_.getSystemManager().getSystem(); + + xmlDocPtr doc = xmlParseFile(filename.c_str()); + if (doc == nullptr) + { + throw std::invalid_argument("Cannot find world file"); + } + + xmlNodePtr top = xmlDocGetRootElement(doc); + if (top == nullptr) + { + throw std::invalid_argument("Error parsing world file"); + } + + if (xmlStrcmp(top->name, reinterpret_cast("world"))) + { + throw std::invalid_argument("Error parsing world file"); + } + + xmlChar* key = nullptr; + + key = getProp(top, "startx"); + realizable.startingX = atoi(reinterpret_cast(key)); + xmlFree(key); + + key = getProp(top, "starty"); + realizable.startingY = atoi(reinterpret_cast(key)); + xmlFree(key); + + key = getProp(top, "startmap"); + realizable.startingMapId = atoi(reinterpret_cast(key)); + xmlFree(key); + + for (xmlNodePtr node = top->xmlChildrenNode; + node != nullptr; + node = node->next) + { + if (!xmlStrcmp(node->name, reinterpret_cast("map"))) + { + id_type map = game_.getEntityManager().emplaceEntity(); + + auto& mappable = game_.getEntityManager(). + emplaceComponent(map, + Texture("res/tiles.png"), + Texture("res/font.bmp")); + + key = getProp(node, "id"); + mappable.mapId = atoi(reinterpret_cast(key)); + xmlFree(key); + + key = getProp(node, "title"); + mappable.title = reinterpret_cast(key); + xmlFree(key); + + for (xmlNodePtr mapNode = node->xmlChildrenNode; + mapNode != nullptr; + mapNode = mapNode->next) + { + if (!xmlStrcmp( + mapNode->name, + reinterpret_cast("environment"))) + { + key = xmlNodeGetContent(mapNode); + if (key == nullptr) + { + throw std::invalid_argument("Error parsing world file"); + } + + mappable.tiles.clear(); + mappable.tiles.push_back(atoi(strtok( + reinterpret_cast(key), + ",\n"))); + + for (size_t i = 1; i < (MAP_WIDTH * MAP_HEIGHT); i++) + { + mappable.tiles.push_back(atoi(strtok(nullptr, ",\n"))); + } + + xmlFree(key); + } else if (!xmlStrcmp( + mapNode->name, + reinterpret_cast("adjacent"))) + { + key = getProp(mapNode, "type"); + std::string adjTypeStr(reinterpret_cast(key)); + xmlFree(key); + + MappableComponent::Adjacent::Type adjType; + if (adjTypeStr == "wall") + { + adjType = MappableComponent::Adjacent::Type::wall; + } else if (adjTypeStr == "wrap") + { + adjType = MappableComponent::Adjacent::Type::wrap; + } else if (adjTypeStr == "warp") + { + adjType = MappableComponent::Adjacent::Type::warp; + } else if (adjTypeStr == "reverseWarp") + { + adjType = MappableComponent::Adjacent::Type::reverse; + } else { + throw std::logic_error("Invalid adjacency type"); + } + + key = getProp(mapNode, "map"); + size_t adjMapId = atoi(reinterpret_cast(key)); + xmlFree(key); + + key = getProp(mapNode, "dir"); + std::string adjDir(reinterpret_cast(key)); + xmlFree(key); + + if (adjDir == "left") + { + mappable.leftAdjacent = {adjType, adjMapId}; + } else if (adjDir == "right") + { + mappable.rightAdjacent = {adjType, adjMapId}; + } else if (adjDir == "up") + { + mappable.upAdjacent = {adjType, adjMapId}; + } else if (adjDir == "down") + { + mappable.downAdjacent = {adjType, adjMapId}; + } else { + throw std::logic_error("Invalid adjacency direction"); + } + } + } + + mapping.generateBoundaries(map); + + realizable.maps.insert(map); + realizable.entityByMapId[mappable.mapId] = map; + } + } + + xmlFreeDoc(doc); + + loadMap(realizable.entityByMapId[realizable.startingMapId]); + + return world; +} + +EntityManager::id_type RealizingSystem::getSingleton() const +{ + std::set result = + game_.getEntityManager().getEntitiesWithComponents< + RealizableComponent>(); + + if (result.empty()) + { + throw std::logic_error("No realizable entity found"); + } else if (result.size() > 1) + { + throw std::logic_error("Multiple realizable entities found"); + } + + return *std::begin(result); +} + +void RealizingSystem::loadMap(id_type mapEntity) +{ + id_type world = getSingleton(); + + auto& realizable = game_.getEntityManager(). + getComponent(world); + + auto& animating = game_.getSystemManager().getSystem(); + auto& pondering = game_.getSystemManager().getSystem(); + + std::set players = + game_.getEntityManager().getEntitiesWithComponents< + PlayableComponent>(); + + if (realizable.hasActiveMap) + { + id_type oldMap = realizable.activeMap; + + auto& oldMappable = game_.getEntityManager(). + getComponent(oldMap); + + // Deactivate any map objects from the old map. + for (id_type prototype : oldMappable.objects) + { + leaveActiveMap(prototype); + } + + // Deactivate players that were on the old map. + for (id_type player : players) + { + auto& playable = game_.getEntityManager(). + getComponent(player); + + if (playable.mapId == oldMap) + { + leaveActiveMap(player); + } + } + } + + realizable.hasActiveMap = true; + realizable.activeMap = mapEntity; + + auto& mappable = game_.getEntityManager(). + getComponent(mapEntity); + + // Initialize the new map's objects. + for (id_type prototype : mappable.objects) + { + if (game_.getEntityManager(). + hasComponent(prototype)) + { + auto& transformable = game_.getEntityManager(). + getComponent(prototype); + + transformable.x = transformable.origX; + transformable.y = transformable.origY; + transformable.w = transformable.origW; + transformable.h = transformable.origH; + } + + if (game_.getEntityManager().hasComponent(prototype)) + { + animating.initPrototype(prototype); + } + + if (game_.getEntityManager().hasComponent(prototype)) + { + pondering.initPrototype(prototype); + } + + enterActiveMap(prototype); + } + + // Activate any players on the map. + for (id_type player : players) + { + auto& playable = game_.getEntityManager(). + getComponent(player); + + if (playable.mapId == mapEntity) + { + enterActiveMap(player); + } + } +} + +void RealizingSystem::enterActiveMap(id_type entity) +{ + if (game_.getEntityManager().hasComponent(entity)) + { + auto& animatable = game_.getEntityManager(). + getComponent(entity); + + animatable.active = true; + } + + if (game_.getEntityManager().hasComponent(entity)) + { + auto& ponderable = game_.getEntityManager(). + getComponent(entity); + + ponderable.active = true; + } +} + +void RealizingSystem::leaveActiveMap(id_type entity) +{ + if (game_.getEntityManager().hasComponent(entity)) + { + auto& animatable = game_.getEntityManager(). + getComponent(entity); + + animatable.active = false; + } + + if (game_.getEntityManager().hasComponent(entity)) + { + auto& ponderable = game_.getEntityManager(). + getComponent(entity); + + ponderable.active = false; + } +} diff --git a/src/systems/realizing.h b/src/systems/realizing.h new file mode 100644 index 0000000..c681892 --- /dev/null +++ b/src/systems/realizing.h @@ -0,0 +1,43 @@ +#ifndef REALIZING_H_6853748C +#define REALIZING_H_6853748C + +#include "system.h" + +class RealizingSystem : public System { +public: + + RealizingSystem(Game& game) : System(game) + { + } + + /** + * Creates the singleton realizable entity and initializes it with the + * provided world definition. + */ + id_type initSingleton(std::string filename); + + /** + * Helper method that returns the entity ID of the (assumed) singleton entity + * with a RealizableComponent. Throws an exception if the number of realizable + * entities is not exactly one. + */ + id_type getSingleton() const; + + /** + * Loads the given map. + */ + void loadMap(id_type mapEntity); + + /** + * Treats the given entity as part of the active map. + */ + void enterActiveMap(id_type entity); + + /** + * Stops treating the given entity as part of the active map. + */ + void leaveActiveMap(id_type entity); + +}; + +#endif /* end of include guard: REALIZING_H_6853748C */ diff --git a/src/world.cpp b/src/world.cpp deleted file mode 100644 index 3b6bd41..0000000 --- a/src/world.cpp +++ /dev/null @@ -1,155 +0,0 @@ -#include "world.h" -#include -#include -#include -#include "consts.h" - -inline xmlChar* getProp(xmlNodePtr node, const char* attr) -{ - xmlChar* key = xmlGetProp(node, reinterpret_cast(attr)); - if (key == nullptr) - { - throw std::invalid_argument("Error parsing world file"); - } - - return key; -} - -World::World(std::string filename) -{ - xmlDocPtr doc = xmlParseFile(filename.c_str()); - if (doc == nullptr) - { - throw std::invalid_argument("Cannot find world file"); - } - - xmlNodePtr top = xmlDocGetRootElement(doc); - if (top == nullptr) - { - throw std::invalid_argument("Error parsing world file"); - } - - if (xmlStrcmp(top->name, reinterpret_cast("world"))) - { - throw std::invalid_argument("Error parsing world file"); - } - - xmlChar* key = nullptr; - - key = getProp(top, "startx"); - startX_ = atoi(reinterpret_cast(key)); - xmlFree(key); - - key = getProp(top, "starty"); - startY_ = atoi(reinterpret_cast(key)); - xmlFree(key); - - key = getProp(top, "startmap"); - startMap_ = atoi(reinterpret_cast(key)); - xmlFree(key); - - for (xmlNodePtr node = top->xmlChildrenNode; - node != nullptr; - node = node->next) - { - if (!xmlStrcmp(node->name, reinterpret_cast("map"))) - { - key = getProp(node, "id"); - size_t mapId = atoi(reinterpret_cast(key)); - xmlFree(key); - - key = getProp(node, "title"); - std::string mapTitle(reinterpret_cast(key)); - xmlFree(key); - - std::vector mapTiles; - Map::Adjacent leftAdj; - Map::Adjacent rightAdj; - Map::Adjacent upAdj; - Map::Adjacent downAdj; - - for (xmlNodePtr mapNode = node->xmlChildrenNode; - mapNode != nullptr; - mapNode = mapNode->next) - { - if (!xmlStrcmp( - mapNode->name, - reinterpret_cast("environment"))) - { - key = xmlNodeGetContent(mapNode); - - mapTiles.clear(); - mapTiles.push_back(atoi(strtok(reinterpret_cast(key), ",\n"))); - for (size_t i = 1; i < (MAP_WIDTH * MAP_HEIGHT); i++) - { - mapTiles.push_back(atoi(strtok(nullptr, ",\n"))); - } - - xmlFree(key); - } else if (!xmlStrcmp( - mapNode->name, - reinterpret_cast("adjacent"))) - { - key = getProp(mapNode, "type"); - std::string adjTypeStr(reinterpret_cast(key)); - xmlFree(key); - - Map::Adjacent::Type adjType; - if (adjTypeStr == "wall") - { - adjType = Map::Adjacent::Type::wall; - } else if (adjTypeStr == "wrap") - { - adjType = Map::Adjacent::Type::wrap; - } else if (adjTypeStr == "warp") - { - adjType = Map::Adjacent::Type::warp; - } else if (adjTypeStr == "reverseWarp") - { - adjType = Map::Adjacent::Type::reverse; - } else { - throw std::logic_error("Invalid adjacency type"); - } - - key = getProp(mapNode, "map"); - int adjMapId = atoi(reinterpret_cast(key)); - xmlFree(key); - - key = getProp(mapNode, "dir"); - std::string adjDir(reinterpret_cast(key)); - xmlFree(key); - - if (adjDir == "left") - { - leftAdj = {adjType, adjMapId}; - } else if (adjDir == "right") - { - rightAdj = {adjType, adjMapId}; - } else if (adjDir == "up") - { - upAdj = {adjType, adjMapId}; - } else if (adjDir == "down") - { - downAdj = {adjType, adjMapId}; - } else { - throw std::logic_error("Invalid adjacency direction"); - } - } - } - - maps_.emplace( - std::piecewise_construct, - std::forward_as_tuple(mapId), - std::forward_as_tuple( - mapId, - std::move(mapTiles), - std::move(mapTitle), - leftAdj, - rightAdj, - upAdj, - downAdj)); - } - } - - xmlFreeDoc(doc); -} diff --git a/src/world.h b/src/world.h deleted file mode 100644 index b88adf4..0000000 --- a/src/world.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef WORLD_H_153C698B -#define WORLD_H_153C698B - -#include -#include -#include "map.h" - -class World { -public: - - explicit World(std::string filename); - - inline const Map& getMap(size_t id) const - { - return maps_.at(id); - } - - inline size_t getStartingMapId() const - { - return startMap_; - } - - inline int getStartingX() const - { - return startX_; - } - - inline int getStartingY() const - { - return startY_; - } - -private: - - std::map maps_; - size_t startMap_; - int startX_; - int startY_; -}; - -#endif /* end of include guard: WORLD_H_153C698B */ -- cgit 1.4.1 From ff99cefc647f9215ad1cdc9f408c9fc655b45706 Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Fri, 4 May 2018 10:26:07 -0400 Subject: Added a comment to TransformableComponent describing the ferrying stipulation --- src/components/transformable.h | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src/components/transformable.h') diff --git a/src/components/transformable.h b/src/components/transformable.h index 3296e49..6f3c2ef 100644 --- a/src/components/transformable.h +++ b/src/components/transformable.h @@ -8,6 +8,12 @@ public: /** * The coordinates of the entity. + * + * Note that ponderable entities sometimes have special behavior related to + * their coordinates, specifically that ferried bodies will behave oddly if + * their coordinates are changed outside of the PonderingSystem. Before doing + * so, use PonderingSystem::unferry on the body to ensure that it is not + * ferried. */ double x; double y; -- cgit 1.4.1 From 5c82f052c26303318e81ddd76475c1d188cc74f4 Mon Sep 17 00:00:00 2001 From: Kelly Rauchenberger Date: Tue, 8 May 2018 21:09:36 -0400 Subject: Simplified positions/sizes with vectors Positions and sizes are now stored as vectors (of doubles and ints, respectively). This allows for at least minor code simplification in many places, and cleans up the CollisionParams code in PonderingSystem quite a bit. --- src/components/automatable.h | 4 +- src/components/playable.h | 4 +- src/components/ponderable.h | 10 +- src/components/realizable.h | 4 +- src/components/transformable.h | 13 +- src/systems/animating.cpp | 8 +- src/systems/automating.cpp | 3 +- src/systems/orienting.cpp | 14 +- src/systems/playing.cpp | 19 +-- src/systems/playing.h | 4 +- src/systems/pondering.cpp | 294 +++++++++++++++-------------------------- src/systems/pondering.h | 34 +++-- src/systems/realizing.cpp | 38 +++--- src/vector.h | 111 ++++++++++++++++ 14 files changed, 285 insertions(+), 275 deletions(-) create mode 100644 src/vector.h (limited to 'src/components/transformable.h') diff --git a/src/components/automatable.h b/src/components/automatable.h index b37945f..c1fd1a3 100644 --- a/src/components/automatable.h +++ b/src/components/automatable.h @@ -4,6 +4,7 @@ #include "component.h" #include #include +#include "vector.h" class AutomatableComponent : public Component { public: @@ -18,8 +19,7 @@ public: * The horizontal and vertical speed, in pixels/sec, that the entity should * move at. */ - double speedX; - double speedY; + vec2d speed; /** * The duration of the action in seconds. diff --git a/src/components/playable.h b/src/components/playable.h index 94d4326..b8af0f2 100644 --- a/src/components/playable.h +++ b/src/components/playable.h @@ -3,6 +3,7 @@ #include "component.h" #include "entity_manager.h" +#include "vector.h" class PlayableComponent : public Component { public: @@ -24,8 +25,7 @@ public: * @managed_by PlayingSystem */ size_t checkpointMapId; - double checkpointX; - double checkpointY; + vec2d checkpointPos; }; diff --git a/src/components/ponderable.h b/src/components/ponderable.h index eff20e9..c0312b4 100644 --- a/src/components/ponderable.h +++ b/src/components/ponderable.h @@ -4,6 +4,7 @@ #include #include "component.h" #include "entity_manager.h" +#include "vector.h" class PonderableComponent : public Component { public: @@ -45,14 +46,12 @@ public: /** * The velocity of the body. */ - double velX = 0.0; - double velY = 0.0; + vec2d vel = { 0.0, 0.0 }; /** * The acceleration of the body. */ - double accelX = 0.0; - double accelY = 0.0; + vec2d accel = { 0.0, 0.0 }; /** * The type of physical body that the entity is meant to assume. The body will @@ -89,8 +88,7 @@ public: * * @managed_by PonderingSystem */ - double relX; - double relY; + vec2d rel = { 0.0, 0.0 }; /** * The bodies that are being ferried by this body. diff --git a/src/components/realizable.h b/src/components/realizable.h index 0858e7a..b749aeb 100644 --- a/src/components/realizable.h +++ b/src/components/realizable.h @@ -5,6 +5,7 @@ #include #include #include "entity_manager.h" +#include "vector.h" class RealizableComponent : public Component { public: @@ -31,8 +32,7 @@ public: * @managed_by RealizingSystem */ int startingMapId; - int startingX; - int startingY; + vec2i startingPos; /** * The set of map entities loaded by this entity. It is only intended for diff --git a/src/components/transformable.h b/src/components/transformable.h index 6f3c2ef..bb21996 100644 --- a/src/components/transformable.h +++ b/src/components/transformable.h @@ -2,6 +2,7 @@ #define LOCATABLE_H_39E526CA #include "component.h" +#include "vector.h" class TransformableComponent : public Component { public: @@ -15,24 +16,20 @@ public: * so, use PonderingSystem::unferry on the body to ensure that it is not * ferried. */ - double x; - double y; + vec2d pos; /** * The size of the entity. */ - int w; - int h; + vec2i size; /** * For prototypes, the original coordinates and size of the entity. * * @managed_by RealizingSystem */ - double origX; - double origY; - int origW; - int origH; + vec2d origPos; + vec2i origSize; }; #endif /* end of include guard: LOCATABLE_H_39E526CA */ diff --git a/src/systems/animating.cpp b/src/systems/animating.cpp index 8543ba2..50a32fc 100644 --- a/src/systems/animating.cpp +++ b/src/systems/animating.cpp @@ -64,10 +64,10 @@ void AnimatingSystem::render(Texture& texture) } Rectangle dstrect { - static_cast(transform.x), - static_cast(transform.y), - transform.w, - transform.h}; + static_cast(transform.pos.x()), + static_cast(transform.pos.y()), + transform.size.w(), + transform.size.h()}; const AnimationSet& aset = sprite.animationSet; game_.getRenderer().blit( diff --git a/src/systems/automating.cpp b/src/systems/automating.cpp index 0d85957..61b97d9 100644 --- a/src/systems/automating.cpp +++ b/src/systems/automating.cpp @@ -54,8 +54,7 @@ void AutomatingSystem::tick(double dt) auto& ponderable = game_.getEntityManager(). getComponent(entity); - ponderable.velX = curAction.speedX; - ponderable.velY = curAction.speedY; + ponderable.vel = curAction.speed; automatable.remaining -= dt; } diff --git a/src/systems/orienting.cpp b/src/systems/orienting.cpp index 206ebf6..d73ddd2 100644 --- a/src/systems/orienting.cpp +++ b/src/systems/orienting.cpp @@ -24,27 +24,27 @@ void OrientingSystem::tick(double) { case OrientableComponent::WalkState::still: { - ponderable.velX = 0.0; + ponderable.vel.x() = 0.0; break; } case OrientableComponent::WalkState::left: { - ponderable.velX = -WALK_SPEED; + ponderable.vel.x() = -WALK_SPEED; break; } case OrientableComponent::WalkState::right: { - ponderable.velX = WALK_SPEED; + ponderable.vel.x() = WALK_SPEED; break; } } - if (orientable.isJumping() && (ponderable.velY > 0)) + if (orientable.isJumping() && (ponderable.vel.y() > 0)) { orientable.setJumping(false); } @@ -122,8 +122,8 @@ void OrientingSystem::jump(id_type entity) playSound("res/Randomize87.wav", 0.25); - ponderable.velY = JUMP_VELOCITY; - ponderable.accelY = JUMP_GRAVITY; + ponderable.vel.y() = JUMP_VELOCITY; + ponderable.accel.y() = JUMP_GRAVITY; auto& animating = game_.getSystemManager().getSystem(); if (orientable.isFacingRight()) @@ -147,7 +147,7 @@ void OrientingSystem::stopJumping(id_type entity) auto& ponderable = game_.getEntityManager(). getComponent(entity); - ponderable.accelY = NORMAL_GRAVITY; + ponderable.accel.y() = NORMAL_GRAVITY; } } diff --git a/src/systems/playing.cpp b/src/systems/playing.cpp index acec4e7..dabc9a5 100644 --- a/src/systems/playing.cpp +++ b/src/systems/playing.cpp @@ -42,10 +42,9 @@ void PlayingSystem::initPlayer() auto& transformable = game_.getEntityManager(). emplaceComponent(player); - transformable.x = realizable.startingX; - transformable.y = realizable.startingY; - transformable.w = 10; - transformable.h = 12; + transformable.pos = realizable.startingPos; + transformable.size.w() = 10; + transformable.size.h() = 12; game_.getSystemManager().getSystem().initializeBody( player, @@ -59,8 +58,7 @@ void PlayingSystem::initPlayer() playable.mapId = realizable.activeMap; playable.checkpointMapId = realizable.startingMapId; - playable.checkpointX = realizable.startingX; - playable.checkpointY = realizable.startingY; + playable.checkpointPos = realizable.startingPos; realizing.enterActiveMap(player); @@ -70,8 +68,7 @@ void PlayingSystem::initPlayer() void PlayingSystem::changeMap( id_type player, size_t mapId, - double x, - double y) + vec2d warpPos) { auto& playable = game_.getEntityManager(). getComponent(player); @@ -103,8 +100,7 @@ void PlayingSystem::changeMap( pondering.unferry(player); - transformable.x = x; - transformable.y = y; + transformable.pos = warpPos; if (realizable.activePlayer == player) { @@ -139,8 +135,7 @@ void PlayingSystem::die(id_type player) changeMap( player, playable.checkpointMapId, - playable.checkpointX, - playable.checkpointY); + playable.checkpointPos); animatable.frozen = false; animatable.flickering = false; diff --git a/src/systems/playing.h b/src/systems/playing.h index 9ba403b..31f79ab 100644 --- a/src/systems/playing.h +++ b/src/systems/playing.h @@ -2,6 +2,7 @@ #define PLAYING_H_70A54F7D #include "system.h" +#include "vector.h" class PlayingSystem : public System { public: @@ -15,8 +16,7 @@ public: void changeMap( id_type player, size_t mapId, - double x, - double y); + vec2d warpPos); void die(id_type player); diff --git a/src/systems/pondering.cpp b/src/systems/pondering.cpp index 7b3ab2d..ec83270 100644 --- a/src/systems/pondering.cpp +++ b/src/systems/pondering.cpp @@ -47,7 +47,7 @@ void PonderingSystem::initializeBody( if (type == PonderableComponent::Type::freefalling) { - ponderable.accelY = NORMAL_GRAVITY; + ponderable.accel.y() = NORMAL_GRAVITY; } } @@ -56,10 +56,10 @@ void PonderingSystem::initPrototype(id_type prototype) auto& ponderable = game_.getEntityManager(). getComponent(prototype); - ponderable.velX = 0.0; - ponderable.velY = 0.0; - ponderable.accelX = 0.0; - ponderable.accelY = 0.0; + ponderable.vel.x() = 0.0; + ponderable.vel.y() = 0.0; + ponderable.accel.x() = 0.0; + ponderable.accel.y() = 0.0; ponderable.grounded = false; ponderable.frozen = false; ponderable.collidable = true; @@ -102,19 +102,17 @@ void PonderingSystem::tickBody( // Accelerate if (!ponderable.frozen) { - ponderable.velX += ponderable.accelX * dt; - ponderable.velY += ponderable.accelY * dt; + ponderable.vel += ponderable.accel * dt; if ((ponderable.type == PonderableComponent::Type::freefalling) - && (ponderable.velY > TERMINAL_VELOCITY)) + && (ponderable.vel.y() > TERMINAL_VELOCITY)) { - ponderable.velY = TERMINAL_VELOCITY; + ponderable.vel.y() = TERMINAL_VELOCITY; } } // Move - double newX = transformable.x; - double newY = transformable.y; + vec2d newPos = transformable.pos; if (!ponderable.frozen) { @@ -123,19 +121,13 @@ void PonderingSystem::tickBody( auto& ferryTrans = game_.getEntityManager(). getComponent(ponderable.ferry); - newX = ferryTrans.x + ponderable.relX; - newY = ferryTrans.y + ponderable.relY; + newPos = ferryTrans.pos + ponderable.rel; } - newX += ponderable.velX * dt; - newY += ponderable.velY * dt; + newPos += ponderable.vel * dt; } - CollisionResult result = - moveBody( - entity, - newX, - newY); + CollisionResult result = moveBody(entity, newPos); // Perform cleanup for orientable entites bool groundedChanged = (ponderable.grounded != result.grounded); @@ -194,8 +186,7 @@ void PonderingSystem::tickBody( auto& ferryTrans = game_.getEntityManager(). getComponent(ponderable.ferry); - ponderable.relX = transformable.x - ferryTrans.x; - ponderable.relY = transformable.y - ferryTrans.y; + ponderable.rel = transformable.pos - ferryTrans.pos; } // Handle ferry passengers @@ -212,35 +203,34 @@ void PonderingSystem::tickBody( // Move to an adjacent map, if necessary if (result.adjacentlyWarping) { - double warpX = result.newX; - double warpY = result.newY; + vec2d warpPos = result.pos; switch (result.adjWarpDir) { case Direction::left: { - warpX = GAME_WIDTH + WALL_GAP - transformable.w; + warpPos.x() = GAME_WIDTH + WALL_GAP - transformable.size.w(); break; } case Direction::right: { - warpX = -WALL_GAP; + warpPos.x() = -WALL_GAP; break; } case Direction::up: { - warpY = MAP_HEIGHT * TILE_HEIGHT - transformable.h; + warpPos.y() = MAP_HEIGHT * TILE_HEIGHT - transformable.size.h(); break; } case Direction::down: { - warpY = -WALL_GAP; + warpPos.y() = -WALL_GAP; break; } @@ -250,15 +240,13 @@ void PonderingSystem::tickBody( changeMap( entity, result.adjWarpMapId, - warpX, - warpY); + warpPos); } } -CollisionResult PonderingSystem::moveBody( +PonderingSystem::CollisionResult PonderingSystem::moveBody( id_type entity, - double x, - double y) + vec2d newPos) { auto& ponderable = game_.getEntityManager(). getComponent(entity); @@ -266,26 +254,29 @@ CollisionResult PonderingSystem::moveBody( auto& transformable = game_.getEntityManager(). getComponent(entity); - const double oldX = transformable.x; - const double oldY = transformable.y; - const double oldRight = oldX + transformable.w; - const double oldBottom = oldY + transformable.h; - CollisionResult result; if (ponderable.collidable) { - result = detectCollisions(entity, x, y); + result = detectCollisions(entity, newPos); } else { - result.newX = x; - result.newY = y; + result.pos = newPos; } // Move if (!ponderable.frozen) { - transformable.x = result.newX; - transformable.y = result.newY; + transformable.pos = result.pos; + + if (result.blockedHoriz) + { + ponderable.vel.x() = 0.0; + } + + if (result.blockedVert) + { + ponderable.vel.y() = 0.0; + } } return result; @@ -311,21 +302,14 @@ namespace CollisionParams { return (colliderAxis > entityAxis); } - inline static double OldAxis(const TransformableComponent& transformable) + inline static double EntityAxis(const vec2d& pos, const vec2i& size) { - return HorizVert::AxisOldLower(transformable); + return HorizVert::AxisLower(pos); } - inline static double NewAxis( - const CollisionResult& result, - const TransformableComponent&) + inline static double ObjectAxis(const vec2d& pos, const vec2i& size) { - return HorizVert::AxisNewLower(result); - } - - inline static double ObjectAxis(const TransformableComponent& transformable) - { - return HorizVert::AxisOldUpper(transformable); + return HorizVert::AxisUpper(pos, size); } inline static bool Closer(double left, double right) @@ -352,21 +336,14 @@ namespace CollisionParams { return (colliderAxis < entityAxis); } - inline static double OldAxis(const TransformableComponent& transformable) + inline static double EntityAxis(const vec2d& pos, const vec2i& size) { - return HorizVert::AxisOldUpper(transformable); + return HorizVert::AxisUpper(pos, size); } - inline static double NewAxis( - const CollisionResult& result, - const TransformableComponent& transformable) + inline static double ObjectAxis(const vec2d& pos, const vec2i& size) { - return HorizVert::AxisNewUpper(result, transformable); - } - - inline static double ObjectAxis(const TransformableComponent& transformable) - { - return HorizVert::AxisOldLower(transformable); + return HorizVert::AxisLower(pos); } inline static bool Closer(double left, double right) @@ -375,121 +352,62 @@ namespace CollisionParams { } }; - class Horizontal { + template + class HorizVert { public: - inline static double AxisOldLower( - const TransformableComponent& transformable) + inline static double AxisLower(const vec2d& pos) { - return transformable.x; + return pos.coords[Axis]; } - inline static double AxisOldUpper( - const TransformableComponent& transformable) + inline static double AxisUpper(const vec2d& pos, const vec2i& size) { - return transformable.x + transformable.w; + return pos.coords[Axis] + size.coords[Axis]; } - inline static double AxisNewLower(const CollisionResult& result) + inline static double NonAxisLower(const vec2d& pos) { - return result.newX; + return pos.coords[NonAxis]; } - inline static double AxisNewUpper( - const CollisionResult& result, - const TransformableComponent& transformable) + inline static double NonAxisUpper(const vec2d& pos, const vec2i& size) { - return result.newX + transformable.w; + return pos.coords[NonAxis] + size.coords[NonAxis]; } - inline static double NonAxisOldLower( - const TransformableComponent& transformable) - { - return transformable.y; - } - - inline static double NonAxisOldUpper( - const TransformableComponent& transformable) - { - return transformable.y + transformable.h; - } - - inline static double NonAxisNewLower( - const CollisionResult& result, - const TransformableComponent& transformable) - { - return result.newY; - } - - inline static double NonAxisNewUpper( - const CollisionResult& result, - const TransformableComponent& transformable) - { - return result.newY + transformable.h; - } }; - class Vertical { - public: - - inline static double AxisOldLower( - const TransformableComponent& transformable) - { - return transformable.y; - } - - inline static double AxisOldUpper( - const TransformableComponent& transformable) - { - return transformable.y + transformable.h; - } + using Horizontal = HorizVert<0, 1>; + using Vertical = HorizVert<1, 0>; - inline static double AxisNewLower(const CollisionResult& result) - { - return result.newY; - } + template + class DetectCollisions : public AscDesc { + public: - inline static double AxisNewUpper( - const CollisionResult& result, - const TransformableComponent& transformable) - { - return result.newY + transformable.h; - } + static const Direction Dir = dir; - inline static double NonAxisOldLower( - const TransformableComponent& transformable) + inline static double EntityAxis(const vec2d& pos, const vec2i& size) { - return transformable.x; + return AscDesc::EntityAxis(pos, size); } - inline static double NonAxisOldUpper( - const TransformableComponent& transformable) + inline static double ObjectAxis(const vec2d& pos, const vec2i& size) { - return transformable.x + transformable.w; + return AscDesc::ObjectAxis(pos, size); } - inline static double NonAxisNewLower( - const CollisionResult& result, - const TransformableComponent& transformable) + inline static double EntityAxis(const TransformableComponent& transformable) { - return result.newX; + return AscDesc::EntityAxis(transformable.pos, transformable.size); } - inline static double NonAxisNewUpper( - const CollisionResult& result, - const TransformableComponent& transformable) + inline static double ObjectAxis(const TransformableComponent& transformable) { - return result.newX + transformable.w; + return AscDesc::ObjectAxis(transformable.pos, transformable.size); } }; - template - class DetectCollisions : public AscDesc { - public: - - static const Direction Dir = dir; - }; - class Left : public DetectCollisions> { public: @@ -531,23 +449,22 @@ namespace CollisionParams { }; }; -CollisionResult PonderingSystem::detectCollisions( +PonderingSystem::CollisionResult PonderingSystem::detectCollisions( id_type entity, - double x, - double y) + vec2d newPos) { auto& transformable = game_.getEntityManager(). getComponent(entity); CollisionResult result; - result.newX = x; - result.newY = transformable.y; + result.pos.x() = newPos.x(); + result.pos.y() = transformable.pos.y(); // Find horizontal collisions. - if (result.newX < transformable.x) + if (result.pos.x() < transformable.pos.x()) { detectCollisionsInDirection(entity, result); - } else if (result.newX > transformable.x) + } else if (result.pos.x() > transformable.pos.x()) { detectCollisionsInDirection(entity, result); } @@ -555,13 +472,13 @@ CollisionResult PonderingSystem::detectCollisions( // Find vertical collisions if (!result.stopProcessing) { - result.newY = y; + result.pos.y() = newPos.y(); result.touchedWall = false; - if (result.newY < transformable.y) + if (result.pos.y() < transformable.pos.y()) { detectCollisionsInDirection(entity, result); - } else if (result.newY > transformable.y) + } else if (result.pos.y() > transformable.pos.y()) { detectCollisionsInDirection(entity, result); } @@ -586,25 +503,25 @@ void PonderingSystem::detectCollisionsInDirection( getComponent(mapEntity); // Get old location. - auto& transformable = game_.getEntityManager(). + auto& transform = game_.getEntityManager(). getComponent(entity); bool boundaryCollision = false; auto boundaries = Param::MapBoundaries(mappable); - auto it = boundaries.lower_bound(Param::OldAxis(transformable)); + auto it = boundaries.lower_bound(Param::EntityAxis(transform)); // Find the axis distance of the closest environmental boundary. for (; (it != std::end(boundaries)) && Param::AtLeastInAxisSweep( it->first, - Param::NewAxis(result, transformable)); + Param::EntityAxis(result.pos, transform.size)); it++) { // Check that the boundary is in range for the other axis. - if ((Param::NonAxisNewUpper(result, transformable) > it->second.lower) && - (Param::NonAxisNewLower(result, transformable) < it->second.upper)) + if ((Param::NonAxisUpper(result.pos, transform.size) > it->second.lower) && + (Param::NonAxisLower(result.pos) < it->second.upper)) { // We have a collision! boundaryCollision = true; @@ -644,16 +561,16 @@ void PonderingSystem::detectCollisionsInDirection( // Check if the entity would move into the potential collider, if (Param::IsPastAxis( Param::ObjectAxis(colliderTrans), - Param::NewAxis(result, transformable)) && + Param::EntityAxis(result.pos, transform.size)) && // that it wasn't already colliding, !Param::IsPastAxis( Param::ObjectAxis(colliderTrans), - Param::OldAxis(transformable)) && + Param::EntityAxis(transform)) && // that the position on the non-axis is in range, - (Param::NonAxisOldUpper(colliderTrans) > - Param::NonAxisNewLower(result, transformable)) && - (Param::NonAxisOldLower(colliderTrans) < - Param::NonAxisNewUpper(result, transformable)) && + (Param::NonAxisUpper(colliderTrans.pos, colliderTrans.size) > + Param::NonAxisLower(result.pos)) && + (Param::NonAxisLower(colliderTrans.pos) < + Param::NonAxisUpper(result.pos, transform.size)) && // and that the collider is not farther away than the environmental // boundary. (!boundaryCollision || @@ -688,7 +605,7 @@ void PonderingSystem::detectCollisionsInDirection( // Check if the entity would still move into the potential collider. if (!Param::IsPastAxis( Param::ObjectAxis(colliderTrans), - Param::NewAxis(result, transformable))) + Param::EntityAxis(result.pos, transform.size))) { break; } @@ -702,8 +619,8 @@ void PonderingSystem::detectCollisionsInDirection( Param::Dir, colliderPonder.colliderType, Param::ObjectAxis(colliderTrans), - Param::NonAxisOldLower(colliderTrans), - Param::NonAxisOldUpper(colliderTrans), + Param::NonAxisLower(colliderTrans.pos), + Param::NonAxisUpper(colliderTrans.pos, colliderTrans.size), result); if (result.stopProcessing) @@ -724,8 +641,8 @@ void PonderingSystem::detectCollisionsInDirection( (it->first == boundaryAxis); it++) { - if ((Param::NonAxisNewUpper(result, transformable) > it->second.lower) && - (Param::NonAxisNewLower(result, transformable) < it->second.upper)) + if ((Param::NonAxisLower(result.pos) < it->second.upper) && + (Param::NonAxisUpper(result.pos, transform.size) > it->second.lower)) { processCollision( entity, @@ -756,9 +673,6 @@ void PonderingSystem::processCollision( double upper, CollisionResult& result) { - auto& ponderable = game_.getEntityManager(). - getComponent(entity); - auto& transformable = game_.getEntityManager(). getComponent(entity); @@ -823,29 +737,29 @@ void PonderingSystem::processCollision( { case Direction::left: { - result.newX = GAME_WIDTH + WALL_GAP - transformable.w; + result.pos.x() = GAME_WIDTH + WALL_GAP - transformable.size.w(); break; } case Direction::right: { - result.newX = -WALL_GAP; + result.pos.x() = -WALL_GAP; break; } case Direction::up: { - result.newY = - MAP_HEIGHT * TILE_HEIGHT + WALL_GAP - transformable.h; + result.pos.y() = + MAP_HEIGHT * TILE_HEIGHT + WALL_GAP - transformable.pos.h(); break; } case Direction::down: { - result.newY = -WALL_GAP; + result.pos.y() = -WALL_GAP; break; } @@ -905,33 +819,33 @@ void PonderingSystem::processCollision( { case Direction::left: { - result.newX = axis; - ponderable.velX = 0.0; + result.pos.x() = axis; + result.blockedHoriz = true; break; } case Direction::right: { - result.newX = axis - transformable.w; - ponderable.velX = 0.0; + result.pos.x() = axis - transformable.size.w(); + result.blockedHoriz = true; break; } case Direction::up: { - result.newY = axis; - ponderable.velY = 0.0; + result.pos.y() = axis; + result.blockedVert = true; break; } case Direction::down: { - result.newY = axis - transformable.h; + result.pos.y() = axis - transformable.size.h(); + result.blockedVert = true; result.groundEntity = collider; - ponderable.velY = 0.0; result.grounded = true; break; diff --git a/src/systems/pondering.h b/src/systems/pondering.h index abc6db2..273db67 100644 --- a/src/systems/pondering.h +++ b/src/systems/pondering.h @@ -4,19 +4,7 @@ #include "system.h" #include "components/ponderable.h" #include "direction.h" - -struct CollisionResult -{ - double newX; - double newY; - bool stopProcessing = false; - bool touchedWall = false; - bool adjacentlyWarping = false; - Direction adjWarpDir; - size_t adjWarpMapId; - bool grounded = false; - EntityManager::id_type groundEntity; -}; +#include "vector.h" class PonderingSystem : public System { public: @@ -47,7 +35,19 @@ public: private: - + struct CollisionResult + { + vec2d pos; + bool stopProcessing = false; + bool touchedWall = false; + bool blockedHoriz = false; + bool blockedVert = false; + bool adjacentlyWarping = false; + Direction adjWarpDir; + size_t adjWarpMapId; + bool grounded = false; + id_type groundEntity; + }; void tickBody( id_type entity, @@ -56,13 +56,11 @@ private: CollisionResult moveBody( id_type entity, - double x, - double y); + vec2d newPos); CollisionResult detectCollisions( id_type entity, - double x, - double y); + vec2d newPos); template void detectCollisionsInDirection( diff --git a/src/systems/realizing.cpp b/src/systems/realizing.cpp index 8e670ac..f9285ad 100644 --- a/src/systems/realizing.cpp +++ b/src/systems/realizing.cpp @@ -93,20 +93,20 @@ void parseAI( if (direction == "left") { - action.speedX = -speed; - action.speedY = 0; + action.speed.x() = -speed; + action.speed.y() = 0; } else if (direction == "right") { - action.speedX = speed; - action.speedY = 0; + action.speed.x() = speed; + action.speed.y() = 0; } else if (direction == "up") { - action.speedX = 0; - action.speedY = -speed; + action.speed.x() = 0; + action.speed.y() = -speed; } else if (direction == "down") { - action.speedX = 0; - action.speedY = speed; + action.speed.x() = 0; + action.speed.y() = speed; } action.dur = length / speed; @@ -186,11 +186,11 @@ EntityManager::id_type RealizingSystem::initSingleton( } key = getProp(top, "startx"); - realizable.startingX = atoi(reinterpret_cast(key)); + realizable.startingPos.x() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(top, "starty"); - realizable.startingY = atoi(reinterpret_cast(key)); + realizable.startingPos.y() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(top, "startmap"); @@ -260,11 +260,11 @@ EntityManager::id_type RealizingSystem::initSingleton( emplaceComponent(mapObject); key = getProp(mapNode, "x"); - transformable.origX = atoi(reinterpret_cast(key)); + transformable.origPos.x() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(mapNode, "y"); - transformable.origY = atoi(reinterpret_cast(key)); + transformable.origPos.y() = atoi(reinterpret_cast(key)); xmlFree(key); // Set the sprite and size using the prototype definition. @@ -273,17 +273,17 @@ EntityManager::id_type RealizingSystem::initSingleton( xmlFree(key); key = getProp(prototypeNode, "width"); - transformable.origW = atoi(reinterpret_cast(key)); + transformable.origSize.w() = atoi(reinterpret_cast(key)); xmlFree(key); key = getProp(prototypeNode, "height"); - transformable.origH = atoi(reinterpret_cast(key)); + transformable.origSize.h() = atoi(reinterpret_cast(key)); xmlFree(key); AnimationSet objectAnim( spritePath.c_str(), - transformable.origW, - transformable.origH, + transformable.origSize.w(), + transformable.origSize.h(), 1); objectAnim.emplaceAnimation("static", 0, 1, 1); @@ -503,10 +503,8 @@ void RealizingSystem::loadMap(id_type mapEntity) auto& transformable = game_.getEntityManager(). getComponent(prototype); - transformable.x = transformable.origX; - transformable.y = transformable.origY; - transformable.w = transformable.origW; - transformable.h = transformable.origH; + transformable.pos = transformable.origPos; + transformable.size = transformable.origSize; } if (game_.getEntityManager().hasComponent(prototype)) diff --git a/src/vector.h b/src/vector.h new file mode 100644 index 0000000..3abd98a --- /dev/null +++ b/src/vector.h @@ -0,0 +1,111 @@ +#ifndef COORDINATES_H_A45D34FB +#define COORDINATES_H_A45D34FB + +template +class vec2 { +public: + + T coords[2]; + + vec2() = default; + + vec2(double x, double y) : coords{x, y} + { + } + + inline T& x() + { + return coords[0]; + } + + inline const T& x() const + { + return coords[0]; + } + + inline T& w() + { + return coords[0]; + } + + inline const T& w() const + { + return coords[0]; + } + + inline T& y() + { + return coords[1]; + } + + inline const T& y() const + { + return coords[1]; + } + + inline T& h() + { + return coords[1]; + } + + inline const T& h() const + { + return coords[1]; + } + + template + operator vec2() const + { + return vec2(x(), y()); + } + + vec2 operator+(const vec2& other) const + { + return vec2(x() + other.x(), y() + other.y()); + } + + vec2& operator+=(const vec2& other) + { + x() += other.x(); + y() += other.y(); + + return *this; + } + + vec2 operator-(const vec2& other) const + { + return vec2(x() - other.x(), y() - other.y()); + } + + vec2 operator-=(const vec2& other) + { + x() -= other.x(); + y() -= other.y(); + + return *this; + } + + vec2 operator-() const + { + return vec2(-x(), -y()); + } + + vec2 operator*(double s) const + { + return vec2(x() * s, y() * s); + } + + vec2& operator*=(double s) + { + x() *= s; + y() *= s; + + return *this; + } + +}; + +using vec2d = vec2; +using vec2i = vec2; + +#endif /* end of include guard: COORDINATES_H_A45D34FB */ -- cgit 1.4.1