Apply new Code Styling to all files.

This commit is contained in:
Auri 2020-11-08 22:57:34 -08:00
parent 4915a8130b
commit e49ab18617
322 changed files with 14205 additions and 13136 deletions

4
.idea/misc.xml generated
View File

@ -6,14 +6,12 @@
<file path="$PROJECT_DIR$/src" />
<file path="$PROJECT_DIR$/test" />
</sourceRoots>
<libraryRoots>
<file path="$PROJECT_DIR$/lib" />
</libraryRoots>
<excludeRoots>
<file path="$PROJECT_DIR$/.github" />
<file path="$PROJECT_DIR$/.idea" />
<file path="$PROJECT_DIR$/Libraries" />
<file path="$PROJECT_DIR$/cmake-build-install" />
<file path="$PROJECT_DIR$/lib" />
<file path="$PROJECT_DIR$/worlds" />
<file path="$PROJECT_DIR$/worlds/world" />
</excludeRoots>

View File

@ -21,7 +21,8 @@
/**
* Main entrance point to the program. (Am I really describing what the main function is?)
* Intentionally kept minimal to allow for testing. Real startup logic is done in StartGame. *
* Intentionally kept minimal to allow for testing. Real startup logic is done in StartGame.
*
* @param argc - Argument array length
* @param argv - Argument array
* @returns - A numerical value indicating exit status.

View File

@ -11,7 +11,9 @@
#include "client/Client.h"
#include "server/Server.h"
enum class Mode { CLIENT, SERVER };
enum class Mode {
CLIENT, SERVER
};
/**
@ -23,7 +25,6 @@ enum class Mode { CLIENT, SERVER };
*/
std::map<std::string, std::string> ParseArgs(int argc, char* argv[]) {
//Collect arguments into `args` map
std::map<std::string, std::string> args;
for (int i = 1; i < argc; i++) {
@ -67,8 +68,7 @@ int StartGame(int argc, char* argv[]) {
for (auto arg : ParseArgs(argc, argv)) {
switch (Util::hash(arg.first.c_str())) {
default:
throw std::runtime_error("Invalid argument '" + arg.first + "'.");
default: throw std::runtime_error("Invalid argument '" + arg.first + "'.");
case Util::hash("--mode"):
if (arg.second == "client") mode = Mode::CLIENT;
@ -80,16 +80,13 @@ int StartGame(int argc, char* argv[]) {
// addr.host = arg.second;
// break;
case Util::hash("--port"):
port = static_cast<unsigned short>(stoi(arg.second));
case Util::hash("--port"): port = static_cast<unsigned short>(stoi(arg.second));
break;
case Util::hash("--subgame"):
subgame = arg.second;
case Util::hash("--subgame"): subgame = arg.second;
break;
case Util::hash("--noascii"):
ascii = false;
case Util::hash("--noascii"): ascii = false;
break;
}
}
@ -104,15 +101,8 @@ int StartGame(int argc, char* argv[]) {
"\t\t(____)(____)(__) \\_)(_/\\_/\\_/\n" << std::endl;
}
switch (mode) {
case Mode::CLIENT: {
Client c({1366, 768});
break; }
case Mode::SERVER: {
Server s(port, subgame);
break; }
}
if (mode == Mode::CLIENT) Client({ 1366, 768 });
else Server(port, subgame);
return 0;
}

View File

@ -48,7 +48,7 @@ void Client::startLocalServer(const std::string& subgame) {
// localServer = std::make_shared<LocalServerInstance>(executablePath, addr.port, state.subgame);
// localServer->start();
scene.setScene(std::make_unique<ConnectScene>(*this, Address { "127.0.0.1", Address::DEFAULT_PORT }));
scene.setScene(std::make_unique<ConnectScene>(*this, Address{ "127.0.0.1", Address::DEFAULT_PORT }));
}

View File

@ -16,8 +16,9 @@
class LocalServerInstance;
class Client {
public:
public:
Client(const Client& o) = delete;
explicit Client(glm::ivec2 window);
double getDelta();
@ -26,11 +27,11 @@ public:
Renderer renderer;
SceneManager scene;
ServerConnection connection {};
ServerConnection connection{};
std::shared_ptr<LocalSubgame> game = std::make_shared<LocalSubgame>("../assets/textures");
private:
private:
void loop();
std::shared_ptr<LocalServerInstance> localServer = nullptr;

View File

@ -17,7 +17,7 @@ Input::Input() {
for (bool& key : keysNew) key = false;
}
void Input::init(GLFWwindow *window, glm::ivec2* winDimensions) {
void Input::init(GLFWwindow* window, glm::ivec2* winDimensions) {
this->window = window;
this->winDimensions = winDimensions;
glfwSetKeyCallback(window, keyCallback);
@ -29,8 +29,8 @@ void Input::setCallback(std::function<void(bool, int)> callback) {
}
void Input::update() {
for (bool &key : keysPressed) key = false;
for (bool &key : keysReleased) key = false;
for (bool& key : keysPressed) key = false;
for (bool& key : keysReleased) key = false;
for (int i = 0; i < 1024; i++) {
bool key = keysNew[i];
@ -80,7 +80,7 @@ void Input::update() {
}
}
else {
delta = {mouseX - (winDimensions->x / 2), -(mouseY - (winDimensions->y / 2))};
delta = { mouseX - (winDimensions->x / 2), -(mouseY - (winDimensions->y / 2)) };
glfwSetCursorPos(window, winDimensions->x / 2, winDimensions->y / 2);
}
}
@ -130,7 +130,7 @@ void Input::keyCallback(GLFWwindow* window, int key, int code, int action, int m
}
}
void Input::scrollCallback(GLFWwindow *window, double xO, double yO) {
void Input::scrollCallback(GLFWwindow* window, double xO, double yO) {
auto w = static_cast<Window*>(glfwGetWindowUserPointer(window));
if (xO > 0) {
@ -163,7 +163,7 @@ void Input::lockMouse(bool lock) {
glm::ivec2 Input::mousePos() {
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
return glm::ivec2 { static_cast<int>(xPos), static_cast<int>(yPos) };
return glm::ivec2{ static_cast<int>(xPos), static_cast<int>(yPos) };
}
glm::vec2 Input::mouseDelta() {

View File

@ -9,39 +9,54 @@
#include <glm/vec2.hpp>
class Input {
public:
public:
Input();
void init(GLFWwindow* window, glm::ivec2* winDimensions);
void setCallback(std::function<void(bool, int)> callback);
void update();
bool keyDown(int key);
bool keyPressed(int key);
bool keyReleased(int key);
bool mouseDown(int button);
bool mousePressed(int button);
bool mouseReleased(int button);
void lockMouse(bool lock);
glm::ivec2 mousePos();
glm::vec2 mouseDelta();
private:
private:
void updateMouse(int key);
static void keyCallback(GLFWwindow* window, int key, int code, int action, int mode);
static void scrollCallback(GLFWwindow* window, double, double yO);
GLFWwindow* window = nullptr;
glm::ivec2* winDimensions = nullptr;
bool keysNew[1024] {false};
bool keysDown[1024] {false};
bool keysPressed[1024] {false};
bool keysReleased[1024] {false};
bool keysNew[1024]{ false };
bool keysDown[1024]{ false };
bool keysPressed[1024]{ false };
bool keysReleased[1024]{ false };
struct mouse { bool down = false; bool pressed = false; bool released = false; };
std::array<mouse, 3> mouseState {};
struct mouse {
bool down = false;
bool pressed = false;
bool released = false;
};
std::array<mouse, 3> mouseState{};
glm::vec2 delta;
bool mouseIsLocked = false;

View File

@ -7,7 +7,7 @@
#include "server/Server.h"
#include <iostream>
LocalServerInstance::LocalServerInstance(const std::string &path, unsigned short port, const std::string& subgame) :
LocalServerInstance::LocalServerInstance(const std::string& path, unsigned short port, const std::string& subgame) :
port(port),
path(path),
subgame(subgame) {}
@ -17,7 +17,7 @@ bool LocalServerInstance::start() {
pid = fork();
if (pid == 0) {
const auto sub = ("--subgame=" + subgame);
char *arr[] = {
char* arr[] = {
const_cast <char*>(""),
// const_cast <char*>("-iconic"),
const_cast <char*>("-e"),
@ -39,11 +39,11 @@ bool LocalServerInstance::start() {
}
void LocalServerInstance::stop() {
#ifndef _WIN32
#ifndef _WIN32
if (pid != 0) kill(pid, SIGKILL);
#else
#else
std::cout << Log::err << "Local Server destructor not implemented on Windows!" << Log::endl;
#endif
#endif
}
LocalServerInstance::~LocalServerInstance() {

View File

@ -7,20 +7,24 @@
#include <string>
#ifndef _WIN32
#include <thread>
#include <zconf.h>
#include <signal.h>
#endif
class LocalServerInstance {
public:
public:
LocalServerInstance(const std::string& path, unsigned short port, const std::string& subgame);
bool start();
void stop();
~LocalServerInstance();
private:
private:
std::string path;
std::string subgame;
unsigned short port = 0;

View File

@ -6,7 +6,7 @@
#include "util/Log.h"
Window::Window() : Window({800, 600}) {};
Window::Window() : Window({ 800, 600 }) {};
Window::Window(glm::ivec2 win) :
win(win), center(win.x / 2, win.y / 2) {
@ -41,7 +41,7 @@ Window::Window(glm::ivec2 win) :
if ((error = glewInit()) != GLEW_OK) {
glfwTerminate();
glfwDestroyWindow(mainWindow);
printf("%s", reinterpret_cast<const char *>(glewGetErrorString(error)));
printf("%s", reinterpret_cast<const char*>(glewGetErrorString(error)));
throw std::runtime_error("GLEW Fatal error.");
}
@ -71,11 +71,11 @@ void Window::swapBuffers() {
glfwSwapBuffers(mainWindow);
}
void Window::addResizeCallback(const std::string &identifier, std::function<void(glm::ivec2)> cb) {
void Window::addResizeCallback(const std::string& identifier, std::function<void(glm::ivec2)> cb) {
resizeCallbacks.emplace(identifier, cb);
}
void Window::removeResizeCallback(const std::string &identifier) {
void Window::removeResizeCallback(const std::string& identifier) {
resizeCallbacks.erase(identifier);
}

View File

@ -11,26 +11,32 @@
#include "Input.h"
class Window {
public:
public:
Window();
Window(glm::ivec2 win);
void update();
bool shouldClose();
void swapBuffers();
void addResizeCallback(const std::string& identifier, std::function<void(glm::ivec2)> cb);
void removeResizeCallback(const std::string& identifier);
glm::ivec2 getSize();
void setCursorHand(bool hand);
~Window();
Input input;
GLFWwindow* mainWindow = nullptr;
private:
private:
static void scrollCallback(GLFWwindow* window, double xO, double yO);
static void resizeCallback(GLFWwindow* window, int width, int height);
GLFWcursor* handCursor = nullptr;
@ -38,7 +44,7 @@ private:
glm::ivec2 win;
glm::ivec2 center;
bool keys[1024] {};
bool keys[1024]{};
std::map<std::string, std::function<void(glm::ivec2)>> resizeCallbacks;

View File

@ -14,7 +14,7 @@
#include "util/net/NetHandler.h"
#include "world/player/LocalPlayer.h"
ClientNetworkInterpreter::ClientNetworkInterpreter(ServerConnection &connection, LocalWorld& world) :
ClientNetworkInterpreter::ClientNetworkInterpreter(ServerConnection& connection, LocalWorld& world) :
world(world), connection(connection) {}
void ClientNetworkInterpreter::init(std::function<void(std::unique_ptr<PacketView>)> invCallback) {
@ -50,7 +50,8 @@ void ClientNetworkInterpreter::update() {
}
auto player = world.getPlayer();
if (player) Serializer()
if (player)
Serializer()
.appendE(NetField::POS).append(player->getPos())
.appendE(NetField::VEL).append(player->getVel())
.appendE(NetField::LOOK_PITCH).append(player->getPitch())
@ -62,59 +63,62 @@ void ClientNetworkInterpreter::receivedPacket(std::unique_ptr<PacketView> p) {
switch (p->type) {
default:
std::cout << Log::err << "Received unknown packet of type " << static_cast<int>(p->type)
<< ". Is the server on a different protocol version?" << Log::endl; break;
<< ". Is the server on a different protocol version?" << Log::endl;
break;
case Packet::Type::SERVER_INFO:
serverSideChunkGens = p->d.read<unsigned int>(); break;
case Packet::Type::SERVER_INFO:serverSideChunkGens = p->d.read<unsigned int>();
break;
case Packet::Type::THIS_PLAYER_INFO:
world.getPlayer()->handleAssertion(p->d); break;
case Packet::Type::THIS_PLAYER_INFO:world.getPlayer()->handleAssertion(p->d);
break;
case Packet::Type::PLAYER_ENT_INFO:
world.handlePlayerEntPacket(std::move(p)); break;
case Packet::Type::PLAYER_ENT_INFO:world.handlePlayerEntPacket(std::move(p));
break;
case Packet::Type::CHUNK:
case Packet::Type::MAPBLOCK:
world.handleWorldPacket(std::move(p)); break;
case Packet::Type::MAPBLOCK:world.handleWorldPacket(std::move(p));
break;
case Packet::Type::BLOCK_SET: {
auto pos = p->d.read<glm::ivec3>();
auto block = p->d.read<unsigned int>();
world.getActiveDimension()->setBlock(pos, block);
break; }
break;
}
case Packet::Type::ENTITY_INFO:
world.getActiveDimension().l()->serverEntitiesInfo(p->d); break;
case Packet::Type::ENTITY_INFO:world.getActiveDimension().l()->serverEntitiesInfo(p->d);
break;
case Packet::Type::ENTITY_REMOVED:
world.getActiveDimension().l()->serverEntitiesRemoved(p->d); break;
case Packet::Type::ENTITY_REMOVED:world.getActiveDimension().l()->serverEntitiesRemoved(p->d);
break;
case Packet::Type::INV_DATA:
onInvPacket(std::move(p)); break;
case Packet::Type::INV_DATA:onInvPacket(std::move(p));
break;
case Packet::Type::INV_INVALID: {
std::string source = p->d.read<std::string>();
std::string list = p->d.read<std::string>();
throw std::runtime_error("Invalid inventory " + source + ":" + list + " was request by client."); }
throw std::runtime_error("Invalid inventory " + source + ":" + list + " was request by client.");
}
}
}
void ClientNetworkInterpreter::blockHit(const Target &target) {
void ClientNetworkInterpreter::blockHit(const Target& target) {
Serializer().append<glm::ivec3>(target.pos).append(static_cast<unsigned short>(target.face))
.packet(Packet::Type::BLOCK_HIT).sendTo(connection.getPeer(), Packet::Channel::INTERACT);
}
void ClientNetworkInterpreter::blockPlace(const Target &target) {
void ClientNetworkInterpreter::blockPlace(const Target& target) {
Serializer().append<glm::ivec3>(target.pos).append(static_cast<unsigned short>(target.face))
.packet(Packet::Type::BLOCK_PLACE).sendTo(connection.getPeer(), Packet::Channel::INTERACT);
}
void ClientNetworkInterpreter::blockInteract(const Target &target) {
void ClientNetworkInterpreter::blockInteract(const Target& target) {
Serializer().append<glm::ivec3>(target.pos).append(static_cast<unsigned short>(target.face))
.packet(Packet::Type::BLOCK_INTERACT).sendTo(connection.getPeer(), Packet::Channel::INTERACT);
}
void ClientNetworkInterpreter::blockPlaceOrInteract(const Target &target) {
void ClientNetworkInterpreter::blockPlaceOrInteract(const Target& target) {
Serializer().append<glm::ivec3>(target.pos).append(static_cast<unsigned short>(target.face))
.packet(Packet::Type::BLOCK_PLACE_OR_INTERACT).sendTo(connection.getPeer(), Packet::Channel::INTERACT);
}
@ -129,11 +133,12 @@ void ClientNetworkInterpreter::invUnwatch(const std::string& inv, const std::str
.sendTo(connection.getPeer(), Packet::Channel::INTERACT);
}
void ClientNetworkInterpreter::invInteract(const std::string &inv, const std::string &list, bool primary, unsigned short ind) {
void ClientNetworkInterpreter::invInteract(const std::string& inv, const std::string& list, bool primary,
unsigned short ind) {
Serializer().append<unsigned short>(primary).append(inv).append(list).append<unsigned short>(ind)
.packet(Packet::Type::INV_INTERACT).sendTo(connection.getPeer(), Packet::Channel::INTERACT);
}
void ClientNetworkInterpreter::sendPacket(const Packet &packet, Packet::Channel channel) {
void ClientNetworkInterpreter::sendPacket(const Packet& packet, Packet::Channel channel) {
packet.sendTo(connection.getPeer(), channel);
}

View File

@ -13,35 +13,48 @@
#include "client/conn/ServerConnection.h"
class Model;
class Target;
class LocalWorld;
class PacketView;
class LocalPlayer;
class LocalSubgame;
enum class NetPlayerField;
class ClientNetworkInterpreter {
public:
public:
ClientNetworkInterpreter(const ClientNetworkInterpreter& other) = delete;
ClientNetworkInterpreter(ServerConnection& connection, LocalWorld& world);
void init(std::function<void(std::unique_ptr<PacketView>)> invCallback);
void update();
void blockHit(const Target& target);
void blockPlace(const Target& target);
void blockInteract(const Target& target);
void blockPlaceOrInteract(const Target& target);
void invWatch(const std::string& inv, const std::string& list);
void invUnwatch(const std::string& inv, const std::string& list);
void invInteract(const std::string& inv, const std::string& list, bool primary, unsigned short ind);
void sendPacket(const Packet& packet, Packet::Channel channel);
int recvPackets = 0;
int serverSideChunkGens = 0;
private:
private:
void receivedPacket(std::unique_ptr<PacketView> ePacket);
LocalWorld& world;

View File

@ -67,7 +67,7 @@ void ServerConnection::processConnecting() {
if (attempt < attempts) {
std::cout << Log::info << "Failed to connect to server, retrying." << Log::endl;
connectionTime = std::chrono::high_resolution_clock::now();
attempt ++;
attempt++;
}
else {
std::cout << Log::err << "Failed to connect to server." << Log::endl;
@ -90,11 +90,11 @@ void ServerConnection::disconnect() {
}
}
bool ServerConnection::pollEvents(ENetEvent *event) {
bool ServerConnection::pollEvents(ENetEvent* event) {
return enet_host_service(host, event, 0) > 0;
}
ENetPeer *ServerConnection::getPeer() {
ENetPeer* ServerConnection::getPeer() {
return peer;
}

View File

@ -10,7 +10,7 @@
class Address;
class ServerConnection {
public:
public:
enum class State {
UNCONNECTED,
ATTEMPTING_CONNECT,
@ -23,17 +23,20 @@ public:
ServerConnection() = default;
void attemptConnect(Address addr);
State getConnectionStatus();
void disconnect();
void processConnecting();
bool pollEvents(ENetEvent* event);
ENetPeer* getPeer();
~ServerConnection();
private:
private:
unsigned long timeout = 1000;
unsigned int attempts = 10;

View File

@ -9,9 +9,9 @@
#include "game/def/BlockDef.h"
#include "game/atlas/asset/AtlasRef.h"
ParticleEntity::ParticleEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 pos, BlockDef &block) :
ParticleEntity::ParticleEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 pos, BlockDef& block) :
DrawableEntity(game, dim, std::make_shared<Model>()), Entity(game, dim) {
setPos(pos + glm::vec3(.5,.3,.5));
setPos(pos + glm::vec3(.5, .3, .5));
std::set<std::shared_ptr<AtlasRef>>& textureRefs = block.model.textureRefs;
auto it = textureRefs.cbegin();
@ -28,13 +28,13 @@ ParticleEntity::ParticleEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 pos,
uv -= glm::vec4(0, 0, spanX * 0.75, spanY * 0.75);
uv += glm::vec4(offX, offY, offX, offY);
std::vector<EntityVertex> vertices {
{{-0.05, -0.05, 0}, {uv.x, uv.w, 0, 1}, {1, 1, 1}, true, {0, 0, 1}, {}, {}},
{{-0.05, 0.05, 0}, {uv.x, uv.y, 0, 1}, {1, 1, 1}, true, {0, 0, 1}, {}, {}},
{{ 0.05, 0.05, 0}, {uv.z, uv.y, 0, 1}, {1, 1, 1}, true, {0, 0, 1}, {}, {}},
{{ 0.05, -0.05, 0}, {uv.z, uv.w, 0, 1}, {1, 1, 1}, true, {0, 0, 1}, {}, {}},
std::vector<EntityVertex> vertices{
{{ -0.05, -0.05, 0 }, { uv.x, uv.w, 0, 1 }, { 1, 1, 1 }, true, { 0, 0, 1 }, {}, {}},
{{ -0.05, 0.05, 0 }, { uv.x, uv.y, 0, 1 }, { 1, 1, 1 }, true, { 0, 0, 1 }, {}, {}},
{{ 0.05, 0.05, 0 }, { uv.z, uv.y, 0, 1 }, { 1, 1, 1 }, true, { 0, 0, 1 }, {}, {}},
{{ 0.05, -0.05, 0 }, { uv.z, uv.w, 0, 1 }, { 1, 1, 1 }, true, { 0, 0, 1 }, {}, {}},
};
std::vector<unsigned int> indices {
std::vector<unsigned int> indices{
0, 1, 2, 2, 3, 0,
0, 2, 1, 2, 0, 3,
};
@ -68,6 +68,6 @@ void ParticleEntity::update(double delta, glm::vec3 player) {
velocity.y -= 32.f * delta;
}
void ParticleEntity::draw(Renderer &renderer) {
void ParticleEntity::draw(Renderer& renderer) {
DrawableEntity::draw(renderer);
}

View File

@ -9,14 +9,15 @@
class BlockDef;
class ParticleEntity : public DrawableEntity {
public:
public:
ParticleEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 pos, BlockDef& block);
void update(double delta, glm::vec3 player);
void draw(Renderer& renderer) override;
float time = 0;
private:
glm::vec3 velocity {};
private:
glm::vec3 velocity{};
};

View File

@ -7,8 +7,9 @@
#include "world/dim/ent/DrawableEntity.h"
class PlayerEntity : public DrawableEntity {
public:
PlayerEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 pos, unsigned int id, const std::shared_ptr<Model>& model) :
public:
PlayerEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 pos, unsigned int id, const std::shared_ptr<Model>& model)
:
DrawableEntity(game, dim, model), Entity(game, dim), id(id) {
setPos(pos);
}
@ -17,6 +18,6 @@ public:
return id;
}
private:
private:
unsigned int id;
};

View File

@ -44,24 +44,36 @@ void WireframeEntity::buildMesh(const std::vector<SelectionBox>& boxes) {
this->model->fromMesh(std::move(mesh));
}
void WireframeEntity::createBox(glm::vec3 a, glm::vec3 b, float x, float y, float z, float xSize, float ySize, float zSize) {
float hw = (width/2.0f);
void
WireframeEntity::createBox(glm::vec3 a, glm::vec3 b, float x, float y, float z, float xSize, float ySize, float zSize) {
float hw = (width / 2.0f);
float w = width;
glm::vec3 c = color;
std::vector<EntityVertex> myVerts {
/*0*/ {{x - hw + a.x, y - hw + a.y, z - hw + a.z }, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*1*/ {{x - hw + a.x + xSize + w, y - hw + a.y, z - hw + a.z }, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*2*/ {{x - hw + a.x + xSize + w, y - hw + a.y, z - hw + a.z + zSize + w}, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*3*/ {{x - hw + a.x, y - hw + a.y, z - hw + a.z + zSize + w}, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
std::vector<EntityVertex> myVerts{
/*0*/
{{ x - hw + a.x, y - hw + a.y, z - hw + a.z }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false, { 0, 1, 0 }, {}, {}},
/*1*/{{ x - hw + a.x + xSize + w, y - hw + a.y, z - hw + a.z }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*2*/
{{ x - hw + a.x + xSize + w, y - hw + a.y, z - hw + a.z + zSize + w }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*3*/{{ x - hw + a.x, y - hw + a.y, z - hw + a.z + zSize + w }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*4*/ {{x - hw + a.x, y - hw + a.y + ySize + w, z - hw + a.z }, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*5*/ {{x - hw + a.x + xSize + w, y - hw + a.y + ySize + w, z - hw + a.z }, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*6*/ {{x - hw + a.x + xSize + w, y - hw + a.y + ySize + w, z - hw + a.z + zSize + w}, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*7*/ {{x - hw + a.x, y - hw + a.y + ySize + w, z - hw + a.z + zSize + w}, {c.x, c.y, c.z, 1}, {1, 1, 1}, false, {0, 1, 0}, {}, {}},
/*4*/{{ x - hw + a.x, y - hw + a.y + ySize + w, z - hw + a.z }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*5*/
{{ x - hw + a.x + xSize + w, y - hw + a.y + ySize + w, z - hw + a.z }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
/*6*/{{ x - hw + a.x + xSize + w, y - hw + a.y + ySize + w, z - hw + a.z + zSize + w }, { c.x, c.y, c.z, 1 },
{ 1, 1, 1 }, false, { 0, 1, 0 }, {}, {}},
/*7*/
{{ x - hw + a.x, y - hw + a.y + ySize + w, z - hw + a.z + zSize + w }, { c.x, c.y, c.z, 1 }, { 1, 1, 1 }, false,
{ 0, 1, 0 }, {}, {}},
};
std::vector<unsigned int> myInds {
std::vector<unsigned int> myInds{
0, 1, 2, 2, 3, 0,
4, 7, 6, 6, 5, 4,
0, 4, 5, 5, 1, 0,

View File

@ -10,20 +10,22 @@
#include "client/graph/mesh/EntityVertex.h"
class WireframeEntity : public DrawableEntity {
public:
public:
WireframeEntity(SubgamePtr game, DimensionPtr dim, glm::vec3 color) :
DrawableEntity(game, dim, std::make_shared<Model>()), Entity(game, dim),
color(color) {};
void updateMesh(const std::vector<SelectionBox>& boxes, float width);
private:
std::vector<EntityVertex> vertices {};
std::vector<unsigned int> indices {};
private:
std::vector<EntityVertex> vertices{};
std::vector<unsigned int> indices{};
void buildMesh(const std::vector<SelectionBox>& boxes);
void createBox(glm::vec3 a, glm::vec3 b, float x, float y, float z, float xSize, float ySize, float zSize);
glm::vec3 color {};
glm::vec3 color{};
float width = 0.5;
int indOffset = 0;

View File

@ -65,9 +65,9 @@ void Camera::setPitch(double pitch) {
}
void Camera::update() {
front.x = (float)(cos(glm::radians(yaw)) * cos(glm::radians(pitch)));
front.y = (float)(sin(glm::radians(pitch)));
front.z = (float)(sin(glm::radians(yaw)) * cos(glm::radians(pitch)));
front.x = (float) (cos(glm::radians(yaw)) * cos(glm::radians(pitch)));
front.y = (float) (sin(glm::radians(pitch)));
front.z = (float) (sin(glm::radians(yaw)) * cos(glm::radians(pitch)));
front = glm::normalize(front);
right = glm::normalize(glm::cross(front, worldUp));
@ -88,11 +88,11 @@ glm::vec2 Camera::getBufferDimensions() {
return bufferDimensions;
}
bool Camera::inFrustum(glm::vec3 &p) {
bool Camera::inFrustum(glm::vec3& p) {
return frustum.pointInFrustum(p) == Frustum::INSIDE;
}
int Camera::inFrustum(FrustumAABB &b) {
int Camera::inFrustum(FrustumAABB& b) {
return frustum.boxInFrustum(b);
}

View File

@ -11,33 +11,40 @@
#include "util/frustum/Frustum.h"
class Camera {
public:
public:
Camera();
void create(float buffWidth, float buffHeight, glm::vec3 up);
void changeWindowDimensions(glm::vec2 size);
glm::vec3 getPos();
void setPos(glm::vec3 pos);
void setYaw(double yaw);
void setPitch(double pitch);
glm::mat4 getProjectionMatrix();
glm::mat4 getOrthographicMatrix();
glm::mat4 getViewMatrix();
glm::vec3 getFront();
glm::vec3 getRight();
glm::vec2 getBufferDimensions();
bool inFrustum(glm::vec3 &p);
int inFrustum(FrustumAABB &b);
bool inFrustum(glm::vec3& p);
int inFrustum(FrustumAABB& b);
~Camera();
private:
private:
//Window Size
glm::vec2 bufferDimensions;
@ -66,6 +73,7 @@ private:
double pitch;
void createMatrices();
void update();
};

View File

@ -7,15 +7,18 @@
class Renderer;
class Drawable {
public:
public:
virtual void update(double delta) {};
virtual void draw(Renderer& renderer) {};
virtual bool isVisible() { return visible; }
virtual void setVisible(bool visible) { this->visible = visible; }
virtual ~Drawable() = default;
protected:
protected:
bool visible = true;
};

View File

@ -4,17 +4,17 @@
#include "DrawableGroup.h"
void DrawableGroup::draw(Renderer &renderer) {
void DrawableGroup::draw(Renderer& renderer) {
for (auto drawable : children) {
drawable->draw(renderer);
}
}
void DrawableGroup::addDrawable(Drawable *drawable) {
void DrawableGroup::addDrawable(Drawable* drawable) {
children.push_back(drawable);
}
void DrawableGroup::removeDrawable(Drawable *drawable) {
void DrawableGroup::removeDrawable(Drawable* drawable) {
for (auto it = children.begin(); it < children.end(); ++it) {
if (*it == drawable) {
children.erase(it);
@ -35,6 +35,6 @@ DrawableGroup::~DrawableGroup() {
clearDrawables();
}
std::vector<Drawable *> &DrawableGroup::getChildren() {
std::vector<Drawable*>& DrawableGroup::getChildren() {
return children;
}

View File

@ -9,17 +9,20 @@
#include "Drawable.h"
class DrawableGroup : public Drawable {
public:
public:
void draw(Renderer& renderer) override;
void addDrawable(Drawable* drawable);
void removeDrawable(Drawable* drawable);
void clearDrawables();
std::vector<Drawable*>& getChildren();
~DrawableGroup() override;
protected:
std::vector<Drawable*> children {};
protected:
std::vector<Drawable*> children{};
};

View File

@ -22,13 +22,13 @@ unsigned int Font::getCharWidth(char c) {
return charWidths[index];
}
void Font::getCharWidths(TextureAtlas &atlas) {
void Font::getCharWidths(TextureAtlas& atlas) {
auto& data = atlas.atlasData;
charWidths[0] = 2;
for (unsigned int i = 1; i < amountOfChars; i++) {
glm::vec2 charPos = {i % 18 * charWidth, std::floor(i / 18) * charHeight};
glm::vec2 charPos = { i % 18 * charWidth, std::floor(i / 18) * charHeight };
unsigned int xBase = static_cast<unsigned int>(fontTex->pos.x) + static_cast<unsigned int>(charPos.x);
unsigned int yBase = static_cast<unsigned int>(fontTex->pos.y) + static_cast<unsigned int>(charPos.y);
@ -59,7 +59,7 @@ glm::vec4 Font::getCharUVs(char c) {
unsigned int index = static_cast<unsigned int>(c) - 32;
if (index >= amountOfChars) throw std::runtime_error("Invalid char index.");
glm::vec2 charPos = {(index % 18) * charWidth, std::floor(index / 18) * charHeight};
glm::vec2 charPos = { (index % 18) * charWidth, std::floor(index / 18) * charHeight };
glm::vec4 uv = {
fontTex->uv.x + (charPos.x) / atlasSize.x,
fontTex->uv.y + (charPos.y) / atlasSize.y,

View File

@ -9,23 +9,27 @@
#include <glm/vec4.hpp>
class AtlasRef;
class TextureAtlas;
class Font {
public:
public:
Font() = default;
Font(TextureAtlas& atlas, std::shared_ptr<AtlasRef> tex);
unsigned int getCharWidth(char c);
glm::vec4 getCharUVs(char c);
const static unsigned int amountOfChars = 95;
const static unsigned int charWidth = 7;
const static unsigned int charHeight = 9;
private:
private:
void getCharWidths(TextureAtlas& atlas);
glm::vec2 atlasSize {};
glm::vec2 atlasSize{};
std::shared_ptr<AtlasRef> fontTex = nullptr;
std::array<unsigned short, 95> charWidths {};
std::array<unsigned short, 95> charWidths{};
};

View File

@ -21,7 +21,7 @@ void Model::fromMesh(std::unique_ptr<EntityMesh> mesh) {
meshes.push_back(std::move(mesh));
}
int Model::fromFile(const std::string &path, const std::vector<std::shared_ptr<AtlasRef>> &textures) {
int Model::fromFile(const std::string& path, const std::vector<std::shared_ptr<AtlasRef>>& textures) {
this->textures = textures;
Assimp::Importer importer;
@ -46,7 +46,8 @@ int Model::fromSerialized(const SerializedModel& model, const std::vector<std::s
this->textures = textures;
Assimp::Importer importer;
const aiScene* scene = importer.ReadFileFromMemory(model.data.data(), model.data.length(), aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenNormals, "B3D");
const aiScene* scene = importer.ReadFileFromMemory(model.data.data(), model.data.length(),
aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenNormals, "B3D");
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
std::cout << Log::err << "ERROR::ASSIMP::" << importer.GetErrorString() << Log::endl;
@ -76,11 +77,11 @@ void Model::getTransformsByFrame(double frame, glm::ivec2 bounds, std::vector<gl
// getTransformsByFrame(frameTime, transforms);
//}
const ModelAnimation &Model::getAnimation() {
const ModelAnimation& Model::getAnimation() {
return animation;
}
void Model::loadModelMeshes(aiNode *node, const aiScene *scene) {
void Model::loadModelMeshes(aiNode* node, const aiScene* scene) {
for (unsigned int i = 0; i < node->mNumMeshes; i++) {
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
meshes.emplace_back(std::make_unique<EntityMesh>());
@ -92,17 +93,17 @@ void Model::loadModelMeshes(aiNode *node, const aiScene *scene) {
}
}
void Model::loadMeshAndBone(aiMesh *mesh, std::unique_ptr<EntityMesh>& target) {
void Model::loadMeshAndBone(aiMesh* mesh, std::unique_ptr<EntityMesh>& target) {
std::vector<EntityVertex> vertices;
std::vector<unsigned int> indices;
//Process Vertices
for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
EntityVertex vertex {};
EntityVertex vertex{};
vertex.position = {mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z};
vertex.normal = {mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z};
vertex.colorBlend = {1, 1, 1};
vertex.position = { mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z };
vertex.normal = { mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z };
vertex.colorBlend = { 1, 1, 1 };
assert(mesh->mMaterialIndex >= 0 && mesh->mMaterialIndex < textures.size());
@ -116,7 +117,7 @@ void Model::loadMeshAndBone(aiMesh *mesh, std::unique_ptr<EntityMesh>& target) {
texture->uv.y + mesh->mTextureCoords[0][i].y * (texture->uv.w - texture->uv.y), 0, 1 //Alpha
};
}
else vertex.colorData = {1, 1, 1, 1};
else vertex.colorData = { 1, 1, 1, 1 };
vertices.push_back(vertex);
}
@ -134,7 +135,7 @@ void Model::loadMeshAndBone(aiMesh *mesh, std::unique_ptr<EntityMesh>& target) {
for (unsigned int i = 0; i < mesh->mNumBones; i++) {
aiBone* bone = mesh->mBones[i];
bones[i] = ModelBone(static_cast<unsigned int>(i), -1, {bone->mName.data});
bones[i] = ModelBone(static_cast<unsigned int>(i), -1, { bone->mName.data });
bones[i].offsetMatrix = glm::transpose(MatConv::AiToGLMMat4(bone->mOffsetMatrix));
for (unsigned int j = 0; j < bone->mNumWeights; j++) {
@ -156,7 +157,7 @@ void Model::loadMeshAndBone(aiMesh *mesh, std::unique_ptr<EntityMesh>& target) {
target->create(vertices, indices);
}
void Model::loadAnimations(const aiScene *scene) {
void Model::loadAnimations(const aiScene* scene) {
assert(scene->mNumAnimations <= 1);
if (scene->mNumAnimations == 1) {
@ -174,7 +175,7 @@ void Model::loadAnimations(const aiScene *scene) {
int index = -1;
for (unsigned int k = 0; k < bones.size(); k++) {
if (std::string {aiChannel->mNodeName.data} == bones[k].name) {
if (std::string{ aiChannel->mNodeName.data } == bones[k].name) {
index = k;
continue;
}
@ -185,38 +186,39 @@ void Model::loadAnimations(const aiScene *scene) {
}
else {
animation.channels[index] = AnimChannel(static_cast<unsigned int>(index), aiChannel->mNodeName.data);
AnimChannel &channel = animation.channels[index];
AnimChannel& channel = animation.channels[index];
//Copy Rotation Keys
channel.rotationKeys.reserve(aiChannel->mNumRotationKeys);
for (unsigned int k = 0; k < aiChannel->mNumRotationKeys; k++) {
aiQuatKey *key = &aiChannel->mRotationKeys[k];
aiQuatKey* key = &aiChannel->mRotationKeys[k];
channel.rotationKeys.emplace_back(key->mTime, key->mValue);
}
//Copy Position Keys
channel.positionKeys.reserve(aiChannel->mNumPositionKeys);
for (unsigned int k = 0; k < aiChannel->mNumPositionKeys; k++) {
aiVectorKey *key = &aiChannel->mPositionKeys[k];
aiVectorKey* key = &aiChannel->mPositionKeys[k];
channel.positionKeys.emplace_back(key->mTime,
glm::vec3{key->mValue.x, key->mValue.y, key->mValue.z});
glm::vec3{ key->mValue.x, key->mValue.y, key->mValue.z });
}
//Copy Scale Keys
channel.scaleKeys.reserve(aiChannel->mNumScalingKeys);
for (unsigned int k = 0; k < aiChannel->mNumScalingKeys; k++) {
aiVectorKey *key = &aiChannel->mScalingKeys[k];
channel.scaleKeys.emplace_back(key->mTime, glm::vec3{key->mValue.x, key->mValue.y, key->mValue.z});
aiVectorKey* key = &aiChannel->mScalingKeys[k];
channel.scaleKeys.emplace_back(key->mTime,
glm::vec3{ key->mValue.x, key->mValue.y, key->mValue.z });
}
}
}
}
}
void Model::calcBoneHeirarchy(aiNode *node, const aiScene *scene, int parentBoneIndex) {
void Model::calcBoneHeirarchy(aiNode* node, const aiScene* scene, int parentBoneIndex) {
int index = -1;
for (auto &bone : bones) {
for (auto& bone : bones) {
if (bone.name == std::string(node->mName.data)) {
bone.parent = parentBoneIndex;
index = bone.index;
@ -229,9 +231,10 @@ void Model::calcBoneHeirarchy(aiNode *node, const aiScene *scene, int parentBone
for (unsigned int i = 0; i < node->mNumChildren; i++) calcBoneHeirarchy(node->mChildren[i], scene, index);
}
void Model::calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 parentTransform, glm::ivec2 bounds, std::vector<glm::mat4>& transforms) {
void Model::calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 parentTransform, glm::ivec2 bounds,
std::vector<glm::mat4>& transforms) {
AnimChannel* channel = nullptr;
for (auto &i : animation.channels) {
for (auto& i : animation.channels) {
if (i.index == bone.index) {
channel = &i;
break;
@ -240,10 +243,11 @@ void Model::calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 p
glm::mat4 boneTransformation(1.0f);
if (channel) {
glm::mat4 position = glm::translate(glm::mat4(1.0), calcBoneVal<glm::vec3>(animTime, bounds, channel->positionKeys, {},
[](const glm::vec3 &a, const glm::vec3 &b, float factor) { return glm::mix(a, b, factor); }));
glm::mat4 position = glm::translate(glm::mat4(1.0),
calcBoneVal<glm::vec3>(animTime, bounds, channel->positionKeys, {},
[](const glm::vec3& a, const glm::vec3& b, float factor) { return glm::mix(a, b, factor); }));
glm::mat4 scale = glm::scale(glm::mat4(1.0), calcBoneVal<glm::vec3>(animTime, bounds, channel->scaleKeys, {},
[](const glm::vec3 &a, const glm::vec3 &b, float factor) { return glm::mix(a, b, factor); }));
[](const glm::vec3& a, const glm::vec3& b, float factor) { return glm::mix(a, b, factor); }));
glm::mat4 rotation = glm::transpose(glm::mat4(MatConv::AiToGLMMat3(
calcBoneVal<aiQuaternion>(animTime, bounds, channel->rotationKeys, {},
[](const aiQuaternion& a, const aiQuaternion& b, float factor) {
@ -258,5 +262,6 @@ void Model::calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 p
glm::mat4 globalTransformation = parentTransform * boneTransformation;
transforms[bone.index] = globalInverseTransform * globalTransformation * bone.offsetMatrix;
for (auto& child : bone.children) calcBoneTransformation(animTime, *child, globalTransformation, bounds, transforms);
for (auto& child : bone.children)
calcBoneTransformation(animTime, *child, globalTransformation, bounds, transforms);
}

View File

@ -16,15 +16,18 @@
#include "client/graph/mesh/EntityMesh.h"
class AtlasRef;
class SerializedModel;
class Model {
public:
public:
Model() = default;
void fromMesh(std::unique_ptr<EntityMesh> mesh);
int fromFile(const std::string &path, const std::vector<std::shared_ptr<AtlasRef>> &texture);
int fromSerialized(const SerializedModel &model, const std::vector<std::shared_ptr<AtlasRef>> &texture);
int fromFile(const std::string& path, const std::vector<std::shared_ptr<AtlasRef>>& texture);
int fromSerialized(const SerializedModel& model, const std::vector<std::shared_ptr<AtlasRef>>& texture);
void getTransformsByFrame(double frame, glm::ivec2 bounds, std::vector<glm::mat4>& transforms);
// void getTransformsByTime(double time, std::tuple<uint> bounds, std::vector<glm::mat4>& transforms);
@ -32,15 +35,20 @@ public:
const ModelAnimation& getAnimation();
std::vector<std::unique_ptr<EntityMesh>> meshes;
private:
void loadModelMeshes(aiNode *node, const aiScene *scene);
void loadMeshAndBone(aiMesh *mesh, std::unique_ptr<EntityMesh> &target);
void loadAnimations(const aiScene *scene);
private:
void loadModelMeshes(aiNode* node, const aiScene* scene);
void calcBoneHeirarchy(aiNode *node, const aiScene *scene, int parentBoneIndex);
void calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 parentTransform, glm::ivec2 bounds, std::vector<glm::mat4>& transforms);
void loadMeshAndBone(aiMesh* mesh, std::unique_ptr<EntityMesh>& target);
template <typename T> static inline T calcBoneVal(
void loadAnimations(const aiScene* scene);
void calcBoneHeirarchy(aiNode* node, const aiScene* scene, int parentBoneIndex);
void calcBoneTransformation(double animTime, ModelBone& bone, glm::mat4 parentTransform, glm::ivec2 bounds,
std::vector<glm::mat4>& transforms);
template<typename T>
static inline T calcBoneVal(
double animTime, glm::ivec2 bounds, const std::vector<std::pair<double, T>>& keysArray,
const T& def, std::function<T(const T& a, const T& b, float factor)> merge) {
@ -65,11 +73,11 @@ private:
return merge(keysArray[index].second, keysArray[nextIndex].second, factor);
}
ModelAnimation animation {};
std::vector<ModelBone*> rootBones {};
std::vector<ModelBone> bones {};
std::vector<std::shared_ptr<AtlasRef>> textures {};
ModelAnimation animation{};
std::vector<ModelBone*> rootBones{};
std::vector<ModelBone> bones{};
std::vector<std::shared_ptr<AtlasRef>> textures{};
glm::mat4 globalInverseTransform {};
glm::mat4 globalInverseTransform{};
};

View File

@ -10,12 +10,13 @@
#include "world/dim/ent/AnimChannel.h"
class ModelAnimation {
public:
public:
ModelAnimation() = default;
explicit ModelAnimation(const std::string& name);
std::string name = "";
std::vector<AnimChannel> channels {};
std::vector<AnimChannel> channels{};
unsigned int duration = 0;
double ticksPerSecond = 0;
};

View File

@ -9,15 +9,16 @@
#include <glm/mat4x4.hpp>
class ModelBone {
public:
public:
ModelBone() = default;
ModelBone(unsigned int index, int parent, const std::string& name);
std::string name {};
std::string name{};
unsigned int index = 0;
int parent = 0;
glm::mat4 offsetMatrix {};
glm::mat4 offsetMatrix{};
std::vector<ModelBone*> children;
};

View File

@ -6,24 +6,25 @@
#include "Renderer.h"
Renderer::Renderer() : Renderer({1366, 768}) {};
Renderer::Renderer() : Renderer({ 1366, 768 }) {};
Renderer::Renderer(glm::ivec2 win) :
activeTexture(nullptr),
window(win),
world (win, 2),
world(win, 2),
entity(win, 2),
ssao (win, 1, 24),
blur (win, 1),
light (win, 2) {
ssao(win, 1, 24),
blur(win, 1),
light(win, 2) {
camera.create(window.getSize().x, window.getSize().y, glm::vec3(0, 1, 0));
ssao.createFromFile("../assets/shader/post/passThrough.vs", "../assets/shader/post/ssaoCalc.fs");
blur.createFromFile("../assets/shader/post/passThrough.vs", "../assets/shader/post/ssaoBlur.fs");
light.createFromFile("../assets/shader/post/passThrough.vs", "../assets/shader/post/deferredLighting.fs");
world.createFromFile("../assets/shader/world/world.vs", "../assets/shader/world/world.fs", "../assets/shader/world/world.gs");
world.createFromFile("../assets/shader/world/world.vs", "../assets/shader/world/world.fs",
"../assets/shader/world/world.gs");
entity.createFromFile("../assets/shader/world/entity.vs", "../assets/shader/world/entity.fs");
guiShader = Shader();
@ -70,13 +71,14 @@ void Renderer::beginChunkDeferredCalls() {
glDepthFunc(GL_LESS);
glDisable(GL_BLEND);
glViewport(0, 0, static_cast<int>(world.windowSize.x * world.bufferScale), static_cast<int>(world.windowSize.y * world.bufferScale));
glViewport(0, 0, static_cast<int>(world.windowSize.x * world.bufferScale),
static_cast<int>(world.windowSize.y * world.bufferScale));
glBindFramebuffer(GL_FRAMEBUFFER, light.gBuffer);
glClear(GL_DEPTH_BUFFER_BIT);
const float skyColor[] = {clearColor.x, clearColor.y, clearColor.z, 1};
static const float clearTransparent[] = {0, 0, 0, 1};
const float skyColor[] = { clearColor.x, clearColor.y, clearColor.z, 1 };
static const float clearTransparent[] = { 0, 0, 0, 1 };
glClearBufferfv(GL_COLOR, 0, clearTransparent);
glClearBufferfv(GL_COLOR, 1, clearTransparent);
glClearBufferfv(GL_COLOR, 2, skyColor);
@ -177,7 +179,7 @@ void Renderer::setShader(Shader& s) {
}
void Renderer::setClearColor(unsigned char r, unsigned char g, unsigned char b) {
clearColor = {static_cast<float>(r)/255.f, static_cast<float>(g)/255.f, static_cast<float>(b)/255.f, 1};
clearColor = { static_cast<float>(r) / 255.f, static_cast<float>(g) / 255.f, static_cast<float>(b) / 255.f, 1 };
}
void Renderer::toggleDepthTest(bool enable) {
@ -192,16 +194,17 @@ void Renderer::setModelMatrix(const glm::mat4& modelMatrix) {
glUniformMatrix4fv(currentModelUniform, 1, GL_FALSE, glm::value_ptr(modelMatrix));
}
void Renderer::setBones(std::vector<glm::mat4> &transforms) {
void Renderer::setBones(std::vector<glm::mat4>& transforms) {
if (transforms.empty()) return;
currentShader->setArr((currentShader == &entity ? entity.uniforms.bones : gu.bones), static_cast<GLsizei>(transforms.size()), transforms.at(0));
currentShader->setArr((currentShader == &entity ? entity.uniforms.bones : gu.bones),
static_cast<GLsizei>(transforms.size()), transforms.at(0));
}
void Renderer::setClipBounds(glm::vec4 bounds) {
guiShader.set(gu.clipBounds, {bounds.x, window.getSize().y - bounds.w, bounds.z, window.getSize().y - bounds.y});
guiShader.set(gu.clipBounds, { bounds.x, window.getSize().y - bounds.w, bounds.z, window.getSize().y - bounds.y });
}
void Renderer::enableTexture(Texture *texture) {
void Renderer::enableTexture(Texture* texture) {
if (texture != activeTexture) {
activeTexture = texture;
texture->use(0);
@ -223,9 +226,9 @@ void Renderer::renderQuad() {
glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *) nullptr);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*) nullptr);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void *) (3 * sizeof(float)));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*) (3 * sizeof(float)));
}
glBindVertexArray(quadVAO);

View File

@ -17,38 +17,48 @@
#include "shader/GuiUniforms.h"
class Renderer {
public:
public:
Renderer();
Renderer(glm::ivec2 win);
void update(double delta);
void beginChunkDeferredCalls();
void beginEntityDeferredCalls();
void endDeferredCalls();
void beginGUIDrawCalls();
void swapBuffers();
void setShader(Shader& s);
void setClearColor(unsigned char r, unsigned char g, unsigned char b);
static void toggleDepthTest(bool enable);
static void clearDepthBuffer();
void setModelMatrix(const glm::mat4& modelMatrix);
void setBones(std::vector<glm::mat4>& transforms);
void setClipBounds(glm::vec4 bounds);
void enableTexture(Texture* texture);
Window window;
Camera camera;
private:
private:
void renderQuad();
unsigned int quadVAO = 0;
unsigned int quadVBO = 0;
glm::vec4 clearColor {0, 0, 0, 1};
glm::vec4 clearColor{ 0, 0, 0, 1 };
Texture* activeTexture;
WorldGeometryShader world;

View File

@ -13,7 +13,7 @@ Texture::Texture(const std::string& file) :
}
void Texture::loadFromFile(std::string file) {
unsigned char *texData = stbi_load(file.c_str(), &width, &height, &bitDepth, 0);
unsigned char* texData = stbi_load(file.c_str(), &width, &height, &bitDepth, 0);
if (!texData) throw std::runtime_error("Failed to find texture at " + file + ".");
loadFromBytes(texData, width, height);
stbi_image_free(texData);
@ -40,7 +40,7 @@ void Texture::loadFromBytes(unsigned char* bytes, int width, int height, GLint i
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture::updateTexture(int x, int y, int width, int height, unsigned char *bytes) {
void Texture::updateTexture(int x, int y, int width, int height, unsigned char* bytes) {
glBindTexture(GL_TEXTURE_2D, textureID);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, bytes);
}

View File

@ -8,20 +8,25 @@
#include <GL/glew.h>
class Texture {
public:
public:
Texture() = default;
explicit Texture(const std::string& file);
void loadFromFile(std::string file);
void loadFromBytes(unsigned char* bytes, int width, int height, GLint interpolation = GL_NEAREST, GLint repeatMode = GL_CLAMP_TO_EDGE);
void loadFromBytes(unsigned char* bytes, int width, int height, GLint interpolation = GL_NEAREST,
GLint repeatMode = GL_CLAMP_TO_EDGE);
void updateTexture(int x, int y, int width, int height, unsigned char* bytes);
void use(GLuint position = 0);
void clear();
~Texture();
protected:
protected:
unsigned int textureID = 0;
int width = 0;
int height = 0;

View File

@ -21,7 +21,7 @@ void ChunkMesh::create(const std::vector<ChunkVertex>& vertices, const std::vect
createVertexAttrib(idx++, 1, GL_FLOAT, STRIDE_OFFSET_CHUNK(normal));
createVertexAttrib(idx++, 4, GL_FLOAT, STRIDE_OFFSET_CHUNK(light));
createVertexAttrib(idx++, 1, GL_FLOAT, STRIDE_OFFSET_CHUNK(shaderMod));
createVertexAttrib(idx , 3, GL_FLOAT, STRIDE_OFFSET_CHUNK(modValues));
createVertexAttrib(idx, 3, GL_FLOAT, STRIDE_OFFSET_CHUNK(modValues));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

View File

@ -12,8 +12,9 @@
class ChunkVertex;
class ChunkMesh : public Mesh {
public:
public:
ChunkMesh() = default;
ChunkMesh(const ChunkMesh& o) { throw std::runtime_error("No copy constructor for ChunkMeshes"); };
void create(const std::vector<ChunkVertex>& vertices, const std::vector<unsigned int>& indices);

View File

@ -5,6 +5,7 @@
#include <vector>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/normal.hpp>
#include "ChunkMeshGenerator.h"
@ -21,8 +22,10 @@
#include "game/atlas/LocalBiomeAtlas.h"
#include "game/atlas/LocalDefinitionAtlas.h"
ChunkMeshGenerator::ChunkMeshGenerator(ChunkMeshDetails* meshDetails, LocalDefinitionAtlas& defs, LocalBiomeAtlas& biomes,
std::shared_ptr<Chunk> chunk, std::array<std::shared_ptr<Chunk>, 6> adjacent, std::array<NoiseSample, 3>& blockOffsets) :
ChunkMeshGenerator::ChunkMeshGenerator(ChunkMeshDetails* meshDetails, LocalDefinitionAtlas& defs,
LocalBiomeAtlas& biomes,
std::shared_ptr<Chunk> chunk, std::array<std::shared_ptr<Chunk>, 6> adjacent,
std::array<NoiseSample, 3>& blockOffsets) :
meshDetails(meshDetails),
adjacent(adjacent),
biomes(biomes),
@ -57,24 +60,33 @@ ChunkMeshGenerator::ChunkMeshGenerator(ChunkMeshDetails* meshDetails, LocalDefin
for (auto& mod : model.meshMods) {
switch (mod.first) {
default: break;
case MeshMod::OFFSET_X: vis.x += blockOffsets[0].get(vis / 16.f) * mod.second; break;
case MeshMod::OFFSET_Y: vis.y += blockOffsets[1].get(vis / 16.f) * mod.second; break;
case MeshMod::OFFSET_Z: vis.z += blockOffsets[2].get(vis / 16.f) * mod.second; break;
case MeshMod::OFFSET_X: vis.x += blockOffsets[0].get(vis / 16.f) * mod.second;
break;
case MeshMod::OFFSET_Y: vis.y += blockOffsets[1].get(vis / 16.f) * mod.second;
break;
case MeshMod::OFFSET_Z: vis.z += blockOffsets[2].get(vis / 16.f) * mod.second;
break;
}
}
glm::ivec3 pos = { off.x - 1, off.y, off.z };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::XNEG)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::XNEG)], biomeTint, getLightAt(pos));
pos = { off.x + 1, off.y, off.z };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::XPOS)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::XPOS)], biomeTint, getLightAt(pos));
pos = { off.x, off.y - 1, off.z };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::YNEG)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::YNEG)], biomeTint, getLightAt(pos));
pos = { off.x, off.y + 1, off.z };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::YPOS)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::YPOS)], biomeTint, getLightAt(pos));
pos = { off.x, off.y, off.z - 1 };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::ZNEG)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::ZNEG)], biomeTint, getLightAt(pos));
pos = { off.x, off.y, off.z + 1 };
if (!getBlockAt(pos).culls) addFaces(vis, model.parts[static_cast<int>(EVec::ZPOS)], biomeTint, getLightAt(pos));
if (!getBlockAt(pos).culls)
addFaces(vis, model.parts[static_cast<int>(EVec::ZPOS)], biomeTint, getLightAt(pos));
addFaces(vis, model.parts[static_cast<int>(EVec::NO_CULL)], biomeTint, getLightAt(vis));
}
@ -86,10 +98,10 @@ ChunkMeshGenerator::ChunkMeshGenerator(ChunkMeshDetails* meshDetails, LocalDefin
}
BlockDef& ChunkMeshGenerator::getBlockAt(const glm::ivec3& pos) {
glm::ivec3 dir = {(pos.x < 0 ? -1 : pos.x > 15 ? 1 : 0),
(pos.y < 0 ? -1 : pos.y > 15 ? 1 : 0), (pos.z < 0 ? -1 : pos.z > 15 ? 1 : 0)};
glm::ivec3 dir = { (pos.x < 0 ? -1 : pos.x > 15 ? 1 : 0),
(pos.y < 0 ? -1 : pos.y > 15 ? 1 : 0), (pos.z < 0 ? -1 : pos.z > 15 ? 1 : 0) };
if (dir != glm::ivec3 {0, 0, 0}) {
if (dir != glm::ivec3{ 0, 0, 0 }) {
unsigned int ind = static_cast<unsigned int>(Vec::TO_ENUM.at(dir));
auto& chunk = adjacent[ind];
return defs.blockFromId(chunk->getBlock(Space::Block::index(pos - dir * 16)));
@ -99,10 +111,10 @@ BlockDef& ChunkMeshGenerator::getBlockAt(const glm::ivec3& pos) {
}
glm::vec4 ChunkMeshGenerator::getLightAt(const glm::ivec3& pos) {
glm::ivec3 dir = {(pos.x < 0 ? -1 : pos.x > 15 ? 1 : 0),
(pos.y < 0 ? -1 : pos.y > 15 ? 1 : 0), (pos.z < 0 ? -1 : pos.z > 15 ? 1 : 0)};
glm::ivec3 dir = { (pos.x < 0 ? -1 : pos.x > 15 ? 1 : 0),
(pos.y < 0 ? -1 : pos.y > 15 ? 1 : 0), (pos.z < 0 ? -1 : pos.z > 15 ? 1 : 0) };
if (dir != glm::ivec3 {0, 0, 0}) {
if (dir != glm::ivec3{ 0, 0, 0 }) {
unsigned int ind = static_cast<unsigned int>(Vec::TO_ENUM.at(dir));
auto& chunk = adjacent[ind];
return chunk->getLight(Space::Block::index(pos - dir * 16));
@ -111,7 +123,9 @@ glm::vec4 ChunkMeshGenerator::getLightAt(const glm::ivec3& pos) {
return chunk->getLight(Space::Block::index(pos));
}
void ChunkMeshGenerator::addFaces(const glm::vec3 &offset, const std::vector<MeshPart> &meshParts, const glm::vec3& tint, glm::vec4 light) {
void
ChunkMeshGenerator::addFaces(const glm::vec3& offset, const std::vector<MeshPart>& meshParts, const glm::vec3& tint,
glm::vec4 light) {
for (const MeshPart& mp : meshParts) {
glm::vec3 modData = {};
@ -122,17 +136,16 @@ void ChunkMeshGenerator::addFaces(const glm::vec3 &offset, const std::vector<Mes
case ShaderMod::ROTATE_Y:
case ShaderMod::ROTATE_Z:
case ShaderMod::SWAY_ATTACHED:
case ShaderMod::SWAY_FULL_BLOCK:
modData = { Util::packFloat((offset - 8.f) / 8.f), mp.modValue, 0 };
case ShaderMod::SWAY_FULL_BLOCK:modData = { Util::packFloat((offset - 8.f) / 8.f), mp.modValue, 0 };
break;
}
for (const BlockModelVertex &vertex : mp.vertices) {
for (const BlockModelVertex& vertex : mp.vertices) {
meshDetails->vertices.push_back({
vertex.pos + offset,
vertex.tex,
mp.blendInd ? tint : glm::vec3 {1, 1, 1},
mp.blendInd ? vertex.blendMask : glm::vec2 {-1, -1},
mp.blendInd ? tint : glm::vec3{ 1, 1, 1 },
mp.blendInd ? vertex.blendMask : glm::vec2{ -1, -1 },
Util::packFloat(vertex.nml),
glm::vec4(light),
static_cast<float>(mp.shaderMod),

View File

@ -9,23 +9,32 @@
#include <memory>
class Chunk;
class MeshPart;
class BlockDef;
class NoiseSample;
class LocalBiomeAtlas;
class ChunkMeshDetails;
class LocalDefinitionAtlas;
class ChunkMeshGenerator {
public:
public:
ChunkMeshGenerator(ChunkMeshDetails* meshDetails, LocalDefinitionAtlas& defs, LocalBiomeAtlas& biomes,
std::shared_ptr<Chunk> chunk, std::array<std::shared_ptr<Chunk>, 6> adjacent,
std::array<NoiseSample, 3>& blockOffsets);
private:
private:
inline BlockDef& getBlockAt(const glm::ivec3& pos);
inline glm::vec4 getLightAt(const glm::ivec3& pos);
void addFaces(const glm::vec3 &offset, const std::vector<MeshPart> &meshParts, const glm::vec3& tint, glm::vec4 light);
void
addFaces(const glm::vec3& offset, const std::vector<MeshPart>& meshParts, const glm::vec3& tint, glm::vec4 light);
LocalDefinitionAtlas& defs;
LocalBiomeAtlas& biomes;

View File

@ -10,7 +10,9 @@ class Renderer;
struct ChunkRenderElem {
virtual void draw(Renderer& renderer) = 0;
virtual glm::vec3 getPos() = 0;
// Used to determine if the RenderElem should be deleted.
// Bool is if the RenderElem should be kept alive.
// True = keep, False = remove

View File

@ -4,7 +4,7 @@
#include "EntityMesh.h"
EntityMesh::EntityMesh(const EntityMesh &o) :
EntityMesh::EntityMesh(const EntityMesh& o) :
vertices(o.vertices),
indices(o.indices) {
this->indCount = o.indCount;
@ -33,7 +33,7 @@ void EntityMesh::initModel() {
createVertexAttrib(idx++, 1, GL_FLOAT, STRIDE_OFFSET_ENTITY(useTex));
createVertexAttrib(idx++, 3, GL_FLOAT, STRIDE_OFFSET_ENTITY(normal));
createVertexAttrib(idx++, 4, GL_INT, STRIDE_OFFSET_ENTITY(boneIDs));
createVertexAttrib(idx , 4, GL_FLOAT, STRIDE_OFFSET_ENTITY(boneWeights));
createVertexAttrib(idx, 4, GL_FLOAT, STRIDE_OFFSET_ENTITY(boneWeights));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

View File

@ -11,14 +11,18 @@
#include "EntityVertex.h"
class EntityMesh : public Mesh {
public:
public:
EntityMesh() = default;
EntityMesh(const EntityMesh& o);
void create(const std::vector<EntityVertex>& vertices, const std::vector<unsigned int>& indices);
~EntityMesh() = default;
private:
private:
void initModel();
std::vector<EntityVertex> vertices {};
std::vector<unsigned int> indices {};
std::vector<EntityVertex> vertices{};
std::vector<unsigned int> indices{};
};

View File

@ -8,19 +8,20 @@
#include <glm/vec4.hpp>
class EntityVertex {
public:
public:
EntityVertex() = default;
EntityVertex(glm::vec3 position, glm::vec4 colorData, glm::vec3 colorBlend, float useTex, glm::vec3 normal,
glm::ivec4 boneIDs, glm::vec4 boneWeights) : position(position), colorData(colorData),
colorBlend(colorBlend), useTex(useTex), normal(normal), boneIDs(boneIDs), boneWeights(boneWeights) {};
glm::vec3 position {};
glm::vec4 colorData {};
glm::vec3 colorBlend {};
glm::vec3 position{};
glm::vec4 colorData{};
glm::vec3 colorBlend{};
float useTex = false;
glm::vec3 normal {};
glm::ivec4 boneIDs {};
glm::vec4 boneWeights {};
glm::vec3 normal{};
glm::ivec4 boneIDs{};
glm::vec4 boneWeights{};
};
#define STRIDE_OFFSET_ENTITY(m) sizeof(struct EntityVertex), (void *)offsetof(struct EntityVertex, m)

View File

@ -15,7 +15,7 @@ void Mesh::cleanup() {
indCount = 0;
}
void Mesh::genArrays(GLuint vboLength, GLuint iboLength, const void *verticesPtr, const void *indicesPtr) {
void Mesh::genArrays(GLuint vboLength, GLuint iboLength, const void* verticesPtr, const void* indicesPtr) {
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
@ -28,7 +28,7 @@ void Mesh::genArrays(GLuint vboLength, GLuint iboLength, const void *verticesPtr
glBufferData(GL_ARRAY_BUFFER, vboLength, verticesPtr, GL_STATIC_DRAW);
}
void Mesh::createVertexAttrib(GLuint offset, GLuint size, GLenum type, GLsizei stride, const void *pointer) {
void Mesh::createVertexAttrib(GLuint offset, GLuint size, GLenum type, GLsizei stride, const void* pointer) {
glEnableVertexAttribArray(offset);
if (type == GL_INT)
glVertexAttribIPointer(offset, size, type, stride, pointer);

View File

@ -7,15 +7,18 @@
#include <GL/glew.h>
class Mesh {
public:
public:
Mesh() = default;
void cleanup();
virtual void draw() const;
~Mesh();
protected:
protected:
void genArrays(GLuint vboLength, GLuint iboLength, const void* verticesPtr, const void* indicesPtr);
void createVertexAttrib(GLuint offset, GLuint size, GLenum type, GLsizei stride, const void* pointer);
GLuint VAO = 0;

View File

@ -10,7 +10,7 @@
#include "client/graph/Renderer.h"
#include "client/graph/mesh/ChunkMesh.h"
void MeshChunk::create(std::vector<ChunkVertex> &vertices, std::vector<unsigned int> &indices) {
void MeshChunk::create(std::vector<ChunkVertex>& vertices, std::vector<unsigned int>& indices) {
this->mesh = std::make_shared<ChunkMesh>();
mesh->create(vertices, indices);
}

View File

@ -11,19 +11,24 @@
#include "client/graph/Drawable.h"
class ChunkMesh;
class ChunkVertex;
class MeshChunk : public ChunkRenderElem, Drawable {
public:
public:
MeshChunk() = default;
void create(std::vector<ChunkVertex> &vertices, std::vector<unsigned int> &indices);
void create(std::vector<ChunkVertex>& vertices, std::vector<unsigned int>& indices);
void draw(Renderer& renderer) override;
bool updateChunkUse(glm::vec3 chunk, bool used) override;
void setPos(glm::vec3 pos);
glm::vec3 getPos() override;
private:
private:
std::shared_ptr<ChunkMesh> mesh = nullptr;
glm::vec3 pos {};
glm::vec3 pos{};
};

View File

@ -18,7 +18,8 @@ void BlurShader::postCreate() {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glGenTextures(1, &colorBuffer);
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0);
@ -30,7 +31,8 @@ void BlurShader::windowResized(glm::ivec2 windowSize) {
this->windowSize = windowSize;
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}

View File

@ -9,8 +9,9 @@
#include "Shader.h"
class BlurShader : public Shader {
public:
public:
explicit BlurShader(glm::ivec2 windowSize, float bufferScale);
void postCreate() override;
void windowResized(glm::ivec2 windowSize);
@ -19,12 +20,12 @@ public:
GLint sampleScale;
};
Uniforms uniforms {};
Uniforms uniforms{};
unsigned int fbo = 0;
unsigned int colorBuffer = 0;
private:
glm::ivec2 windowSize {};
private:
glm::ivec2 windowSize{};
float bufferScale = 1;
};

View File

@ -9,8 +9,9 @@
#include "Shader.h"
class EntityGeometryShader : public Shader {
public:
public:
explicit EntityGeometryShader(glm::ivec2 windowSize, float bufferScale);
void postCreate() override;
struct Uniforms {
@ -21,9 +22,9 @@ public:
GLint bones;
};
Uniforms uniforms {};
Uniforms uniforms{};
private:
glm::ivec2 windowSize {};
private:
glm::ivec2 windowSize{};
float bufferScale = 1;
};

View File

@ -28,7 +28,8 @@ void LightingShader::postCreate() {
glGenTextures(1, &gPosition);
glBindTexture(GL_TEXTURE_2D, gPosition);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
@ -37,25 +38,28 @@ void LightingShader::postCreate() {
glGenTextures(1, &gNormal);
glBindTexture(GL_TEXTURE_2D, gNormal);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gNormal, 0);
glGenTextures(1, &gColorSpec);
glBindTexture(GL_TEXTURE_2D, gColorSpec);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<int>(windowSize.x), static_cast<int>(windowSize.y), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<int>(windowSize.x), static_cast<int>(windowSize.y), 0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gColorSpec, 0);
unsigned int attachments[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
unsigned int attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, attachments);
glGenRenderbuffers(1, &rDepth);
glBindRenderbuffer(GL_RENDERBUFFER, rDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale));
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale));
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rDepth);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
@ -72,22 +76,26 @@ void LightingShader::windowResized(glm::ivec2 windowSize) {
glBindFramebuffer(GL_FRAMEBUFFER, gBuffer);
glBindTexture(GL_TEXTURE_2D, gPosition);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, gPosition, 0);
glBindTexture(GL_TEXTURE_2D, gNormal);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, gNormal, 0);
glBindTexture(GL_TEXTURE_2D, gColorSpec);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, gColorSpec, 0);
unsigned int attachments[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2};
unsigned int attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 };
glDrawBuffers(3, attachments);
glBindRenderbuffer(GL_RENDERBUFFER, rDepth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale));
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale));
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rDepth);
glBindRenderbuffer(GL_RENDERBUFFER, 0);

View File

@ -9,8 +9,9 @@
#include "Shader.h"
class LightingShader : public Shader {
public:
public:
explicit LightingShader(glm::ivec2 windowSize, float bufferScale);
void postCreate() override;
void windowResized(glm::ivec2 windowSize);
@ -24,7 +25,7 @@ public:
GLint camPosition;
};
Uniforms uniforms {};
Uniforms uniforms{};
unsigned int gBuffer = 0;
unsigned int gPosition = 0;
@ -32,7 +33,7 @@ public:
unsigned int gColorSpec = 0;
unsigned int rDepth = 0;
private:
glm::ivec2 windowSize {};
private:
glm::ivec2 windowSize{};
float bufferScale = 1;
};

View File

@ -28,7 +28,7 @@ void SSAOShader::postCreate() {
std::default_random_engine generator;
for (unsigned int i = 0; i < kernelCount; i++) {
glm::vec3 sample {
glm::vec3 sample{
rand(generator) * 2.0 - 1.0,
rand(generator) * 2.0 - 1.0,
rand(generator)
@ -61,7 +61,8 @@ void SSAOShader::postCreate() {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glGenTextures(1, &colorBuffer);
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_FLOAT, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0);
@ -73,7 +74,8 @@ void SSAOShader::windowResized(glm::ivec2 windowSize) {
this->windowSize = windowSize;
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale), static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, static_cast<int>(windowSize.x * bufferScale),
static_cast<int>(windowSize.y * bufferScale), 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0);
glBindTexture(GL_TEXTURE_2D, 0);
}

View File

@ -10,8 +10,9 @@
#include "Shader.h"
class SSAOShader : public Shader {
public:
public:
explicit SSAOShader(glm::ivec2 windowSize, float bufferScale, unsigned int kernelCount);
void postCreate() override;
void windowResized(glm::ivec2 windowSize);
@ -23,19 +24,19 @@ public:
GLint sampleScale;
};
Uniforms uniforms {};
Uniforms uniforms{};
unsigned int kernelCount = 32;
unsigned int sampleCount = 16;
std::vector<glm::vec3> kernels {};
std::vector<glm::vec3> noise {};
std::vector<glm::vec3> kernels{};
std::vector<glm::vec3> noise{};
unsigned int tex = 0;
unsigned int fbo = 0;
unsigned int colorBuffer = 0;
private:
glm::ivec2 windowSize {};
private:
glm::ivec2 windowSize{};
float bufferScale = 1;
};

View File

@ -14,7 +14,8 @@ void Shader::createFromString(std::string& vertexSource, std::string& fragmentSo
compileShader(vertexSource, fragmentSource);
}
void Shader::createFromFile(const std::string& vertexFile, const std::string& fragmentFile, const std::string& geoFile) {
void
Shader::createFromFile(const std::string& vertexFile, const std::string& fragmentFile, const std::string& geoFile) {
compileShader(readFile(vertexFile), readFile(fragmentFile),
geoFile == "" ? "" : readFile(geoFile));
postCreate();
@ -45,7 +46,7 @@ void Shader::clearShader() {
glUseProgram(0);
}
GLint Shader::get(const std::string &name) {
GLint Shader::get(const std::string& name) {
return glGetUniformLocation(shaderID, name.c_str());
}
@ -79,12 +80,13 @@ void Shader::set(int loc, glm::mat4 val) {
glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(val));
}
void Shader::setArr(int loc, unsigned int count, glm::mat4 &start) {
void Shader::setArr(int loc, unsigned int count, glm::mat4& start) {
checkActive();
glUniformMatrix4fv(loc, count, GL_FALSE, glm::value_ptr(start));
}
void Shader::compileShader(const std::string& vertexSource, const std::string& fragmentSource, const std::string& geoSource) {
void Shader::compileShader(const std::string& vertexSource, const std::string& fragmentSource,
const std::string& geoSource) {
shaderID = glCreateProgram();
if (!shaderID) throw std::runtime_error("Failed to create shader program.");
@ -128,7 +130,8 @@ void Shader::addShader(GLuint program, const std::string& shaderCode, GLenum sha
if (!result) {
glGetShaderInfoLog(shader, sizeof(eLog), nullptr, eLog);
std::string shaderTypeName = (shaderType == GL_VERTEX_SHADER) ? "vertex" : (shaderType == GL_FRAGMENT_SHADER) ? "fragment" : "geometry";
std::string shaderTypeName = (shaderType == GL_VERTEX_SHADER) ? "vertex" : (shaderType == GL_FRAGMENT_SHADER)
? "fragment" : "geometry";
throw std::runtime_error("Failed to compile the " + shaderTypeName + " shader. Error:\n" + eLog);
}

View File

@ -10,34 +10,44 @@
#include <glm/mat4x4.hpp>
class Shader {
public:
public:
void createFromString(std::string& vertexSource, std::string& fragmentSource, const std::string& geoSource = "");
void createFromFile(const std::string& vertexFile, const std::string& fragmentFile, const std::string& geoFile = "");
void
createFromFile(const std::string& vertexFile, const std::string& fragmentFile, const std::string& geoFile = "");
virtual void postCreate() {};
int get(const std::string &name);
int get(const std::string& name);
void use();
static void clearShader();
void set(int loc, unsigned int val);
void set(int loc, int val);
void set(int loc, float val);
void set(int loc, glm::vec3 val);
void set(int loc, glm::vec4 val);
void set(int loc, glm::mat4 val);
void setArr(int loc, unsigned int count, glm::mat4 &start);
void setArr(int loc, unsigned int count, glm::mat4& start);
void cleanup();
~Shader();
private:
private:
static std::string readFile(const std::string& fileLocation);
void compileShader(const std::string& vertexSource, const std::string& fragmentSource, const std::string& geoSource = "");
void compileShader(const std::string& vertexSource, const std::string& fragmentSource,
const std::string& geoSource = "");
static void addShader(unsigned int program, const std::string& shaderCode, GLenum shaderType);
void checkActive();

View File

@ -32,12 +32,17 @@ void WorldGeometryShader::postCreate() {
void WorldGeometryShader::windowResized(glm::ivec2 windowSize) {
this->windowSize = windowSize;
}
void WorldGeometryShader::updateSwayMap(double delta) {
swayOffset += delta * 2.8;
for (int i = 0; i < 16 * 16; i++) {
swayData[i*4] = static_cast<unsigned char>((fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset))) + 1) / 2.f * 255.f);
swayData[i*4+1] = static_cast<unsigned char>((fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset + 50))) + 1) / 2.f * 255.f);
swayData[i*4+2] = static_cast<unsigned char>((fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset + 100))) + 1) / 2.f * 255.f);
swayData[i * 4] = static_cast<unsigned char>(
(fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset))) + 1) / 2.f * 255.f);
swayData[i * 4 + 1] = static_cast<unsigned char>(
(fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset + 50))) + 1) / 2.f * 255.f);
swayData[i * 4 + 2] = static_cast<unsigned char>(
(fmax(-1, fmin(1, swayNoise.GetValue((i / 16) / 3.f, (i % 16) / 3.f, swayOffset + 100))) + 1) / 2.f *
255.f);
}
swayTex.updateTexture(0, 0, 16, 16, &swayData[0]);
}

View File

@ -12,11 +12,13 @@
#include "../Texture.h"
class WorldGeometryShader : public Shader {
public:
public:
explicit WorldGeometryShader(glm::ivec2 windowSize, float bufferScale);
void postCreate() override;
void windowResized(glm::ivec2 windowSize);
void updateSwayMap(double delta);
struct Uniforms {
@ -29,13 +31,13 @@ public:
GLint time;
};
Uniforms uniforms {};
Uniforms uniforms{};
Texture swayTex;
double swayOffset = 0;
noise::module::Perlin swayNoise;
std::vector<unsigned char> swayData {};
std::vector<unsigned char> swayData{};
glm::ivec2 windowSize {};
glm::ivec2 windowSize{};
float bufferScale = 1;
};

View File

@ -23,39 +23,39 @@ DebugGui::DebugGui(glm::vec2 bufferSize, SubgamePtr game, WorldPtr world) :
Font f(game.l()->textures, fontRef);
auto crosshairText = std::make_shared<GuiText>("crosshairText");
crosshairText->create({2, 2}, {}, {0.2, 0.2, 0.2, 0.5}, {1, 1, 1, 1}, f);
crosshairText->create({ 2, 2 }, {}, { 0.2, 0.2, 0.2, 0.5 }, { 1, 1, 1, 1 }, f);
add(crosshairText);
auto dataText = std::make_shared<GuiText>("dataText");
dataText->create({2, 2}, {}, {0.2, 0.2, 0.2, 0.5}, {1, 1, 1, 1}, f);
dataText->create({ 2, 2 }, {}, { 0.2, 0.2, 0.2, 0.5 }, { 1, 1, 1, 1 }, f);
add(dataText);
auto interpGraph = std::make_shared<GuiLabelledGraph>("interpGraph");
interpGraph->create({244, 64}, {}, "Interp", 120, 256, genericHistogramRef, f);
interpGraph->create({ 244, 64 }, {}, "Interp", 120, 256, genericHistogramRef, f);
add(interpGraph);
auto meshGraph = std::make_shared<GuiLabelledGraph>("meshGraph");
meshGraph->create({244, 64}, {}, "Mesh", 120, 32, genericHistogramRef, f);
meshGraph->create({ 244, 64 }, {}, "Mesh", 120, 32, genericHistogramRef, f);
add(meshGraph);
auto genGraph = std::make_shared<GuiLabelledGraph>("genGraph");
genGraph->create({244, 64}, {}, "Gen", 120, 16, genericHistogramRef, f);
genGraph->create({ 244, 64 }, {}, "Gen", 120, 16, genericHistogramRef, f);
add(genGraph);
auto packetGraph = std::make_shared<GuiLabelledGraph>("packetGraph");
packetGraph->create({244, 64}, {}, "Packets", 120, 32, genericHistogramRef, f);
packetGraph->create({ 244, 64 }, {}, "Packets", 120, 32, genericHistogramRef, f);
add(packetGraph);
auto fpsGraph = std::make_shared<GuiLabelledGraph>("fpsGraph");
fpsGraph->create({244, 64}, {}, "FPS", 120, 60, fpsHistogramRef, f);
fpsGraph->create({ 244, 64 }, {}, "FPS", 120, 60, fpsHistogramRef, f);
add(fpsGraph);
auto drawsGraph = std::make_shared<GuiLabelledGraph>("drawsGraph");
drawsGraph->create({244, 64}, {}, "Draw Calls", 120, 0, genericHistogramRef, f);
drawsGraph->create({ 244, 64 }, {}, "Draw Calls", 120, 0, genericHistogramRef, f);
add(drawsGraph);
auto gpuGraph = std::make_shared<GuiLabelledGraph>("gpuGraph");
gpuGraph->create({244, 64}, {}, "GPU", 120, 1, genericHistogramRef, f);
gpuGraph->create({ 244, 64 }, {}, "GPU", 120, 1, genericHistogramRef, f);
add(gpuGraph);
positionElements(bufferSize);
@ -65,23 +65,25 @@ void DebugGui::positionElements(glm::vec2 bufferSize) {
auto bufferWidth = static_cast<int>(bufferSize.x);
auto bufferHeight = static_cast<int>(bufferSize.y);
get<GuiText>("crosshairText")->setPos({bufferWidth / 2 + 22, bufferHeight / 2 - 7});
get<GuiText>("dataText")->setPos({10, 10});
get<GuiText>("crosshairText")->setPos({ bufferWidth / 2 + 22, bufferHeight / 2 - 7 });
get<GuiText>("dataText")->setPos({ 10, 10 });
get<GuiLabelledGraph>("genGraph")->setPos({bufferWidth - 254, bufferHeight - 70 - 160});
get<GuiLabelledGraph>("packetGraph")->setPos({bufferWidth - 254, bufferHeight - 70 - 240});
get<GuiLabelledGraph>("meshGraph")->setPos({bufferWidth - 254, bufferHeight - 70 - 80});
get<GuiLabelledGraph>("interpGraph")->setPos({bufferWidth - 254, bufferHeight - 70});
get<GuiLabelledGraph>("genGraph")->setPos({ bufferWidth - 254, bufferHeight - 70 - 160 });
get<GuiLabelledGraph>("packetGraph")->setPos({ bufferWidth - 254, bufferHeight - 70 - 240 });
get<GuiLabelledGraph>("meshGraph")->setPos({ bufferWidth - 254, bufferHeight - 70 - 80 });
get<GuiLabelledGraph>("interpGraph")->setPos({ bufferWidth - 254, bufferHeight - 70 });
get<GuiLabelledGraph>("fpsGraph")->setPos({bufferWidth - 254, 10});
get<GuiLabelledGraph>("drawsGraph")->setPos({bufferWidth - 254, 90});
get<GuiLabelledGraph>("gpuGraph")->setPos({bufferWidth - 254, 90 + 80});
get<GuiLabelledGraph>("fpsGraph")->setPos({ bufferWidth - 254, 10 });
get<GuiLabelledGraph>("drawsGraph")->setPos({ bufferWidth - 254, 90 });
get<GuiLabelledGraph>("gpuGraph")->setPos({ bufferWidth - 254, 90 + 80 });
}
void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chunks*/, int drawCalls, int ssGen, int ssPack) {
void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chunks*/, int drawCalls, int ssGen,
int ssPack) {
Target target = player->getTarget();
auto& onBiomeDef = game->getBiomes().biomeFromId(world.l()->getActiveDimension()->getBiome(glm::floor(player->getPos())));
auto& onBiomeDef = game->getBiomes().biomeFromId(
world.l()->getActiveDimension()->getBiome(glm::floor(player->getPos())));
auto& targetedBlockDef = game->getDefs().blockFromId(world.l()->getActiveDimension()->getBlock(target.pos));
/* Top-right Graphs */ {
@ -128,10 +130,13 @@ void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chu
str << "C: " << vecToString(posOffsetFromChunk) << " [" << vecToString(chunkPos) << "]" << std::endl;
str << "M: " << vecToString(posOffsetFromBlock) << " [" << vecToString(mapBlockPos) << "]" << std::endl;
str << "R: " << vecToString(posOffsetFromRegion) << " [" << vecToString(regionPos) << "]" << std::endl << std::endl;
str << "R: " << vecToString(posOffsetFromRegion) << " [" << vecToString(regionPos) << "]" << std::endl
<< std::endl;
str << "Texture Slots: " << game.l()->textures.textureSlotsUsed << " / " << game.l()->textures.maxTextureSlots
<< " (" << round(game.l()->textures.textureSlotsUsed / static_cast<float>(game.l()->textures.maxTextureSlots) * 100) << "%)" << std::endl << std::endl;
<< " ("
<< round(game.l()->textures.textureSlotsUsed / static_cast<float>(game.l()->textures.maxTextureSlots) * 100)
<< "%)" << std::endl << std::endl;
str << "Biome: " << onBiomeDef.identifier << " [" << onBiomeDef.index << "]" << std::endl << std::endl;
@ -143,7 +148,7 @@ void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chu
target.face == EVec::RIGHT ? "RIGHT" :
target.face == EVec::FRONT ? "FRONT" :
target.face == EVec::BACK ? "BACK" :
"NONE" ;
"NONE";
str << "Pointing At: " << targetedBlockDef.identifier << " [" << targetedBlockDef.index << "]" << std::endl;
str << "Pointed Position: " << vecToString(target.pos) << std::endl;
@ -157,8 +162,10 @@ void DebugGui::update(std::shared_ptr<LocalPlayer> player, double fps, int /*chu
}
/* Crosshair Text */ {
if (target.type == Target::Type::BLOCK) get<GuiText>("crosshairText")->setText(targetedBlockDef.name + " (" +
targetedBlockDef.identifier + ") [" + std::to_string(targetedBlockDef.index) + "]");
if (target.type == Target::Type::BLOCK)
get<GuiText>("crosshairText")->setText(targetedBlockDef.name + " (" +
targetedBlockDef.identifier + ") [" +
std::to_string(targetedBlockDef.index) + "]");
else get<GuiText>("crosshairText")->setText("");
}
}

View File

@ -9,19 +9,24 @@
#include "util/CovariantPtr.h"
class LocalPlayer;
class LocalSubgame;
class LocalWorld;
class DebugGui : public GuiContainer {
public:
public:
DebugGui(glm::vec2 bufferSize, SubgamePtr game, WorldPtr world);
void bufferResized(glm::vec2 bufferSize);
void changeVisibilityState(int state);
void positionElements(glm::vec2 bufferSize);
void update(std::shared_ptr<LocalPlayer> player, double fps, int chunks, int drawCalls, int ssGen, int ssPack);
private:
private:
int displayMode;
WorldPtr world;

View File

@ -18,7 +18,7 @@ GameGui::GameGui(InventoryRefsPtr refs, glm::vec2 bufferSize, SubgamePtr defs, R
hudRoot->add(hudLuaRoot);
menuRoot->add(menuLuaRoot);
handList->create({3, 3}, {}, {}, refs.l()->getCursorList(), refs.l()->getCursorList(), defs);
handList->create({ 3, 3 }, {}, {}, refs.l()->getCursorList(), refs.l()->getCursorList(), defs);
menuRoot->add(handList);
}
@ -73,10 +73,10 @@ bool GameGui::isVisible() {
return menuRoot->isVisible();
}
void GameGui::drawHud(Renderer &renderer) {
void GameGui::drawHud(Renderer& renderer) {
hudRoot->draw(renderer);
}
void GameGui::drawMenu(Renderer &renderer) {
void GameGui::drawMenu(Renderer& renderer) {
menuRoot->draw(renderer);
}

View File

@ -8,28 +8,36 @@
#include "client/gui/compound/GuiInventoryList.h"
class GameGui {
public:
public:
explicit GameGui(InventoryRefsPtr refs, glm::vec2 bufferSize, SubgamePtr defs, Renderer& renderer);
void winResized(glm::ivec2 win);
void update(double delta);
void setVisible(bool visible);
bool isVisible();
void showMenu(std::shared_ptr<LuaGuiElement> root);
void closeMenu();
const bool isInMenu() const;
void setHud(std::shared_ptr<LuaGuiElement> hud);
std::shared_ptr<LuaGuiElement> getHud();
void drawHud(Renderer& renderer);
void drawMenu(Renderer& renderer);
private:
private:
SubgamePtr defs;
Renderer& renderer;
glm::ivec2 win {};
glm::ivec2 win{};
bool inMenu = false;
std::shared_ptr<LuaGuiElement> hudRootElem = nullptr;

View File

@ -10,12 +10,13 @@
#include "world/inv/LocalInventoryRefs.h"
class GameGuiBuilder : public GuiBuilder {
public:
public:
GameGuiBuilder(InventoryRefsPtr refs, SubgamePtr defs, std::shared_ptr<GuiContainer> root) :
defs(defs), refs(refs), GuiBuilder(defs.l()->textures, defs.l()->models, root) {};
std::shared_ptr<GuiComponent> createComponent(LuaGuiElement& elem, glm::ivec2 bounds) override;
private:
private:
InventoryRefsPtr refs;
SubgamePtr defs;
};

View File

@ -27,7 +27,7 @@ void GuiBuilder::update() {
void GuiBuilder::build(glm::ivec2 winBounds) {
clear(false);
if (winBounds != glm::ivec2 {}) this->winBounds = winBounds;
if (winBounds != glm::ivec2{}) this->winBounds = winBounds;
if (elements) create(*elements, root, this->winBounds);
}
@ -42,7 +42,7 @@ void GuiBuilder::create(LuaGuiElement& element, std::shared_ptr<GuiComponent> pa
auto component = createComponent(element, bounds);
if (!component) throw std::runtime_error("GuiBuilder failed to create component: " + element.key);
parent->add(component);
for (auto &child : element.children) create(*child, component, component->getScale());
for (auto& child : element.children) create(*child, component, component->getScale());
}
}
@ -57,17 +57,13 @@ std::shared_ptr<GuiComponent> GuiBuilder::createComponent(LuaGuiElement& elem, g
c = body;
break;
}
case Util::hash("Rect"):
c = GuiRect::fromSerialized(elem, textures, bounds);
case Util::hash("Rect"):c = GuiRect::fromSerialized(elem, textures, bounds);
break;
case Util::hash("Button"):
c = GuiImageButton::fromSerialized(elem, textures, bounds);
case Util::hash("Button"):c = GuiImageButton::fromSerialized(elem, textures, bounds);
break;
case Util::hash("Text"):
c = GuiText::fromSerialized(elem, textures, bounds);
case Util::hash("Text"):c = GuiText::fromSerialized(elem, textures, bounds);
break;
case Util::hash("Model"):
c = GuiModel::fromSerialized(elem, textures, models, bounds);
case Util::hash("Model"):c = GuiModel::fromSerialized(elem, textures, models, bounds);
break;
}

View File

@ -12,19 +12,28 @@
class GuiContainer;
class GuiBuilder {
public:
struct ComponentCallbacks { GuiComponent::callback left {}, right {}, hover {}; };
public:
struct ComponentCallbacks {
GuiComponent::callback left{}, right{}, hover{};
};
GuiBuilder(TextureAtlas& textures, ModelStore& models, std::shared_ptr<GuiContainer> root);
void setGuiRoot(std::shared_ptr<LuaGuiElement> menu);
void update();
void build(glm::ivec2 winBounds = {});
void clear(bool deleteRoot = true);
~GuiBuilder();
protected:
protected:
void create(LuaGuiElement& element, std::shared_ptr<GuiComponent> parent, glm::ivec2 bounds);
virtual std::shared_ptr<GuiComponent> createComponent(LuaGuiElement& elem, glm::ivec2 bounds);
static void clearCallbacks(std::shared_ptr<GuiComponent> component);
void elementUpdated();
@ -39,5 +48,5 @@ protected:
bool dirty = false;
glm::ivec2 winBounds {};
glm::ivec2 winBounds{};
};

View File

@ -30,11 +30,11 @@ void GuiComponent::setPos(glm::ivec2 pos) {
if (parent != nullptr) {
glm::vec3 parentPos = parent->entity.getPos();
pos += glm::vec2 {parentPos.x, parentPos.y};
pos += glm::vec2 {parent->getPadding().w, parent->getPadding().x};
pos += glm::vec2{ parentPos.x, parentPos.y };
pos += glm::vec2{ parent->getPadding().w, parent->getPadding().x };
}
entity.setPos({pos.x, pos.y, 0});
entity.setPos({ pos.x, pos.y, 0 });
for (const auto& child : children) {
child->updatePos();
@ -47,7 +47,7 @@ glm::vec2 GuiComponent::getScale() {
void GuiComponent::setScale(glm::vec2 scale) {
this->scale = scale;
entity.setScale({scale.x, scale.y, scale.x});
entity.setScale({ scale.x, scale.y, scale.x });
}
glm::vec4 GuiComponent::getPadding() {
@ -74,7 +74,7 @@ void GuiComponent::setCallback(GuiComponent::CallbackType type, const callback&
callbacks[static_cast<unsigned int>(type)] = cb;
}
void GuiComponent::handleMouseInput(Window &window) {
void GuiComponent::handleMouseInput(Window& window) {
auto mousePos = window.input.mousePos();
window.setCursorHand(mouseActivity(mousePos));
@ -143,8 +143,8 @@ void GuiComponent::draw(Renderer& renderer) {
entity.draw(renderer);
for (const auto& child : children) {
renderer.setClipBounds(overflows ? glm::vec4 {} : glm::vec4 {entity.getPos().x, entity.getPos().y,
entity.getPos().x + scale.x, entity.getPos().y + scale.y});
renderer.setClipBounds(overflows ? glm::vec4{} : glm::vec4{ entity.getPos().x, entity.getPos().y,
entity.getPos().x + scale.x, entity.getPos().y + scale.y });
child->draw(renderer);
}
}
@ -168,10 +168,10 @@ void GuiComponent::updatePos() {
glm::vec2 realPos(pos);
if (parent != nullptr) {
glm::vec3 parentPos = parent->entity.getPos();
realPos += glm::vec2 {parentPos.x, parentPos.y};
realPos += glm::vec2 {parent->getPadding().w, parent->getPadding().x};
realPos += glm::vec2{ parentPos.x, parentPos.y };
realPos += glm::vec2{ parent->getPadding().w, parent->getPadding().x };
}
entity.setPos({realPos.x, realPos.y, 0});
entity.setPos({ realPos.x, realPos.y, 0 });
for (const auto& child : children) {
child->updatePos();
}

View File

@ -14,11 +14,14 @@
class Window;
class GuiComponent : public Drawable {
public:
enum class CallbackType { PRIMARY, SECONDARY, HOVER };
public:
enum class CallbackType {
PRIMARY, SECONDARY, HOVER
};
typedef std::function<void(bool, glm::ivec2)> callback;
GuiComponent() = default;
explicit GuiComponent(const std::string& key);
virtual void update(double delta) override;
@ -26,19 +29,28 @@ public:
const std::string& getKey();
virtual glm::ivec2 getPos();
virtual void setPos(glm::ivec2 pos);
virtual glm::vec2 getScale();
virtual void setScale(glm::vec2 scale);
virtual glm::vec4 getPadding();
virtual void setPadding(glm::vec4 padding);
void setOverflows(bool overflows);
void setVisible(bool visible) override;
virtual void setCallback(CallbackType type, const callback& cb);
void handleMouseInput(Window& window);
template<class T> std::shared_ptr<T> get(const std::string &key) {
for (auto &it : children) {
template<class T>
std::shared_ptr<T> get(const std::string& key) {
for (auto& it : children) {
if (it.get()->key == key) {
return std::static_pointer_cast<T>(it);
}
@ -47,26 +59,30 @@ public:
};
std::shared_ptr<GuiComponent> insert(unsigned int index, std::shared_ptr<GuiComponent> component);
std::shared_ptr<GuiComponent> add(std::shared_ptr<GuiComponent> component);
std::list<std::shared_ptr<GuiComponent>> getChildren();
void remove(const std::string& key);
void empty();
void draw(Renderer& renderer) override;
protected:
protected:
bool mouseActivity(glm::ivec2 pos);
bool clickEvent(bool left, bool state, glm::ivec2 pos);
std::string key = "";
GuiComponent* parent = nullptr;
std::list<std::shared_ptr<GuiComponent>> children;
glm::ivec2 pos {};
glm::vec2 scale {};
glm::vec4 padding {};
glm::ivec2 hitbox {};
glm::ivec2 pos{};
glm::vec2 scale{};
glm::vec4 padding{};
glm::ivec2 hitbox{};
bool visible = true;
bool hovered = false;
@ -75,7 +91,7 @@ protected:
DrawableEntity entity;
std::array<callback, 3> callbacks;
private:
private:
void updatePos();
};

View File

@ -25,7 +25,7 @@ namespace SerialGui {
namespace {
static std::vector<std::string> split(const std::string& value, unsigned int targetCount = 0) {
std::vector<std::string> vec {};
std::vector<std::string> vec{};
if (value == "") throw std::runtime_error("expected one or more values to split");
@ -73,18 +73,23 @@ namespace SerialGui {
}
}
template <typename T> static T calcNumbers(const T in, glm::ivec2 multiple = {}) {};
template<typename T>
static T calcNumbers(const T in, glm::ivec2 multiple = {}) {};
template <typename T> static T get(const LuaGuiElement& elem, const std::string& req, glm::ivec2 multiple = {}) {
template<typename T>
static T get(const LuaGuiElement& elem, const std::string& req, glm::ivec2 multiple = {}) {
if (!elem.has<T>(req)) return T{};
return calcNumbers<T>(elem.get<T>(req), multiple);
}
template <> glm::vec2 calcNumbers<glm::vec2>(const glm::vec2 in, glm::ivec2 multiple) {
return {convertNum(in.x, multiple.x), convertNum(in.y, multiple.y)};
template<>
glm::vec2 calcNumbers<glm::vec2>(const glm::vec2 in, glm::ivec2 multiple) {
return { convertNum(in.x, multiple.x), convertNum(in.y, multiple.y) };
}
template <> glm::vec4 calcNumbers<glm::vec4>(const glm::vec4 in, glm::ivec2 multiple) {
return {convertNum(in.x, multiple.x), convertNum(in.y, multiple.y), convertNum(in.z, multiple.x), convertNum(in.w, multiple.y)};
template<>
glm::vec4 calcNumbers<glm::vec4>(const glm::vec4 in, glm::ivec2 multiple) {
return { convertNum(in.x, multiple.x), convertNum(in.y, multiple.y), convertNum(in.z, multiple.x),
convertNum(in.w, multiple.y) };
}
};

View File

@ -4,9 +4,9 @@
#include "GuiContainer.h"
GuiContainer::GuiContainer(const std::string &key) : GuiComponent(key) {}
GuiContainer::GuiContainer(const std::string& key) : GuiComponent(key) {}
void GuiContainer::draw(Renderer &renderer) {
void GuiContainer::draw(Renderer& renderer) {
for (const auto& child : children) {
child->draw(renderer);
}

View File

@ -7,8 +7,9 @@
#include "client/gui/GuiComponent.h"
class GuiContainer : public GuiComponent {
public:
public:
GuiContainer() = default;
explicit GuiContainer(const std::string& key);
void draw(Renderer& renderer) override;

View File

@ -8,15 +8,15 @@
#include "client/graph/Model.h"
#include "game/atlas/asset/AtlasRef.h"
GuiGraph::GuiGraph(const std::string &key) : GuiComponent(key) {}
GuiGraph::GuiGraph(const std::string& key) : GuiComponent(key) {}
void GuiGraph::create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr <AtlasRef> texture,
void GuiGraph::create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture,
unsigned int length, float maxValue, bool editInPlace) {
this->scale = scale;
this->padding = padding;
setScale({scale.x + padding.w + padding.y, scale.y + padding.x + padding.z});
setScale({ scale.x + padding.w + padding.y, scale.y + padding.x + padding.z });
this->length = length;
this->maxVal = maxValue;
@ -59,8 +59,8 @@ void GuiGraph::setMax(float max) {
}
void GuiGraph::buildHistogramMesh() {
std::vector<EntityVertex> vertices {};
std::vector<unsigned int> indices {};
std::vector<EntityVertex> vertices{};
std::vector<unsigned int> indices{};
auto uv = texture->uv;
uv.z -= uv.x;
@ -70,29 +70,33 @@ void GuiGraph::buildHistogramMesh() {
float xOffset = 0;
for (float num : history) {
float distFromPointer = (xOffset <= insertionPoint) ? insertionPoint - xOffset : insertionPoint + length - xOffset;
float age = std::round((90 - (distFromPointer / length)*90)) / 100.0f;
float distFromPointer = (xOffset <= insertionPoint) ? insertionPoint - xOffset : insertionPoint + length -
xOffset;
float age = std::round((90 - (distFromPointer / length) * 90)) / 100.0f;
float h = num / maxVal;
float sec = (float)std::round(9 - fmin(h, 1)*9) * 0.1f;
float sec = (float) std::round(9 - fmin(h, 1) * 9) * 0.1f;
auto columnVerts = std::vector<EntityVertex> {
{{xOffset, -h, 0}, {uv.x + age * uv.z, uv.y + sec * uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{xOffset + 1,-h, 0}, {uv.x + (age+0.01f) * uv.z, uv.y + sec * uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{xOffset + 1, 0, 0}, {uv.x + (age+0.01f) * uv.z, uv.y + (sec+0.10f) * uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{xOffset, 0, 0}, {uv.x + age * uv.z, uv.y + (sec+0.10f) * uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
auto columnVerts = std::vector<EntityVertex>{
{{ xOffset, -h, 0 }, { uv.x + age * uv.z, uv.y + sec * uv.w, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}},
{{ xOffset + 1, -h, 0 }, { uv.x + (age + 0.01f) * uv.z, uv.y + sec * uv.w, 0, 1 }, { 1, 1, 1 }, true, {},
{}, {}},
{{ xOffset + 1, 0, 0 }, { uv.x + (age + 0.01f) * uv.z, uv.y + (sec + 0.10f) * uv.w, 0, 1 }, { 1, 1, 1 },
true, {}, {}, {}},
{{ xOffset, 0, 0 }, { uv.x + age * uv.z, uv.y + (sec + 0.10f) * uv.w, 0, 1 }, { 1, 1, 1 }, true, {}, {},
{}},
};
vertices.insert(vertices.end(), columnVerts.begin(), columnVerts.end());
indices.push_back( indOffset);
indices.push_back(indOffset);
indices.push_back(3 + indOffset);
indices.push_back(1 + indOffset);
indices.push_back(3 + indOffset);
indices.push_back(2 + indOffset);
indices.push_back(1 + indOffset);
xOffset ++;
xOffset++;
indOffset += 4;
}

View File

@ -9,15 +9,20 @@
class AtlasRef;
class GuiGraph : public GuiComponent {
public:
public:
GuiGraph() = default;
GuiGraph(const std::string& key);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, unsigned int length, float maxValue, bool editInPlace);
void
create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, unsigned int length, float maxValue,
bool editInPlace);
void setMax(float max);
void pushValue(float value);
private:
private:
void buildHistogramMesh();
bool editInPlace = false;

View File

@ -11,7 +11,7 @@
#include "game/def/BlockDef.h"
#include "game/def/CraftItemDef.h"
GuiInventoryItem::GuiInventoryItem(const std::string &key) : GuiContainer(key) {}
GuiInventoryItem::GuiInventoryItem(const std::string& key) : GuiContainer(key) {}
void GuiInventoryItem::create(glm::vec2 scale, unsigned short count, ItemDef& def, Font f) {
@ -19,7 +19,7 @@ void GuiInventoryItem::create(glm::vec2 scale, unsigned short count, ItemDef& de
auto texture = static_cast<CraftItemDef&>(def).textureRefs[0];
auto shadow = std::make_shared<GuiRect>("shadow");
shadow->create(scale * 16.f, {}, texture, {0, 0, 0, 0.2});
shadow->create(scale * 16.f, {}, texture, { 0, 0, 0, 0.2 });
add(shadow);
shadow->setPos(scale);
@ -32,7 +32,7 @@ void GuiInventoryItem::create(glm::vec2 scale, unsigned short count, ItemDef& de
auto item = std::make_shared<GuiModel>("mesh");
item->create(scale * 10.5f, model);
item->setPos(glm::vec2{8, 8} * scale);
item->setPos(glm::vec2{ 8, 8 } * scale);
item->setRotationX(180.f - 30.f);
item->setRotationY(45.f);
@ -43,9 +43,9 @@ void GuiInventoryItem::create(glm::vec2 scale, unsigned short count, ItemDef& de
if (count > 1) {
auto text = std::make_shared<GuiText>("count");
text->create(scale, {}, {}, {1, 1, 1, 1}, f);
text->create(scale, {}, {}, { 1, 1, 1, 1 }, f);
text->setText(std::to_string(count));
add(text);
text->setPos({(19 - text->getWidth()) * scale.x, 9 * scale.y});
text->setPos({ (19 - text->getWidth()) * scale.x, 9 * scale.y });
}
}

View File

@ -7,11 +7,13 @@
#include "GuiContainer.h"
class ItemDef;
class Font;
class GuiInventoryItem : public GuiContainer {
public:
public:
GuiInventoryItem() = default;
GuiInventoryItem(const std::string& key);
void create(glm::vec2 scale, unsigned short itemCount, ItemDef& def, Font font);

View File

@ -11,20 +11,21 @@
#include "game/atlas/asset/ModelStore.h"
#include "game/atlas/TextureAtlas.h"
GuiModel::GuiModel(const std::string &key) : GuiComponent(key) {}
GuiModel::GuiModel(const std::string& key) : GuiComponent(key) {}
std::shared_ptr<GuiModel> GuiModel::fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, ModelStore& models, glm::ivec2 bounds) {
std::shared_ptr<GuiModel>
GuiModel::fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, ModelStore& models, glm::ivec2 bounds) {
glm::vec2 pos = SerialGui::get<glm::vec2>(elem, "position", bounds);
glm::vec2 scale = SerialGui::get<glm::vec2>(elem, "scale");
glm::vec2 anim_range = SerialGui::get<glm::vec2>(elem, "anim_range");
if (scale == glm::vec2{0, 0}) scale = {1, 1};
if (scale == glm::vec2{ 0, 0 }) scale = { 1, 1 };
std::string type = elem.get_or<std::string>("type", "model");
std::string source = elem.get_or<std::string>("source", "");
std::string texture = elem.get_or<std::string>("texture", "");
auto m = std::make_shared<Model>();
if (type == "model") m->fromSerialized(models.models[source], {textures[texture]});
if (type == "model") m->fromSerialized(models.models[source], { textures[texture] });
auto model = std::make_shared<GuiModel>(elem.key);
model->create(scale, m);
@ -37,7 +38,7 @@ std::shared_ptr<GuiModel> GuiModel::fromSerialized(const LuaGuiElement& elem, Te
void GuiModel::create(glm::vec2 scale, std::shared_ptr<Model> model) {
entity.setModel(model);
setScale({scale.x + padding.w + padding.y, scale.y + padding.x + padding.z});
setScale({ scale.x + padding.w + padding.y, scale.y + padding.x + padding.z });
setRotationX(180);
setRotationY(215);
@ -63,7 +64,7 @@ void GuiModel::setRotationZ(float z) {
entity.setRotateZ(z);
}
void GuiModel::draw(Renderer &renderer) {
void GuiModel::draw(Renderer& renderer) {
renderer.toggleDepthTest(true);
renderer.clearDepthBuffer();
GuiComponent::draw(renderer);

View File

@ -9,27 +9,36 @@
#include "GuiContainer.h"
class LocalSubgame;
class ModelStore;
class TextureAtlas;
class LuaGuiElement;
class GuiModel : public GuiComponent {
public:
public:
GuiModel() = default;
GuiModel(const std::string& key);
static std::shared_ptr<GuiModel> fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, ModelStore& models, glm::ivec2 bounds);
static std::shared_ptr<GuiModel>
fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, ModelStore& models, glm::ivec2 bounds);
void create(glm::vec2 scale, std::shared_ptr<Model> model);
void update(double delta) override;
void animate(glm::vec2 range);
void setRotationX(float x);
void setRotationY(float x);
void setRotationZ(float x);
void draw(Renderer& renderer) override;
protected:
protected:
float depth = 300;
};

View File

@ -10,7 +10,7 @@
#include "game/atlas/TextureAtlas.h"
#include "game/atlas/asset/AtlasRef.h"
GuiRect::GuiRect(const std::string &key) : GuiComponent(key) {}
GuiRect::GuiRect(const std::string& key) : GuiComponent(key) {}
std::shared_ptr<GuiRect> GuiRect::fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds) {
glm::vec2 pos = SerialGui::get<glm::vec2>(elem, "position", bounds);
@ -19,7 +19,7 @@ std::shared_ptr<GuiRect> GuiRect::fromSerialized(const LuaGuiElement& elem, Text
glm::vec4 padding = SerialGui::get<glm::vec4>(elem, "padding", bounds);
pos -= offset * size;
size -= glm::vec2 {padding.y + padding.w, padding.x + padding.z};
size -= glm::vec2{ padding.y + padding.w, padding.x + padding.z };
std::string background = elem.get_or<std::string>("background", "");
bool hideOverflow = elem.get_or<std::string>("overflow", "visible") == "hidden";
@ -27,7 +27,7 @@ std::shared_ptr<GuiRect> GuiRect::fromSerialized(const LuaGuiElement& elem, Text
auto rect = std::make_shared<GuiRect>(elem.key);
if (background[0] == '#') rect->create(size, padding, Util::hexToColorVec(background));
else if (background.size() > 0) rect->create(size, padding, textures[background]);
else rect->create(size, padding, glm::vec4 {});
else rect->create(size, padding, glm::vec4{});
rect->setOverflows(!hideOverflow);
rect->setPos(pos);
return rect;
@ -41,16 +41,16 @@ void GuiRect::create(glm::vec2 scale, glm::vec4 padding, glm::vec4 color) {
this->padding = padding;
auto mesh = std::make_unique<EntityMesh>();
mesh->create({{{0, 0, 0}, color, {1, 1, 1}, false, {}, {}, {}},
{{0, 1, 0}, color, {1, 1, 1}, false, {}, {}, {}},
{{1, 1, 0}, color, {1, 1, 1}, false, {}, {}, {}},
{{1, 0, 0}, color, {1, 1, 1}, false, {}, {}, {}}
}, {0, 1, 2, 2, 3, 0});
mesh->create({{{ 0, 0, 0 }, color, { 1, 1, 1 }, false, {}, {}, {}},
{{ 0, 1, 0 }, color, { 1, 1, 1 }, false, {}, {}, {}},
{{ 1, 1, 0 }, color, { 1, 1, 1 }, false, {}, {}, {}},
{{ 1, 0, 0 }, color, { 1, 1, 1 }, false, {}, {}, {}}
}, { 0, 1, 2, 2, 3, 0 });
auto model = std::make_shared<Model>();
model->fromMesh(std::move(mesh));
entity.setModel(model);
setScale({scale.x + padding.w + padding.y, scale.y + padding.x + padding.z});
setScale({ scale.x + padding.w + padding.y, scale.y + padding.x + padding.z });
}
// Multiple Color Constructor
@ -62,16 +62,16 @@ void GuiRect::create(glm::vec2 scale, glm::vec4 padding, glm::vec4 tl, glm::vec4
auto mesh = std::make_unique<EntityMesh>();
mesh->create({
{{0, 0, 0}, tl, {1, 1, 1}, false, {}, {}, {}},
{{0, 1, 0}, bl, {1, 1, 1}, false, {}, {}, {}},
{{1, 1, 0}, br, {1, 1, 1}, false, {}, {}, {}},
{{1, 0, 0}, tr, {1, 1, 1}, false, {}, {}, {}}
}, {0, 1, 2, 2, 3, 0});
{{ 0, 0, 0 }, tl, { 1, 1, 1 }, false, {}, {}, {}},
{{ 0, 1, 0 }, bl, { 1, 1, 1 }, false, {}, {}, {}},
{{ 1, 1, 0 }, br, { 1, 1, 1 }, false, {}, {}, {}},
{{ 1, 0, 0 }, tr, { 1, 1, 1 }, false, {}, {}, {}}
}, { 0, 1, 2, 2, 3, 0 });
auto model = std::make_shared<Model>();
model->fromMesh(std::move(mesh));
entity.setModel(model);
setScale({scale.x + padding.w + padding.y, scale.y + padding.x + padding.z});
setScale({ scale.x + padding.w + padding.y, scale.y + padding.x + padding.z });
}
// Texture Constructor
@ -81,20 +81,20 @@ void GuiRect::create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRe
this->scale = scale;
this->padding = padding;
this->texture = texture;
this->hitbox = scale + glm::vec2{padding.y + padding.w, padding.x + padding.z};
this->hitbox = scale + glm::vec2{ padding.y + padding.w, padding.x + padding.z };
auto mesh = std::make_unique<EntityMesh>();
mesh->create({
{{0, 0, 0}, {this->texture->uv.x, this->texture->uv.y, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{0, 1, 0}, {this->texture->uv.x, this->texture->uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{1, 1, 0}, {this->texture->uv.z, this->texture->uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{1, 0, 0}, {this->texture->uv.z, this->texture->uv.y, 0, 1}, {1, 1, 1}, true, {}, {}, {}}
}, {0, 1, 2, 2, 3, 0});
{{ 0, 0, 0 }, { this->texture->uv.x, this->texture->uv.y, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}},
{{ 0, 1, 0 }, { this->texture->uv.x, this->texture->uv.w, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}},
{{ 1, 1, 0 }, { this->texture->uv.z, this->texture->uv.w, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}},
{{ 1, 0, 0 }, { this->texture->uv.z, this->texture->uv.y, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}}
}, { 0, 1, 2, 2, 3, 0 });
auto model = std::make_shared<Model>();
model->fromMesh(std::move(mesh));
entity.setModel(model);
setScale({scale.x + padding.w + padding.y, scale.y + padding.x + padding.z});
setScale({ scale.x + padding.w + padding.y, scale.y + padding.x + padding.z });
}
// Texture Constructor
@ -107,14 +107,14 @@ void GuiRect::create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRe
auto mesh = std::make_unique<EntityMesh>();
mesh->create({
{{0, 0, 0}, {this->texture->uv.x, this->texture->uv.y, 0, tint.w}, glm::vec3{tint}, true, {}, {}, {}},
{{0, 1, 0}, {this->texture->uv.x, this->texture->uv.w, 0, tint.w}, glm::vec3{tint}, true, {}, {}, {}},
{{1, 1, 0}, {this->texture->uv.z, this->texture->uv.w, 0, tint.w}, glm::vec3{tint}, true, {}, {}, {}},
{{1, 0, 0}, {this->texture->uv.z, this->texture->uv.y, 0, tint.w}, glm::vec3{tint}, true, {}, {}, {}}
}, {0, 1, 2, 2, 3, 0});
{{ 0, 0, 0 }, { this->texture->uv.x, this->texture->uv.y, 0, tint.w }, glm::vec3{ tint }, true, {}, {}, {}},
{{ 0, 1, 0 }, { this->texture->uv.x, this->texture->uv.w, 0, tint.w }, glm::vec3{ tint }, true, {}, {}, {}},
{{ 1, 1, 0 }, { this->texture->uv.z, this->texture->uv.w, 0, tint.w }, glm::vec3{ tint }, true, {}, {}, {}},
{{ 1, 0, 0 }, { this->texture->uv.z, this->texture->uv.y, 0, tint.w }, glm::vec3{ tint }, true, {}, {}, {}}
}, { 0, 1, 2, 2, 3, 0 });
auto model = std::make_shared<Model>();
model->fromMesh(std::move(mesh));
entity.setModel(model);
setScale({scale.x + padding.w + padding.y, scale.y + padding.x + padding.z});
setScale({ scale.x + padding.w + padding.y, scale.y + padding.x + padding.z });
}

View File

@ -7,23 +7,31 @@
#include "client/gui/GuiComponent.h"
class AtlasRef;
class LocalSubgame;
class TextureAtlas;
class LuaGuiElement;
class GuiRect : public GuiComponent {
public:
public:
GuiRect() = default;
GuiRect(const std::string& key);
static std::shared_ptr<GuiRect> fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
static std::shared_ptr<GuiRect>
fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
void create(glm::vec2 scale, glm::vec4 padding, glm::vec4 color);
void create(glm::vec2 scale, glm::vec4 padding, glm::vec4 tl, glm::vec4 tr, glm::vec4 bl, glm::vec4 br);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, glm::vec4 tint);
protected:
protected:
std::shared_ptr<AtlasRef> texture = nullptr;
};

View File

@ -12,7 +12,7 @@
#include "game/atlas/asset/AtlasRef.h"
#include "world/dim/ent/AnimationSegment.h"
GuiText::GuiText(const std::string &key) : GuiComponent(key) {}
GuiText::GuiText(const std::string& key) : GuiComponent(key) {}
void GuiText::create(glm::vec2 scale, glm::vec4 padding, glm::vec4 bgcolor, glm::vec4 color, Font font) {
// Text Constructor
@ -35,7 +35,7 @@ std::shared_ptr<GuiText> GuiText::fromSerialized(const LuaGuiElement& elem, Text
glm::vec2 size = SerialGui::get<glm::vec2>(elem, "size", bounds);
glm::vec4 padding = SerialGui::get<glm::vec4>(elem, "padding", bounds);
glm::vec2 scale = SerialGui::get<glm::vec2>(elem, "scale");
if (scale == glm::vec2{0, 0}) scale = {1, 1};
if (scale == glm::vec2{ 0, 0 }) scale = { 1, 1 };
pos -= offset * size;
@ -44,7 +44,7 @@ std::shared_ptr<GuiText> GuiText::fromSerialized(const LuaGuiElement& elem, Text
std::string content = elem.get_or<std::string>("content", "");
auto text = std::make_shared<GuiText>(elem.key);
text->create(scale * SerialGui::SCALE_MODIFIER, padding, background_color, color, {textures, textures["font"]});
text->create(scale * SerialGui::SCALE_MODIFIER, padding, background_color, color, { textures, textures["font"] });
text->setText(content);
text->setPos(pos);
@ -58,9 +58,9 @@ void GuiText::setText(std::string text) {
maxLineWidth = 0;
std::vector<EntityVertex> textVertices;
textVertices.reserve(text.length()*8 + 200);
textVertices.reserve(text.length() * 8 + 200);
std::vector<unsigned int> textIndices;
textIndices.reserve(text.length()*12 + 240);
textIndices.reserve(text.length() * 12 + 240);
//Draw background & Measure Line Width
int lineWidth = 0;
@ -80,10 +80,14 @@ void GuiText::setText(std::string text) {
if (lineWidth > maxLineWidth) maxLineWidth = lineWidth;
if (bgcolor.w != 0) {
textVertices.emplace_back(glm::vec3 {-1, yOffset - 1, 0}, bgcolor, glm::vec3(1), 0.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {-1, yOffset + h + 1, 0}, bgcolor, glm::vec3(1), 0.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {lineWidth + 1, yOffset + h + 1, 0}, bgcolor, glm::vec3(1), 0.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {lineWidth + 1, yOffset - 1, 0}, bgcolor, glm::vec3(1), 0.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3{ -1, yOffset - 1, 0 }, bgcolor, glm::vec3(1), 0.f, glm::vec3{},
glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ -1, yOffset + h + 1, 0 }, bgcolor, glm::vec3(1), 0.f,
glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ lineWidth + 1, yOffset + h + 1, 0 }, bgcolor, glm::vec3(1),
0.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ lineWidth + 1, yOffset - 1, 0 }, bgcolor, glm::vec3(1), 0.f,
glm::vec3{}, glm::ivec4{}, glm::vec4{});
textIndices.emplace_back(indOffset);
textIndices.emplace_back(indOffset + 1);
@ -133,10 +137,10 @@ void GuiText::setText(std::string text) {
auto charUVs = font.getCharUVs(c);
for (unsigned int j = 0; j <= 1; j++) {
glm::vec3 c = {this->color.x, this->color.y, this->color.z};
glm::vec3 c = { this->color.x, this->color.y, this->color.z };
if (j == 0) {
c *= glm::vec3 {0.4, 0.4, 0.45};
c *= glm::vec3{ 0.4, 0.4, 0.45 };
xOffset += 1;
yOffset += 1;
}
@ -145,10 +149,14 @@ void GuiText::setText(std::string text) {
yOffset -= 1;
}
textVertices.emplace_back(glm::vec3 {xOffset, yOffset, 0}, glm::vec4 {charUVs.x, charUVs.y, 0, color.w}, c, 1.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {xOffset, yOffset + h, 0}, glm::vec4 {charUVs.x, charUVs.w, 0, color.w}, c, 1.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {xOffset + charWidth, yOffset + h, 0}, glm::vec4 {charUVs.z, charUVs.w, 0, color.w}, c, 1.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3 {xOffset + charWidth, yOffset, 0}, glm::vec4 {charUVs.z, charUVs.y, 0, color.w}, c, 1.f, glm::vec3 {}, glm::ivec4 {}, glm::vec4 {});
textVertices.emplace_back(glm::vec3{ xOffset, yOffset, 0 }, glm::vec4{ charUVs.x, charUVs.y, 0, color.w },
c, 1.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ xOffset, yOffset + h, 0 },
glm::vec4{ charUVs.x, charUVs.w, 0, color.w }, c, 1.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ xOffset + charWidth, yOffset + h, 0 },
glm::vec4{ charUVs.z, charUVs.w, 0, color.w }, c, 1.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textVertices.emplace_back(glm::vec3{ xOffset + charWidth, yOffset, 0 },
glm::vec4{ charUVs.z, charUVs.y, 0, color.w }, c, 1.f, glm::vec3{}, glm::ivec4{}, glm::vec4{});
textIndices.emplace_back(indOffset);
textIndices.emplace_back(indOffset + 1);

View File

@ -9,25 +9,30 @@
#include "client/graph/Font.h"
class TextureAtlas;
class LuaGuiElement;
class GuiText : public GuiComponent {
public:
public:
GuiText() = default;
explicit GuiText(const std::string& key);
static std::shared_ptr<GuiText> fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
static std::shared_ptr<GuiText>
fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
void create(glm::vec2 scale, glm::vec4 padding, glm::vec4 bgcolor, glm::vec4 color, Font font);
unsigned int getWidth();
void setText(std::string text);
std::string getText();
private:
private:
Font font;
glm::vec4 bgcolor {};
glm::vec4 color {};
glm::vec4 bgcolor{};
glm::vec4 color{};
std::string text;
unsigned int maxLineWidth = 0;

View File

@ -9,16 +9,17 @@
#include "client/gui/basic/GuiText.h"
#include "game/atlas/asset/AtlasRef.h"
GuiImageButton::GuiImageButton(const std::string &key) : GuiRect(key) {}
GuiImageButton::GuiImageButton(const std::string& key) : GuiRect(key) {}
std::shared_ptr<GuiImageButton> GuiImageButton::fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds) {
std::shared_ptr<GuiImageButton>
GuiImageButton::fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds) {
glm::vec2 pos = SerialGui::get<glm::vec2>(elem, "position", bounds);
glm::vec2 offset = SerialGui::get<glm::vec2>(elem, "position_anchor");
glm::vec2 size = SerialGui::get<glm::vec2>(elem, "size", bounds);
glm::vec4 padding = SerialGui::get<glm::vec4>(elem, "padding", bounds);
pos -= offset * size;
size -= glm::vec2 {padding.y + padding.w, padding.x + padding.z};
size -= glm::vec2{ padding.y + padding.w, padding.x + padding.z };
std::string background = elem.get_or<std::string>("background", "");
std::string background_hover = elem.get_or<std::string>("background_hover", background);
@ -33,8 +34,8 @@ std::shared_ptr<GuiImageButton> GuiImageButton::fromSerialized(const LuaGuiEleme
if (content != "") {
auto text = std::make_shared<GuiText>(elem.key + "__TEXT");
text->create(glm::vec2(SerialGui::SCALE_MODIFIER), padding, {}, {1, 1, 1, 1}, {textures, textures["font"]});
text->setPos({6 * SerialGui::SCALE_MODIFIER, size.y / 2 - 4.5 * SerialGui::SCALE_MODIFIER});
text->create(glm::vec2(SerialGui::SCALE_MODIFIER), padding, {}, { 1, 1, 1, 1 }, { textures, textures["font"] });
text->setPos({ 6 * SerialGui::SCALE_MODIFIER, size.y / 2 - 4.5 * SerialGui::SCALE_MODIFIER });
text->setText(content);
button->add(text);
}
@ -45,14 +46,15 @@ std::shared_ptr<GuiImageButton> GuiImageButton::fromSerialized(const LuaGuiEleme
// Texture Constructor
// Creates a GuiImageButton object with two textures
// defined by the 'texture' & 'hoverTexture' reference.
void GuiImageButton::create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, std::shared_ptr<AtlasRef> hoverTexture) {
void GuiImageButton::create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture,
std::shared_ptr<AtlasRef> hoverTexture) {
this->hoverTexture = hoverTexture;
GuiRect::create(scale, padding, texture);
setCallback(GuiComponent::CallbackType::HOVER, nullptr);
}
void GuiImageButton::setCallback(GuiComponent::CallbackType type, const GuiComponent::callback &cb) {
void GuiImageButton::setCallback(GuiComponent::CallbackType type, const GuiComponent::callback& cb) {
if (type == CallbackType::HOVER) {
GuiComponent::setCallback(type, [&, cb](bool nowHovered, glm::ivec2 pos) {
if (cb) cb(nowHovered, pos);
@ -67,15 +69,15 @@ void GuiImageButton::rebuild(bool hover) {
auto mesh = std::make_unique<EntityMesh>();
mesh->create({
{{0, 0, 0}, {tex->uv.x, tex->uv.y, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{0, 1, 0}, {tex->uv.x, tex->uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{1, 1, 0}, {tex->uv.z, tex->uv.w, 0, 1}, {1, 1, 1}, true, {}, {}, {}},
{{1, 0, 0}, {tex->uv.z, tex->uv.y, 0, 1}, {1, 1, 1}, true, {}, {}, {}}
}, {0, 1, 2, 2, 3, 0});
{{ 0, 0, 0 }, { tex->uv.x, tex->uv.y, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}},
{{ 0, 1, 0 }, { tex->uv.x, tex->uv.w, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}},
{{ 1, 1, 0 }, { tex->uv.z, tex->uv.w, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}},
{{ 1, 0, 0 }, { tex->uv.z, tex->uv.y, 0, 1 }, { 1, 1, 1 }, true, {}, {}, {}}
}, { 0, 1, 2, 2, 3, 0 });
auto model = std::make_shared<Model>();
model->fromMesh(std::move(mesh));
entity.setModel(model);
setScale({scale.x + padding.w + padding.y, scale.y + padding.x + padding.z});
setScale({ scale.x + padding.w + padding.y, scale.y + padding.x + padding.z });
}

View File

@ -7,16 +7,21 @@
#include "../basic/GuiRect.h"
class GuiImageButton : public GuiRect {
public:
public:
GuiImageButton() = default;
GuiImageButton(const std::string& key);
static std::shared_ptr<GuiImageButton> fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
static std::shared_ptr<GuiImageButton>
fromSerialized(const LuaGuiElement& elem, TextureAtlas& textures, glm::ivec2 bounds);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture, std::shared_ptr<AtlasRef> hoverTexture);
void create(glm::vec2 scale, glm::vec4 padding, std::shared_ptr<AtlasRef> texture,
std::shared_ptr<AtlasRef> hoverTexture);
void setCallback(CallbackType type, const callback& cb) override;
private:
private:
void rebuild(bool hover);
std::shared_ptr<AtlasRef> hoverTexture = nullptr;
};

View File

@ -12,7 +12,7 @@
#include "game/atlas/LocalDefinitionAtlas.h"
#include "client/gui/basic/GuiInventoryItem.h"
GuiInventoryList::GuiInventoryList(const std::string &key) : GuiContainer(key) {}
GuiInventoryList::GuiInventoryList(const std::string& key) : GuiContainer(key) {}
std::shared_ptr<GuiInventoryList> GuiInventoryList::fromSerialized(const LuaGuiElement& elem,
SubgamePtr game, glm::ivec2 bounds, InventoryRefsPtr refs) {
@ -52,9 +52,9 @@ void GuiInventoryList::create(glm::vec2 scale, glm::vec4 padding, glm::ivec2 inn
this->scale = scale;
this->padding = padding;
this->innerPadding = innerPadding;
this->hitbox = (list->getWidth() == 0 ? glm::ivec2 {} : glm::ivec2 {
padding.x + list->getWidth() * (innerPadding.x*scale.x),
padding.y + (list->getLength() / list->getWidth()) * (innerPadding.y*scale.y) });
this->hitbox = (list->getWidth() == 0 ? glm::ivec2{} : glm::ivec2{
padding.x + list->getWidth() * (innerPadding.x * scale.x),
padding.y + (list->getLength() / list->getWidth()) * (innerPadding.y * scale.y) });
drawContents();
myCallback = std::make_shared<std::function<void()>>(std::bind(&GuiInventoryList::drawContents, this));
@ -64,7 +64,7 @@ void GuiInventoryList::create(glm::vec2 scale, glm::vec4 padding, glm::ivec2 inn
setCallback(CallbackType::SECONDARY, nullptr);
setCallback(CallbackType::HOVER, nullptr);
hoverRect->create({}, {}, {1, 1, 1, 0.1});
hoverRect->create({}, {}, { 1, 1, 1, 0.1 });
}
void GuiInventoryList::setCallback(CallbackType type, const callback& cb) {
@ -80,7 +80,7 @@ void GuiInventoryList::hoverEvent(bool hovered, glm::ivec2 pos) {
pos += glm::ivec2(glm::vec2(this->padding.x, this->padding.y) * this->scale);
if (hovered) {
if (!this->hovered) hoverRect->setScale({16*scale.x, 16*scale.y});
if (!this->hovered) hoverRect->setScale({ 16 * scale.x, 16 * scale.y });
glm::ivec2 slot = pos / (glm::ivec2(this->scale) * this->innerPadding);
slot.x = std::min(slot.x, static_cast<int>(list->getWidth() - 1));
@ -112,9 +112,9 @@ void GuiInventoryList::drawContents() {
if (list->getWidth() == 0) return;
unsigned short length = this->length == 0 ? list->getLength() : this->length;
this->hitbox = glm::ivec2 {
padding.x + list->getWidth() * (innerPadding.x*scale.x),
padding.y + (list->getLength() / list->getWidth()) * (innerPadding.y*scale.y)
this->hitbox = glm::ivec2{
padding.x + list->getWidth() * (innerPadding.x * scale.x),
padding.y + (list->getLength() / list->getWidth()) * (innerPadding.y * scale.y)
};
empty();
@ -137,7 +137,8 @@ void GuiInventoryList::drawContents() {
auto item = std::make_shared<GuiInventoryItem>("item_" + std::to_string(i) + "_" + std::to_string(j));
item->create(scale, stack.count, defs->getDefs().fromId(stack.id), f);
add(item);
item->setPos({padding.x + j * (16*scale.x+innerPadding.x/scale.x), padding.y + i * (16*scale.y+innerPadding.y/scale.y)});
item->setPos({ padding.x + j * (16 * scale.x + innerPadding.x / scale.x),
padding.y + i * (16 * scale.y + innerPadding.y / scale.y) });
}
}

View File

@ -9,14 +9,19 @@
#include "util/CovariantPtr.h"
class LocalSubgame;
class LuaGuiElement;
class LocalInventoryRefs;
class LocalInventoryList;
class GuiInventoryList : public GuiContainer {
public:
public:
GuiInventoryList() = default;
GuiInventoryList(const std::string& key);
~GuiInventoryList() override;
static std::shared_ptr<GuiInventoryList> fromSerialized(const LuaGuiElement& elem,
@ -29,9 +34,12 @@ public:
void setCallback(CallbackType type, const callback& cb) override;
void hoverEvent(bool hovered, glm::ivec2 pos);
void interactEvent(glm::ivec2 pos, bool primary);
void drawContents();
private:
private:
std::shared_ptr<GuiRect> hoverRect = std::make_shared<GuiRect>("hover_rect");
std::shared_ptr<std::function<void()>> myCallback = nullptr;

View File

@ -4,9 +4,9 @@
#include "GuiLabelledGraph.h"
GuiLabelledGraph::GuiLabelledGraph(const std::string &key) : GuiContainer(key) {}
GuiLabelledGraph::GuiLabelledGraph(const std::string& key) : GuiContainer(key) {}
void GuiLabelledGraph::create(glm::vec2 scale, glm::vec4 padding, const std::string &title,
void GuiLabelledGraph::create(glm::vec2 scale, glm::vec4 padding, const std::string& title,
unsigned int graphLength, unsigned int graphScale,
std::shared_ptr<AtlasRef> graphTextureRef, Font font) {
@ -22,21 +22,23 @@ void GuiLabelledGraph::create(glm::vec2 scale, glm::vec4 padding, const std::str
this->graphTextureRef = std::move(graphTextureRef);
auto background = std::make_shared<GuiRect>("background");
background->create(scale, {}, {0.1, 0.1, 0.1, 0.2}, {0.1, 0.1, 0.1, 0.2}, {0.1, 0.1, 0.1, 0.7}, {0.1, 0.1, 0.1, 0.7});
background->create(scale, {}, { 0.1, 0.1, 0.1, 0.2 }, { 0.1, 0.1, 0.1, 0.2 }, { 0.1, 0.1, 0.1, 0.7 },
{ 0.1, 0.1, 0.1, 0.7 });
add(background);
background->setPos({0, 0});
background->setPos({ 0, 0 });
auto graph = std::make_shared<GuiGraph>("graph");
graph->create({scale.x / (graphLength + GRAPH_PAD_X), scale.y * 0.4}, {}, this->graphTextureRef, graphLength, graphScale, true);
graph->create({ scale.x / (graphLength + GRAPH_PAD_X), scale.y * 0.4 }, {}, this->graphTextureRef, graphLength,
graphScale, true);
add(graph);
graph->setPos({GRAPH_PAD_X, GRAPH_PAD_Y});
graph->setPos({ GRAPH_PAD_X, GRAPH_PAD_Y });
auto label = std::make_shared<GuiText>("label");
label->create({2, 2}, {}, {}, {1, 1, 1, 1}, this->font);
label->create({ 2, 2 }, {}, {}, { 1, 1, 1, 1 }, this->font);
add(label);
label->setPos({TEXT_PAD_X, TEXT_PAD_Y});
label->setPos({ TEXT_PAD_X, TEXT_PAD_Y });
for (float &i : history) i = 0;
for (float& i : history) i = 0;
}
void GuiLabelledGraph::pushValue(float value) {

View File

@ -12,8 +12,9 @@
#include "world/dim/ent/DrawableEntity.h"
class GuiLabelledGraph : public GuiContainer {
public:
public:
GuiLabelledGraph() = default;
GuiLabelledGraph(const std::string& key);
void create(glm::vec2 scale, glm::vec4 padding, const std::string& title,
@ -21,13 +22,14 @@ public:
std::shared_ptr<AtlasRef> graphTextureRef, Font font);
void pushValue(float value);
private:
private:
std::string title;
std::shared_ptr<AtlasRef> graphTextureRef;
Font font;
int ind = 0;
float history[5] {};
float history[5]{};
};

View File

@ -17,7 +17,7 @@
#include "lua/modules/mSetGui.h"
#include "lua/modules/mStartGame.h"
MenuSandbox::MenuSandbox(glm::ivec2 &win, Client& client, std::shared_ptr<GuiContainer> container) :
MenuSandbox::MenuSandbox(glm::ivec2& win, Client& client, std::shared_ptr<GuiContainer> container) :
LuaParser(*client.game),
win(win),
client(client),
@ -30,7 +30,7 @@ void MenuSandbox::reset() {
builder.clear(true);
core = {};
mod = {};
lua = sol::state {};
lua = sol::state{};
lua.open_libraries(sol::lib::base, sol::lib::string, sol::lib::math, sol::lib::table, sol::lib::debug);
loadApi();
@ -47,8 +47,8 @@ void MenuSandbox::loadApi() {
ClientApi::gui_element(lua);
MenuApi::set_gui (builder, win, lua, core);
MenuApi::start_game (client, core);
MenuApi::set_gui(builder, win, lua, core);
MenuApi::start_game(client, core);
bindModules();
@ -93,14 +93,14 @@ sol::protected_function_result MenuSandbox::runFileSandboxed(const std::string&
throw std::runtime_error("Error opening '" + file + "', file not found.");
}
void MenuSandbox::loadAndRunMod(const std::string &modPath) {
void MenuSandbox::loadAndRunMod(const std::string& modPath) {
if (!cf_file_exists(modPath.data())) throw std::runtime_error("Directory not found.");
LuaMod mod;
std::string root = modPath + "/script";
std::list<std::string> dirsToScan {root};
std::list<std::string> luaFiles {};
std::list<std::string> dirsToScan{ root };
std::list<std::string> luaFiles{};
cf_dir_t dir;
while (!dirsToScan.empty()) {
@ -143,7 +143,7 @@ void MenuSandbox::loadAndRunMod(const std::string &modPath) {
std::ifstream t(file);
std::string fileStr((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
LuaMod::File f {modPath, fileStr};
LuaMod::File f{ modPath, fileStr };
mod.files.push_back(f);
}
@ -164,15 +164,15 @@ void MenuSandbox::showError(const std::string& what, const std::string& subgame)
container->add(errWrap);
auto errPrefix = std::make_shared<GuiText>("error_text");
errPrefix->create({3, 3}, {}, {0.7, 0, 0.3, 1}, {1, 1, 1, 1}, f);
errPrefix->create({ 3, 3 }, {}, { 0.7, 0, 0.3, 1 }, { 1, 1, 1, 1 }, f);
errPrefix->setText(errPrefixText);
errPrefix->setPos({8, 16});
errPrefix->setPos({ 8, 16 });
errWrap->add(errPrefix);
auto errMsg = std::make_shared<GuiText>("error_text");
errMsg->create({3, 3}, {}, {}, {1, 0.5, 0.6, 1}, f);
errMsg->create({ 3, 3 }, {}, {}, { 1, 0.5, 0.6, 1 }, f);
errMsg->setText(what);
errMsg->setPos({8, 52});
errMsg->setPos({ 8, 52 });
errWrap->add(errMsg);
}
@ -189,7 +189,8 @@ sol::protected_function_result MenuSandbox::errorCallback(sol::protected_functio
std::string fileName = errString.substr(0, lineNumStart);
int lineNum = std::stoi(errString.substr(lineNumStart + 1, lineNumEnd - lineNumStart - 1));
for (const LuaMod::File& file : mod.files) if (file.path == fileName)
for (const LuaMod::File& file : mod.files)
if (file.path == fileName)
throw std::runtime_error(ErrorFormatter::formatError(fileName, lineNum, errString, file.file));
throw std::out_of_range("Error thrown outside of handled files. [2]");

View File

@ -10,32 +10,41 @@
#include "client/gui/GuiBuilder.h"
class Client;
class Subgame;
class AtlasRef;
class SubgameDef;
class GuiContainer;
class MenuSandbox : LuaParser {
public:
public:
MenuSandbox(glm::ivec2& window, Client& client, std::shared_ptr<GuiContainer> container);
void load(const SubgameDef& subgame);
void update(double delta) override;
void windowResized();
using LuaParser::update;
private:
private:
void reset();
void loadApi();
void loadAndRunMod(const std::string& modPath);
void showError(const std::string& what, const std::string& subgame);
sol::protected_function_result runFileSandboxed(const std::string& file);
virtual sol::protected_function_result errorCallback(sol::protected_function_result r) const override;
LuaMod mod {};
std::vector<std::shared_ptr<AtlasRef>> modAssets {};
LuaMod mod{};
std::vector<std::shared_ptr<AtlasRef>> modAssets{};
std::shared_ptr<GuiContainer> container = nullptr;
std::shared_ptr<GuiContainer> luaContainer = nullptr;

View File

@ -11,8 +11,8 @@
class AtlasRef;
class SubgameDef {
public:
public:
std::shared_ptr<AtlasRef> iconRef = nullptr;
SubgameConfig config {};
SubgameConfig config{};
std::string subgamePath = "";
};

View File

@ -25,7 +25,7 @@
* @param addr - The server address to connect to.
*/
ConnectScene::ConnectScene(Client &client, Address addr) : Scene(client),
ConnectScene::ConnectScene(Client& client, Address addr) : Scene(client),
connection(client.connection) {
client.renderer.setClearColor(10, 10, 10);
@ -33,20 +33,20 @@ ConnectScene::ConnectScene(Client &client, Address addr) : Scene(client),
Font f(client.game->textures, client.game->textures["font"]);
auto statusText = std::make_shared<GuiText>("statusText");
statusText->create({2, 2}, {}, {}, {1, 1, 1, 1}, f);
statusText->create({ 2, 2 }, {}, {}, { 1, 1, 1, 1 }, f);
statusText->setText("Connecting...");
statusText->setPos({32, 24});
statusText->setPos({ 32, 24 });
components.add(statusText);
auto loadBar = std::make_shared<GuiRect>("loadBar");
loadBar->create({1, 32}, {}, {0.17, 0.75, 0.93, 1});
loadBar->setPos({0, client.renderer.window.getSize().y - 32});
loadBar->create({ 1, 32 }, {}, { 0.17, 0.75, 0.93, 1 });
loadBar->setPos({ 0, client.renderer.window.getSize().y - 32 });
components.add(loadBar);
connection.attemptConnect(std::move(addr));
client.renderer.window.addResizeCallback("scene", [&](glm::ivec2 win) {
components.get<GuiRect>("loadBar")->setPos({0, win.y - 32});
components.get<GuiRect>("loadBar")->setPos({ 0, win.y - 32 });
});
}
@ -54,19 +54,16 @@ void ConnectScene::update() {
client.game->textures.update();
switch (connectState) {
default:
throw std::runtime_error("Invalid connection state.");
default:throw std::runtime_error("Invalid connection state.");
case State::DONE:
case State::FAILED_CONNECT:
break;
case State::FAILED_CONNECT:break;
case State::CONNECTING:
handleConnecting();
case State::CONNECTING:handleConnecting();
break;
case State::PROPERTIES: {
components.get<GuiRect>("loadBar")->setScale({client.renderer.window.getSize().x * 0.1, 32});
components.get<GuiRect>("loadBar")->setScale({ client.renderer.window.getSize().x * 0.1, 32 });
ENetEvent e;
if (connection.pollEvents(&e) && e.type == ENET_EVENT_TYPE_RECEIVE) {
@ -88,7 +85,7 @@ void ConnectScene::update() {
}
case State::IDENTIFIER_LIST: {
components.get<GuiRect>("loadBar")->setScale({client.renderer.window.getSize().x * 0.2, 32});
components.get<GuiRect>("loadBar")->setScale({ client.renderer.window.getSize().x * 0.2, 32 });
ENetEvent e;
if (connection.pollEvents(&e) && e.type == ENET_EVENT_TYPE_RECEIVE) {
@ -105,7 +102,8 @@ void ConnectScene::update() {
}
else if (p.type == Packet::Type::BIOME_IDENTIFIER_LIST) {
auto statusText = components.get<GuiText>("statusText");
statusText->setText(statusText->getText() + "Received biome index-identifier table.\nDownloading mods...\n");
statusText->setText(
statusText->getText() + "Received biome index-identifier table.\nDownloading mods...\n");
client.game->getBiomes().setIdentifiers(p.d.read<std::vector<std::string>>());
@ -118,7 +116,7 @@ void ConnectScene::update() {
}
case State::MODS: {
components.get<GuiRect>("loadBar")->setScale({client.renderer.window.getSize().x * 0.4, 32});
components.get<GuiRect>("loadBar")->setScale({ client.renderer.window.getSize().x * 0.4, 32 });
ENetEvent e;
if (connection.pollEvents(&e) && e.type == ENET_EVENT_TYPE_RECEIVE) {
PacketView p(e.packet);
@ -133,7 +131,8 @@ void ConnectScene::update() {
else if (p.type == Packet::Type::MOD_ORDER) {
client.game->getParser().getHandler().setModsOrder(p.d.read<std::vector<std::string>>());
statusText->setText(statusText->getText() + "Done downloading mods.\nReceived the mods order.\nDownloading media...\n");
statusText->setText(
statusText->getText() + "Done downloading mods.\nReceived the mods order.\nDownloading media...\n");
connectState = State::MEDIA;
Packet resp(Packet::Type::MEDIA);
@ -144,7 +143,7 @@ void ConnectScene::update() {
}
case State::MEDIA: {
components.get<GuiRect>("loadBar")->setScale({client.renderer.window.getSize().x * 0.6, 32});
components.get<GuiRect>("loadBar")->setScale({ client.renderer.window.getSize().x * 0.6, 32 });
ENetEvent e;
if (connection.pollEvents(&e) && e.type == ENET_EVENT_TYPE_RECEIVE) {
@ -167,14 +166,14 @@ void ConnectScene::update() {
std::string uncompressed = gzip::decompress(data.data(), data.length());
client.game->textures.addImage(
reinterpret_cast<unsigned char *>(const_cast<char *>(uncompressed.data())),
reinterpret_cast<unsigned char*>(const_cast<char*>(uncompressed.data())),
assetName, true, width, height);
}
else if (t == AssetType::MODEL) {
std::string format = p.d.read<std::string>();
std::string data = p.d.read<std::string>();
client.game->models.models.insert({assetName, SerializedModel{assetName, data, format}});
client.game->models.models.insert({ assetName, SerializedModel{ assetName, data, format }});
}
t = static_cast<AssetType>(p.d.read<int>());
@ -184,7 +183,7 @@ void ConnectScene::update() {
statusText->setText(statusText->getText() + "Received " + std::to_string(count) + "x media files.\n");
}
else if (p.type == Packet::Type::MEDIA_DONE) {
components.get<GuiRect>("loadBar")->setScale({client.renderer.window.getSize().x, 32});
components.get<GuiRect>("loadBar")->setScale({ client.renderer.window.getSize().x, 32 });
statusText->setText(statusText->getText() + "Done downloading media.\nJoining world...\n");
connectState = State::DONE;
@ -201,20 +200,16 @@ void ConnectScene::handleConnecting() {
auto statusText = components.get<GuiText>("statusText");
switch (connection.getConnectionStatus()) {
default:
throw std::runtime_error("Uncaught connection error.");
default:throw std::runtime_error("Uncaught connection error.");
case ServerConnection::State::ENET_ERROR:
throw std::runtime_error("Enet Initialization error.");
case ServerConnection::State::ENET_ERROR:throw std::runtime_error("Enet Initialization error.");
break;
case ServerConnection::State::FAILED_CONNECT:
connectState = State::FAILED_CONNECT;
case ServerConnection::State::FAILED_CONNECT:connectState = State::FAILED_CONNECT;
statusText->setText(statusText->getText() + "\nFailed to connect :(\n");
break;
case ServerConnection::State::ATTEMPTING_CONNECT:
connection.processConnecting();
case ServerConnection::State::ATTEMPTING_CONNECT:connection.processConnecting();
dotsTime += client.getDelta();
if (dotsTime > 1) {
@ -224,8 +219,7 @@ void ConnectScene::handleConnecting() {
break;
case ServerConnection::State::CONNECTED:
connectState = State::PROPERTIES;
case ServerConnection::State::CONNECTED:connectState = State::PROPERTIES;
statusText->setText(statusText->getText() + " Connected!~\n");
resp.sendTo(connection.getPeer(), Packet::Channel::CONNECT);

View File

@ -9,10 +9,11 @@
#include "client/gui/basic/GuiContainer.h"
class ServerConnection;
class Address;
class ConnectScene : public Scene {
public:
public:
enum class State {
CONNECTING,
FAILED_CONNECT,
@ -26,12 +27,14 @@ public:
ConnectScene(Client& state, Address addr);
void update() override;
void draw() override;
void cleanup() override;
void handleConnecting();
private:
private:
State connectState = State::CONNECTING;
ServerConnection& connection;

View File

@ -13,18 +13,20 @@
#include "client/conn/ClientNetworkInterpreter.h"
class LocalSubgame;
class Drawable;
class GameScene : public Scene {
public:
public:
GameScene(Client& client);
void update() override;
void draw() override;
void cleanup() override;
public:
public:
WorldPtr world;
DebugGui debugGui;

View File

@ -10,7 +10,7 @@
#include "client/gui/basic/GuiRect.h"
#include "client/gui/basic/GuiText.h"
LuaErrorScene::LuaErrorScene(Client& client, const std::string &err) : Scene(client), err(err) {
LuaErrorScene::LuaErrorScene(Client& client, const std::string& err) : Scene(client), err(err) {
client.renderer.setClearColor(0, 0, 0);
client.renderer.window.input.lockMouse(false);
@ -18,24 +18,24 @@ LuaErrorScene::LuaErrorScene(Client& client, const std::string &err) : Scene(cli
glm::ivec2 win = client.renderer.window.getSize();
auto container = std::make_shared<GuiRect>("container");
container->create({800, 500}, {}, {0.05, 0.05, 0.05, 1});
container->setPos({win.x / 2 - 800 / 2, win.y / 2 - 500 / 2});
container->create({ 800, 500 }, {}, { 0.05, 0.05, 0.05, 1 });
container->setPos({ win.x / 2 - 800 / 2, win.y / 2 - 500 / 2 });
components.add(container);
auto titleText = std::make_shared<GuiText>("titleText");
titleText->create({3, 3}, {}, {}, {1, 0.4, 0.5, 1}, f);
titleText->create({ 3, 3 }, {}, {}, { 1, 0.4, 0.5, 1 }, f);
titleText->setText("The Zepha sandbox has encountered an error.");
titleText->setPos({16, 12});
titleText->setPos({ 16, 12 });
container->add(titleText);
auto errorText = std::make_shared<GuiText>("errorText");
errorText->create({2, 2}, {}, {}, {0.85, 0.85, 0.85, 1}, f);
errorText->create({ 2, 2 }, {}, {}, { 0.85, 0.85, 0.85, 1 }, f);
errorText->setText(err);
errorText->setPos({16, 48});
errorText->setPos({ 16, 48 });
container->add(errorText);
client.renderer.window.addResizeCallback("scene", [&](glm::ivec2 win) {
components.get<GuiRect>("container")->setPos({win.x / 2 - 800 / 2, win.y / 2 - 500 / 2});
components.get<GuiRect>("container")->setPos({ win.x / 2 - 800 / 2, win.y / 2 - 500 / 2 });
});
}

View File

@ -9,14 +9,16 @@
#include "client/gui/basic/GuiContainer.h"
class LuaErrorScene : public Scene {
public:
public:
LuaErrorScene(Client& client, const std::string& err);
void update() override;
void draw() override;
void cleanup() override;
private:
private:
GuiContainer components;
const std::string err;
};

View File

@ -38,14 +38,14 @@ MainMenuScene::MainMenuScene(Client& client) :
components->add(branding);
{
auto zephaText = std::make_shared<GuiText>("zephaText");
zephaText->create({GS, GS}, {}, {}, {1, 1, 1, 1}, f);
zephaText->create({ GS, GS }, {}, {}, { 1, 1, 1, 1 }, f);
zephaText->setText("Zepha");
branding->add(zephaText);
auto alphaText = std::make_shared<GuiText>("alphaText");
alphaText->create({GS, GS}, {}, {}, {1, 0.5, 0.7, 1}, f);
alphaText->create({ GS, GS }, {}, {}, { 1, 0.5, 0.7, 1 }, f);
alphaText->setText("ALPHA");
alphaText->setPos({25*GS, 0});
alphaText->setPos({ 25 * GS, 0 });
branding->add(alphaText);
}
@ -58,14 +58,14 @@ MainMenuScene::MainMenuScene(Client& client) :
components->add(navigationBar);
{
auto settingsButton = std::make_shared<GuiImageButton>("settingsButton");
settingsButton->create({16 * GS, 16 * GS}, {},
settingsButton->create({ 16 * GS, 16 * GS }, {},
client.game->textures["crop(0, 0, 16, 16, menu_flag_settings)"],
client.game->textures["crop(16, 0, 16, 16, menu_flag_settings)"]);
navigationBar->get<GuiContainer>("navigationBarIcons")->add(settingsButton);
auto closeButton = std::make_shared<GuiImageButton>("closeButton");
closeButton->create({16 * GS, 16 * GS}, {},
closeButton->create({ 16 * GS, 16 * GS }, {},
client.game->textures["crop(0, 0, 16, 16, menu_flag_quit)"],
client.game->textures["crop(16, 0, 16, 16, menu_flag_quit)"]);
@ -73,42 +73,42 @@ MainMenuScene::MainMenuScene(Client& client) :
navigationBar->get<GuiContainer>("navigationBarIcons")->add(closeButton);
auto serversButton = std::make_shared<GuiImageButton>("serversButton");
serversButton->create({16 * GS, 16 * GS}, {},
serversButton->create({ 16 * GS, 16 * GS }, {},
client.game->textures["crop(0, 0, 16, 16, menu_flag_multiplayer)"],
client.game->textures["crop(16, 0, 16, 16, menu_flag_multiplayer)"]);
serversButton->setPos({GS, GS});
serversButton->setPos({ GS, GS });
navigationBarIcons->add(serversButton);
auto contentButton = std::make_shared<GuiImageButton>("contentButton");
contentButton->create({16 * GS, 16 * GS}, {},
contentButton->create({ 16 * GS, 16 * GS }, {},
client.game->textures["crop(0, 0, 16, 16, menu_flag_content)"],
client.game->textures["crop(16, 0, 16, 16, menu_flag_content)"]);
contentButton->setPos({GS + GS * 18, GS});
contentButton->setPos({ GS + GS * 18, GS });
contentButton->setCallback(GuiComponent::CallbackType::PRIMARY, [&](bool down, glm::ivec2) {
if (!down) return;
client.scene.setScene(std::make_unique<ConnectScene>(client, Address { "127.0.0.1" }));
client.scene.setScene(std::make_unique<ConnectScene>(client, Address{ "127.0.0.1" }));
});
navigationBarIcons->add(contentButton);
auto divider = std::make_shared<GuiRect>("divider");
divider->create({GS, GS * 10}, {}, {1, 1, 1, 0.3});
divider->setPos({GS * 2 + GS * 18 * 2, GS * 4});
divider->create({ GS, GS * 10 }, {}, { 1, 1, 1, 0.3 });
divider->setPos({ GS * 2 + GS * 18 * 2, GS * 4 });
navigationBarIcons->add(divider);
findSubgames();
for (unsigned int i = 0; i < subgames.size(); i++) {
auto &subgame = subgames[i];
auto& subgame = subgames[i];
auto button = std::make_shared<GuiImageButton>(subgame.config.name);
button->create({16 * GS, 16 * GS}, {},
button->create({ 16 * GS, 16 * GS }, {},
client.game->textures["crop(0, 0, 16, 16, " + subgame.iconRef->name + ")"],
client.game->textures["crop(16, 0, 16, 16, " + subgame.iconRef->name + ")"]);
button->setPos({GS * 7 + GS * 18 * (i + 2), GS});
button->setPos({ GS * 7 + GS * 18 * (i + 2), GS });
button->setCallback(GuiComponent::CallbackType::PRIMARY, [&](bool down, glm::ivec2) {
if (!down) return;
selectedSubgame = &subgame;
@ -141,7 +141,10 @@ void MainMenuScene::findSubgames() {
while (subgamesDir.has_next) {
cf_file_t subgameFolder;
cf_read_file(&subgamesDir, &subgameFolder);
if (!subgameFolder.is_dir || strncmp(subgameFolder.name, ".", 1) == 0) { cf_dir_next(&subgamesDir); continue; }
if (!subgameFolder.is_dir || strncmp(subgameFolder.name, ".", 1) == 0) {
cf_dir_next(&subgamesDir);
continue;
}
try {
bool hasConf = false, hasIcon = false, hasMods = false;
@ -154,26 +157,35 @@ void MainMenuScene::findSubgames() {
if (!file.is_dir && strncmp(file.name, "icon.png\0", 9) == 0) hasIcon = true;
if (!file.is_dir && strncmp(file.name, "conf.json\0", 10) == 0) hasConf = true;
if ( file.is_dir && strncmp(file.name, "mods\0", 5) == 0) hasMods = true;
if (file.is_dir && strncmp(file.name, "mods\0", 5) == 0) hasMods = true;
cf_dir_next(&subgame);
}
cf_dir_close(&subgame);
if (!hasConf) throw std::runtime_error(std::string("Subgame ") + std::string(subgameFolder.name) + " is missing a conf.json.");
if (!hasMods) throw std::runtime_error(std::string("Subgame ") + std::string(subgameFolder.name) + " is missing a 'mods' directory.");
if (!hasConf)
throw std::runtime_error(
std::string("Subgame ") + std::string(subgameFolder.name) + " is missing a conf.json.");
if (!hasMods)
throw std::runtime_error(
std::string("Subgame ") + std::string(subgameFolder.name) + " is missing a 'mods' directory.");
nlohmann::json j{};
try {
std::ifstream(std::string(subgameFolder.path) + "/conf.json") >> j;
} catch (...) { throw std::runtime_error(std::string(subgameFolder.name) + "/conf.json is not a valid JSON object."); }
}
catch (...) {
throw std::runtime_error(std::string(subgameFolder.name) + "/conf.json is not a valid JSON object.");
}
if (!j.is_object())
throw std::runtime_error(std::string(subgameFolder.name) + "/conf.json is not a valid JSON object.");
if (!j["name"].is_string() || j["name"] == "")
throw std::runtime_error("The 'name' property in " + std::string(subgameFolder.name) + "/conf.json is missing or invalid.");
throw std::runtime_error(
"The 'name' property in " + std::string(subgameFolder.name) + "/conf.json is missing or invalid.");
if (!j["version"].is_string() || j["version"] == "")
throw std::runtime_error("The 'version' property in " + std::string(subgameFolder.name) + "/conf.json is missing or invalid.");
throw std::runtime_error("The 'version' property in " + std::string(subgameFolder.name) +
"/conf.json is missing or invalid.");
std::string name = j["name"];
std::string description = (j["description"].is_string() ? j["description"] : "");
@ -182,9 +194,9 @@ void MainMenuScene::findSubgames() {
std::shared_ptr<AtlasRef> icon = client.game->textures["menu_flag_missing"];
if (hasIcon) icon = client.game->textures.loadImage(std::string(subgameFolder.path) + "/icon.png", name);
subgames.push_back({icon, {name, description, version}, subgameFolder.path});
subgames.push_back({ icon, { name, description, version }, subgameFolder.path });
}
catch(const std::runtime_error& e) {
catch (const std::runtime_error& e) {
std::cout << Log::err << "Encountered an error while loading subgames:\n\t" << e.what() << Log::endl;
}
@ -192,27 +204,28 @@ void MainMenuScene::findSubgames() {
}
cf_dir_close(&subgamesDir);
std::sort(subgames.begin(), subgames.end(), [](SubgameDef& a, SubgameDef& b) { return a.config.name < b.config.name; });
std::sort(subgames.begin(), subgames.end(),
[](SubgameDef& a, SubgameDef& b) { return a.config.name < b.config.name; });
}
void MainMenuScene::positionElements() {
sandbox.windowResized();
branding->setPos({win.x - 55*GS, win.y - 30*GS});
branding->setPos({ win.x - 55 * GS, win.y - 30 * GS });
navigationBar->setPos({0, win.y - 18*GS});
navigationBar->setPos({ 0, win.y - 18 * GS });
auto navigationBarBg = navigationBar->get<GuiContainer>("navigationBarBg");
for (unsigned int i = 0; i < static_cast<float>(win.x) / 64.f / GS; i++) {
auto segment = std::make_shared<GuiRect>("segment_" + std::to_string(i));
segment->create({64 * GS, 18 * GS}, {}, client.game->textures["menu_bar_bg"]);
segment->setPos({i * 64 * GS, 0});
segment->create({ 64 * GS, 18 * GS }, {}, client.game->textures["menu_bar_bg"]);
segment->setPos({ i * 64 * GS, 0 });
navigationBarBg->add(segment);
}
auto navigationBarIcons = navigationBar->get<GuiContainer>("navigationBarIcons");
navigationBarIcons->get<GuiImageButton>("closeButton")->setPos({win.x - 16 * GS - GS, GS});
navigationBarIcons->get<GuiImageButton>("settingsButton")->setPos({win.x - 16 * GS * 2 - GS * 3, GS});
navigationBarIcons->get<GuiImageButton>("closeButton")->setPos({ win.x - 16 * GS - GS, GS });
navigationBarIcons->get<GuiImageButton>("settingsButton")->setPos({ win.x - 16 * GS * 2 - GS * 3, GS });
}
void MainMenuScene::update() {

View File

@ -12,21 +12,24 @@
class Client;
class MainMenuScene : public Scene {
public:
public:
explicit MainMenuScene(Client& client);
void update() override;
void draw() override;
void cleanup() override;
private:
private:
void positionElements();
void findSubgames();
static constexpr float GS = 3;
glm::ivec2 win {};
glm::ivec2 sandboxArea {};
glm::ivec2 win{};
glm::ivec2 sandboxArea{};
std::unique_ptr<GuiContainer> components;
std::shared_ptr<GuiContainer> branding;

View File

@ -10,11 +10,13 @@
class Client;
class Scene {
public:
public:
explicit Scene(Client& client) : client(client) {}
virtual void update() = 0;
virtual void draw() = 0;
virtual void cleanup() = 0;
virtual ~Scene() = default;

View File

@ -9,16 +9,18 @@
#include "Scene.h"
class SceneManager {
public:
public:
void setScene(std::unique_ptr<Scene> scene);
const Scene& getScene();
void update();
void cleanupScene();
~SceneManager();
private:
private:
std::unique_ptr<Scene> scene = nullptr;
};

View File

@ -13,5 +13,5 @@ struct ChunkMeshDetails {
std::vector<ChunkVertex> vertices;
std::vector<unsigned int> indices;
glm::ivec3 pos {};
glm::ivec3 pos{};
};

View File

@ -11,9 +11,9 @@
#include "world/dim/chunk/Chunk.h"
#include "world/dim/LocalDimension.h"
MeshGenStream::MeshGenStream(SubgamePtr game, LocalDimension &dimension) :
MeshGenStream::MeshGenStream(SubgamePtr game, LocalDimension& dimension) :
dimension(dimension),
noiseSampler({NoiseSample {16}, NoiseSample {16}, NoiseSample {16}}) {
noiseSampler({ NoiseSample{ 16 }, NoiseSample{ 16 }, NoiseSample{ 16 }}) {
noise::module::Perlin offsetBaseNoise;
offsetBaseNoise.SetFrequency(8);
@ -76,7 +76,7 @@ std::vector<ChunkMeshDetails*> MeshGenStream::update() {
return std::move(finishedChunks);
}
MeshGenStream::Thread::Thread(LocalSubgame &defs, std::array<NoiseSample, 3>& offsetSamplers) :
MeshGenStream::Thread::Thread(LocalSubgame& defs, std::array<NoiseSample, 3>& offsetSamplers) :
game(defs), offsetSamplers(offsetSamplers), thread(std::bind(&MeshGenStream::Thread::exec, this)) {}
void MeshGenStream::Thread::exec() {
@ -87,7 +87,8 @@ void MeshGenStream::Thread::exec() {
auto& u = jobs[i];
if (!u.busy) continue;
ChunkMeshGenerator m(u.meshDetails, game.getDefs(), game.getBiomes(), u.thisChunk, u.adjacentChunks, offsetSamplers);
ChunkMeshGenerator m(u.meshDetails, game.getDefs(), game.getBiomes(), u.thisChunk, u.adjacentChunks,
offsetSamplers);
empty = false;
u.busy = false;
}

Some files were not shown because too many files have changed in this diff Show More