Compare commits

..

52 Commits

Author SHA1 Message Date
Kayne Ruse 4cce98dba4 BattleData can hold a limited number of characters 2016-08-29 19:05:41 +10:00
Kayne Ruse b2aecc933a I need to do some refactoring 2016-08-26 00:11:54 +10:00
Kayne Ruse 64833f86da Added index to CharacterData, removed some expensive lookups 2016-08-25 23:23:57 +10:00
Kayne Ruse 518ea93adc Added RoomData::[Pop/Push]Character() 2016-08-25 20:47:08 +10:00
Kayne Ruse 07218418a2 Discovered I need to do something 2016-08-25 20:01:17 +10:00
Kayne Ruse 6d8d7963a1 Renamed CombatInstance to Battle, for clarity 2016-07-11 10:14:07 +10:00
Kayne Ruse 69a13c5ed6 Broke RoomData::RunFrame() into several parts for readability 2016-07-09 20:14:07 +10:00
Kayne Ruse 011f71ea61 Wrote out the pseudocode for RoomData::RunFrame
This method is too overloaded. The pseudocode itself takes up a whole
page.
2016-07-09 17:25:13 +10:00
Kayne Ruse 4894daa273 Moved barrier system into it's own subdirectory 2016-07-09 16:56:35 +10:00
Kayne Ruse 9a1dcc2f53 Set barrier bounds 2016-05-29 02:24:10 +10:00
Kayne Ruse 8d2fc45d7d Combat instances are created alongside the barriers 2016-05-29 02:15:41 +10:00
Kayne Ruse 867a86fd79 Fixed Missing #include<functional> 2016-05-28 13:01:19 +10:00
Kayne Ruse 7ccea0d1c0 I quit 2016-04-25 22:22:04 +10:00
Kayne Ruse 7c6468c1dd Multiple changes, read more
* Implemented HeartbeatUtility
* simplified the SQL files
* Added a dummy inventory button
2016-04-25 22:10:11 +10:00
Kayne Ruse 5285397101 I really hate SQL 2016-04-22 20:00:31 +10:00
Kayne Ruse ba295099f3 Experimenting with SQL 2016-04-22 18:14:07 +10:00
Kayne Ruse 754fb71850 Updated SQL script 2016-04-22 08:26:19 +10:00
Kayne Ruse dd25f068af Merge remote-tracking branch 'refs/remotes/origin/master' 2016-04-19 10:14:08 +10:00
Kayne Ruse bf273db9c2 Fixed Typo in README.md 2016-04-18 09:20:03 +10:00
Kayne Ruse 5d3d82bf3f Added a new button graphic 2016-04-17 02:15:23 +10:00
Kayne Ruse 36ba3fa132 Updated GUI library 2016-04-17 02:10:08 +10:00
Kayne Ruse 3002afa1e9 Moved a file 2016-04-17 01:35:34 +10:00
Kayne Ruse f9936f6107 Fixed bin directory 2016-04-15 00:22:53 +10:00
Kayne Ruse 905af46731 Adjusted file names for case sensitivity 2016-04-15 00:17:13 +10:00
Kayne Ruse 8b0bc76a9f Fixed a script 2016-04-14 23:42:11 +10:00
Kayne Ruse fb2d49f1e0 Added respawning rabbits 2016-04-14 23:33:39 +10:00
Kayne Ruse cc6981e35f Refined culling logic, added periodic query 2016-04-14 22:56:15 +10:00
Kayne Ruse f9a5f60969 Try a different approach for creature deletion
This works almost instantly, as opposed to the refactored version, which
takes nearly a second, or more.
2016-04-14 21:52:44 +10:00
Kayne Ruse b74a5aabcd Comment tweaks 2016-04-14 04:17:49 +10:00
Kayne Ruse 7c88392cf3 The server is updating the barrier display 2016-04-12 19:11:57 +10:00
Kayne Ruse 20b121766a Expanded creature & barrier API 2016-04-11 02:18:13 +10:00
Kayne Ruse f32b8a9b4f Exposed BarrierManager to the API* 2016-04-11 01:03:02 +10:00
Kayne Ruse ccb7adbd10 Fixed copying pointer to/from packet 2016-04-11 01:01:22 +10:00
Kayne Ruse 8e7af9ce88 Fixed the table inheritance which was backwards 2016-04-11 00:08:42 +10:00
Kayne Ruse 752f8f82f9 Unit tested CompositeImage, BaseBarrier::CorrectSprite working correctly 2016-04-10 00:12:27 +10:00
Kayne Ruse 1f2d0b8e76 Barriers are created at the correct location 2016-04-09 00:02:39 +10:00
Kayne Ruse ec409c8177 Reduced a graphical artifact, but it's still visible 2016-04-08 23:50:52 +10:00
Kayne Ruse 82d5a5c181 Moved BarrierManager 2016-04-08 23:32:41 +10:00
Kayne Ruse 420d39d467 Barriers are being drawn 2016-04-08 23:30:17 +10:00
Kayne Ruse e2e2e243d4 Server responds to barrier queries 2016-04-08 22:30:44 +10:00
Kayne Ruse 5d0f9e1bb8 Barriers are created in client-side BarrierManager
Still need to hookup a barrier query, and get them drawn to the screen.
2016-04-08 10:48:01 +10:00
Kayne Ruse d3f855c69b Wrote CompositeImage, added it to BaseBarrier 2016-04-05 23:40:31 +10:00
Kayne Ruse 8749d1fd93 Barriers are queried, created when colliding with creatures 2016-04-04 02:41:14 +10:00
Kayne Ruse 7205d6692c Threaded barriers into the client, not yet queried
I've also refactored the rooms slightly.
2016-04-04 01:05:32 +10:00
Kayne Ruse 7b9c016082 Threaded the barriers through the networking system 2016-04-03 22:32:39 +10:00
Kayne Ruse 235f3b57e0 Filled out some barrier stuff 2016-04-03 21:27:48 +10:00
Kayne Ruse f23b929f8a Added some boilerplate 2016-04-03 16:04:41 +10:00
Kayne Ruse 48b9a9b264 Added combat scene 2016-04-03 15:24:20 +10:00
Kayne Ruse d7196df760 Added some files for combat system 2016-04-03 02:44:09 +11:00
Kayne Ruse 957458d489 Renamed some of Get() methods to Find(), read more
From now on, ideally any function with "get" in the name should always
return a valid value. A function with "find" in the name, however, does
the same thing, but may also return an invalid result such as an error
code.
2016-04-03 02:17:02 +11:00
Kayne Ruse 3b24aae422 Added barrier graphics 2016-04-01 01:31:14 +11:00
Kayne Ruse a751531e18 Added distance based creature culling 2016-03-30 12:54:59 +11:00
128 changed files with 3857 additions and 510 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ This game is inspired by classic 2D RPGs (Final Fantasy, The Legend of Zelda), a
## Releases ## Releases
* The most recent stable build for Windows can be found [here](https://dl.dropboxusercontent.com/u/46669050/Tortuga-win.rar). * The most recent stable build for Windows can be found [here](https://dl.dropboxusercontent.com/u/46669050/Tortuga-win.rar).
* The most recent stable build for Windows can be found [here](https://dl.dropboxusercontent.com/u/46669050/Tortuga-linux.tar). * The most recent stable build for Linux can be found [here](https://dl.dropboxusercontent.com/u/46669050/Tortuga-linux.tar).
## Documentation ## Documentation
+4
View File
@@ -318,6 +318,7 @@ void ClientApplication::ProcessEvents() {
#include "options_menu.hpp" #include "options_menu.hpp"
#include "lobby_menu.hpp" #include "lobby_menu.hpp"
#include "world.hpp" #include "world.hpp"
#include "combat.hpp"
#include "disconnected_screen.hpp" #include "disconnected_screen.hpp"
void ClientApplication::ProcessSceneSignal(SceneSignal signal) { void ClientApplication::ProcessSceneSignal(SceneSignal signal) {
@@ -341,6 +342,9 @@ void ClientApplication::ProcessSceneSignal(SceneSignal signal) {
case SceneSignal::WORLD: case SceneSignal::WORLD:
activeScene = new World(&clientIndex, &accountIndex); activeScene = new World(&clientIndex, &accountIndex);
break; break;
case SceneSignal::COMBAT:
activeScene = new Combat(&clientIndex, &accountIndex);
break;
case SceneSignal::DISCONNECTEDSCREEN: case SceneSignal::DISCONNECTEDSCREEN:
activeScene = new DisconnectedScreen(); activeScene = new DisconnectedScreen();
break; break;
+94
View File
@@ -0,0 +1,94 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "barrier_manager.hpp"
void BarrierManager::DrawTo(SDL_Renderer* const dest, Sint16 x, Sint16 y, double scaleX, double scaleY) {
for (auto& it : elementMap) {
it.second.DrawTo(dest, x, y);
}
}
void BarrierManager::LoadBaseImage(SDL_Renderer* renderer, std::string fname) {
baseImage.Load(renderer, fname);
}
void BarrierManager::UnloadBaseImage() {
baseImage.Free();
}
void BarrierManager::LoadTemplateImages(SDL_Renderer* renderer, std::string spriteDir, std::list<std::string> names) {
//sprite names are file names only
for (auto& it : names) {
templateImages.emplace(it, Image(renderer, spriteDir + it));
}
}
void BarrierManager::UnloadTemplateImages() {
templateImages.clear();
}
BaseBarrier* BarrierManager::Create(int index) {
elementMap.emplace(index, BaseBarrier(baseImage, templateImages));
return &elementMap[index];
}
void BarrierManager::Unload(int i) {
elementMap.erase(i);
}
void BarrierManager::UnloadAll() {
elementMap.clear();
}
void BarrierManager::UnloadIf(std::function<bool(std::pair<const int, BaseBarrier const&>)> fn) {
std::map<int, BaseBarrier>::iterator it = elementMap.begin();
while (it != elementMap.end()) {
if (fn(*it)) {
it = elementMap.erase(it);
}
else {
++it;
}
}
}
int BarrierManager::Size() {
return elementMap.size();
}
BaseBarrier* BarrierManager::Find(int i) {
std::map<int, BaseBarrier>::iterator it = elementMap.find(i);
if (it == elementMap.end()) {
return nullptr;
}
return &it->second;
}
std::map<int, BaseBarrier>* BarrierManager::GetContainer() {
return &elementMap;
}
std::map<std::string, Image>* BarrierManager::GetTemplateContainer() {
return &templateImages;
}
+58
View File
@@ -0,0 +1,58 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "base_barrier.hpp"
#include <functional>
#include <list>
#include <string>
class BarrierManager {
public:
BarrierManager() = default;
~BarrierManager() = default;
void DrawTo(SDL_Renderer* const, Sint16 x, Sint16 y, double scaleX = 1.0, double scaleY = 1.0);
//NOTE: don't use these while you have barriers loaded
void LoadBaseImage(SDL_Renderer* renderer, std::string fname);
void UnloadBaseImage();
void LoadTemplateImages(SDL_Renderer* renderer, std::string spriteDir, std::list<std::string> names);
void UnloadTemplateImages();
BaseBarrier* Create(int index);
void Unload(int i);
void UnloadAll();
void UnloadIf(std::function<bool(std::pair<const int, BaseBarrier const&>)> fn);
int Size();
BaseBarrier* Find(int i);
std::map<int, BaseBarrier>* GetContainer();
std::map<std::string, Image>* GetTemplateContainer();
private:
Image baseImage;
std::map<std::string, Image> templateImages;
std::map<int, BaseBarrier> elementMap;
};
+105
View File
@@ -0,0 +1,105 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "base_barrier.hpp"
#include "config_utility.hpp"
#include <cstring>
#include <sstream>
#include <stdexcept>
BaseBarrier::BaseBarrier(Image& argBaseImage, std::map<std::string, Image>& templateImages) {
baseImage.SetTexture(argBaseImage.GetTexture());
composite.SetTextures(templateImages);
memset(status, 0, sizeof(int) * 8);
CorrectSprite();
}
BaseBarrier::~BaseBarrier() {
//
}
void BaseBarrier::CorrectSprite() {
//TODO: link status to sprite
for (int i = 0; i < 8; i++) {
//setup the name
std::ostringstream os;
os << "slot " << i+1;
switch(status[i]) {
case 0:
composite.Disable(os.str() + " green.png");
composite.Disable(os.str() + " red.png");
break;
case 1:
composite.Enable(os.str() + " green.png");
composite.Disable(os.str() + " red.png");
break;
case 2:
composite.Disable(os.str() + " green.png");
composite.Enable(os.str() + " red.png");
break;
default: {
std::ostringstream os;
os << "index " << i << ", value " << status[i] << std::endl;
throw(std::runtime_error("Unknown graphical status in barrier; " + os.str()));
}
}
}
}
void BaseBarrier::Update() {
//
}
void BaseBarrier::DrawTo(SDL_Renderer* const dest, int camX, int camY) {
//ignore the default sprite for now
baseImage.DrawTo(dest, origin.x - camX, origin.y - camY);
composite.DrawTo(dest, origin.x - camX, origin.y - camY);
}
int BaseBarrier::SetStatus(int k, int v) {
if (k >= 8 || k < 0) {
return -1;
}
return status[k] = v;
}
int BaseBarrier::FindStatus(int k) {
if (k >= 8 || k < 0) {
return -1;
}
return status[k];
}
int* BaseBarrier::SetStatusArray(int* ptr) {
memcpy(status, ptr, sizeof(int) * 8);
return status;
}
int* BaseBarrier::GetStatusArray() {
return status;
}
CompositeImage<>* BaseBarrier::GetComposite() {
return &composite;
}
+52
View File
@@ -0,0 +1,52 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "entity.hpp"
#include "composite_image.hpp"
class BaseBarrier: public Entity {
public:
BaseBarrier() = default;
BaseBarrier(Image& baseImage, std::map<std::string, Image>& templateImages);
virtual ~BaseBarrier();
void CorrectSprite();
void Update();
void DrawTo(SDL_Renderer* const, int camX, int camY);
int SetStatus(int, int);
int FindStatus(int);
int* SetStatusArray(int*);
int* GetStatusArray();
CompositeImage<>* GetComposite();
protected:
//metadata
int status[8];
Image baseImage;
CompositeImage<> composite;
};
+3 -3
View File
@@ -50,14 +50,14 @@ BoundingBox Entity::SetBounds(BoundingBox b) {
return bounds = b; return bounds = b;
} }
Vector2 Entity::GetOrigin() { Vector2 Entity::GetOrigin() const {
return origin; return origin;
} }
Vector2 Entity::GetMotion() { Vector2 Entity::GetMotion() const {
return motion; return motion;
} }
BoundingBox Entity::GetBounds() { BoundingBox Entity::GetBounds() const {
return bounds; return bounds;
} }
+3 -3
View File
@@ -39,9 +39,9 @@ public:
Vector2 SetMotion(Vector2 v); Vector2 SetMotion(Vector2 v);
BoundingBox SetBounds(BoundingBox b); BoundingBox SetBounds(BoundingBox b);
Vector2 GetOrigin(); Vector2 GetOrigin() const;
Vector2 GetMotion(); Vector2 GetMotion() const;
BoundingBox GetBounds(); BoundingBox GetBounds() const;
protected: protected:
Entity() = default; Entity() = default;
+58
View File
@@ -0,0 +1,58 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "heartbeat_utility.hpp"
#include "channels.hpp"
#include "ip_operators.hpp"
//heartbeat system
void HeartbeatUtility::hPing(ServerPacket* const argPacket) {
ServerPacket newPacket;
newPacket.type = SerialPacketType::PONG;
network.SendTo(argPacket->srcAddress, &newPacket);
}
void HeartbeatUtility::hPong(ServerPacket* const argPacket) {
if (*network.GetIPAddress(Channels::SERVER) != argPacket->srcAddress) {
throw(std::runtime_error("Heartbeat message received from an unknown source"));
}
attemptedBeats = 0;
lastBeat = Clock::now();
}
int HeartbeatUtility::CheckHeartBeat() {
//check the connection (heartbeat)
if (Clock::now() - lastBeat > std::chrono::seconds(3)) {
if (attemptedBeats > 2) {
return 1;
}
else {
ServerPacket newPacket;
newPacket.type = SerialPacketType::PING;
network.SendTo(Channels::SERVER, &newPacket);
attemptedBeats++;
lastBeat = Clock::now();
}
}
return 0;
}
+42
View File
@@ -0,0 +1,42 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "server_packet.hpp"
#include "udp_network_utility.hpp"
#include <chrono>
class HeartbeatUtility {
public:
//heartbeat system
void hPing(ServerPacket* const);
void hPong(ServerPacket* const);
int CheckHeartBeat();
private:
UDPNetworkUtility& network = UDPNetworkUtility::GetSingleton();
typedef std::chrono::steady_clock Clock;
Clock::time_point lastBeat = Clock::now();
int attemptedBeats = 0;
};
+1
View File
@@ -33,5 +33,6 @@ enum SceneSignal {
OPTIONSMENU, OPTIONSMENU,
LOBBYMENU, LOBBYMENU,
WORLD, WORLD,
COMBAT,
DISCONNECTEDSCREEN, DISCONNECTEDSCREEN,
}; };
+77
View File
@@ -0,0 +1,77 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "combat.hpp"
//Public access members
Combat::Combat(int* const argClientIndex, int* const argAccountIndex) {
//
}
Combat::~Combat() {
//
}
void Combat::RenderFrame(SDL_Renderer* renderer) {
//
}
//frame phases
void Combat::FrameStart() {
//
}
void Combat::Update() {
//
}
void Combat::FrameEnd() {
//
}
//input events
void Combat::QuitEvent() {
//
}
void Combat::MouseMotion(SDL_MouseMotionEvent const& event) {
//
}
void Combat::MouseButtonDown(SDL_MouseButtonEvent const& event) {
//
}
void Combat::MouseButtonUp(SDL_MouseButtonEvent const& event) {
//
}
void Combat::MouseWheel(SDL_MouseWheelEvent const& event) {
//
}
void Combat::KeyDown(SDL_KeyboardEvent const& event) {
//
}
void Combat::KeyUp(SDL_KeyboardEvent const& event) {
//
}
+48
View File
@@ -0,0 +1,48 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "base_scene.hpp"
class Combat: public BaseScene {
public:
//Public access members
Combat(int* const argClientIndex, int* const argAccountIndex);
~Combat();
void RenderFrame(SDL_Renderer* renderer) override;
private:
//frame phases
void FrameStart() override;
void Update() override;
void FrameEnd() override;
//input events
void QuitEvent();
void MouseMotion(SDL_MouseMotionEvent const& event) override;
void MouseButtonDown(SDL_MouseButtonEvent const& event) override;
void MouseButtonUp(SDL_MouseButtonEvent const& event) override;
void MouseWheel(SDL_MouseWheelEvent const& event) override;
void KeyDown(SDL_KeyboardEvent const& event) override;
void KeyUp(SDL_KeyboardEvent const& event) override;
};
+7 -3
View File
@@ -28,6 +28,8 @@
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
constexpr SDL_Color WHITE = {255, 255, 255, 255};
//------------------------- //-------------------------
//Public access members //Public access members
//------------------------- //-------------------------
@@ -49,14 +51,16 @@ DisconnectedScreen::DisconnectedScreen() {
//setup the button //setup the button
backButton.SetBackgroundTexture(GetRenderer(), image.GetTexture()); backButton.SetBackgroundTexture(GetRenderer(), image.GetTexture());
backButton.SetText(GetRenderer(), font, "Back", COLOR_WHITE); backButton.SetText(GetRenderer(), font, WHITE, "Back");
//set the button positions //set the button positions
backButton.SetX(50); backButton.SetX(50);
backButton.SetY(50); backButton.SetY(50);
//set the disconnection message text //set the disconnection message text
textLine.SetText(GetRenderer(), font, config["client.disconnectMessage"], {255, 255, 255, 255}); textLine.SetX(50);
textLine.SetY(30);
textLine.SetText(GetRenderer(), font, WHITE, config["client.disconnectMessage"]);
//full reset //full reset
UDPNetworkUtility::GetSingleton().Unbind(Channels::SERVER); UDPNetworkUtility::GetSingleton().Unbind(Channels::SERVER);
@@ -92,7 +96,7 @@ void DisconnectedScreen::FrameEnd() {
void DisconnectedScreen::RenderFrame(SDL_Renderer* renderer) { void DisconnectedScreen::RenderFrame(SDL_Renderer* renderer) {
backButton.DrawTo(renderer); backButton.DrawTo(renderer);
textLine.DrawTo(renderer, 50, 30); textLine.DrawTo(renderer);
} }
//------------------------- //-------------------------
+15 -7
View File
@@ -27,6 +27,8 @@
#include <stdexcept> #include <stdexcept>
#include <sstream> #include <sstream>
constexpr SDL_Color WHITE = {255, 255, 255, 255};
//------------------------- //-------------------------
//Public access members //Public access members
//------------------------- //-------------------------
@@ -52,11 +54,11 @@ LobbyMenu::LobbyMenu(int* const argClientIndex, int* const argAccountIndex):
//setup the buttons //setup the buttons
searchButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture()); searchButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture());
searchButton.SetText(GetRenderer(), font, "Search", COLOR_WHITE); searchButton.SetText(GetRenderer(), font, WHITE, "Search");
joinButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture()); joinButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture());
joinButton.SetText(GetRenderer(), font, "Join", COLOR_WHITE); joinButton.SetText(GetRenderer(), font, WHITE, "Join");
backButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture()); backButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture());
backButton.SetText(GetRenderer(), font, "Back", COLOR_WHITE); backButton.SetText(GetRenderer(), font, WHITE, "Back");
//set the button positions (assumed) //set the button positions (assumed)
searchButton.SetX(50); searchButton.SetX(50);
@@ -67,6 +69,7 @@ LobbyMenu::LobbyMenu(int* const argClientIndex, int* const argAccountIndex):
backButton.SetY(90); backButton.SetY(90);
//pseudo-list selection //pseudo-list selection
//TODO: move this into the UI library?
boundingBox = {300, 50, 200, 12}; boundingBox = {300, 50, 200, 12};
//hacked together a highlight box //hacked together a highlight box
@@ -121,8 +124,13 @@ void LobbyMenu::RenderFrame(SDL_Renderer* renderer) {
} }
//draw the server's info //draw the server's info
serverVector[i].nameImage.DrawTo(renderer, boundingBox.x, boundingBox.y + boundingBox.h * i); serverVector[i].nameImage.SetX(boundingBox.x);
serverVector[i].playerCountImage.DrawTo(renderer, boundingBox.x+276, boundingBox.y + boundingBox.h * i); serverVector[i].nameImage.SetY(boundingBox.y + boundingBox.h * i);
serverVector[i].nameImage.DrawTo(renderer);
serverVector[i].playerCountImage.SetX(boundingBox.x+276);
serverVector[i].playerCountImage.SetY(boundingBox.y + boundingBox.h * i);
serverVector[i].playerCountImage.DrawTo(renderer);
} }
} }
@@ -248,8 +256,8 @@ void LobbyMenu::HandleBroadcastResponse(ServerPacket* const argPacket) {
}; };
//text graphics //text graphics
serverVector.back().nameImage.SetText(GetRenderer(), font, newServer.name, color); serverVector.back().nameImage.SetText(GetRenderer(), font, color, newServer.name);
serverVector.back().playerCountImage.SetText(GetRenderer(), font, itoa_base10(newServer.playerCount), color); serverVector.back().playerCountImage.SetText(GetRenderer(), font, color, itoa_base10(newServer.playerCount));
} }
void LobbyMenu::HandleJoinResponse(ClientPacket* const argPacket) { void LobbyMenu::HandleJoinResponse(ClientPacket* const argPacket) {
+15 -11
View File
@@ -26,6 +26,8 @@
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
constexpr SDL_Color WHITE = {255, 255, 255, 255};
//------------------------- //-------------------------
//Public access members //Public access members
//------------------------- //-------------------------
@@ -46,11 +48,11 @@ MainMenu::MainMenu() {
//setup the buttons //setup the buttons
startButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture()); startButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture());
startButton.SetText(GetRenderer(), font, "Start", COLOR_WHITE); startButton.SetText(GetRenderer(), font, WHITE, "Start");
optionsButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture()); optionsButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture());
optionsButton.SetText(GetRenderer(), font, "Options", COLOR_WHITE); optionsButton.SetText(GetRenderer(), font, WHITE, "Options");
quitButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture()); quitButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture());
quitButton.SetText(GetRenderer(), font, "Quit", COLOR_WHITE); quitButton.SetText(GetRenderer(), font, WHITE, "Quit");
//set the button positions //set the button positions
startButton.SetX(50); startButton.SetX(50);
@@ -61,9 +63,15 @@ MainMenu::MainMenu() {
quitButton.SetY(50 + 20 * 2); quitButton.SetY(50 + 20 * 2);
//text box //text box
textBox.PushLine(GetRenderer(), font, "Thanks for playing!", {255, 255, 255, 255}); int h = -1;
textBox.PushLine(GetRenderer(), font, "You can get the latest version at: ", {255, 255, 255, 255}); SDL_RenderGetLogicalSize(GetRenderer(), nullptr, &h);
textBox.PushLine(GetRenderer(), font, "krgamestudios.com", {255, 255, 255, 255}); //TODO: (9) click to open the website/update
textBox.SetX(50);
textBox.SetY(h-100);
textBox.PushLine(GetRenderer(), font, WHITE, "Thanks for playing!");
textBox.PushLine(GetRenderer(), font, WHITE, "You can get the latest version at: ");
textBox.PushLine(GetRenderer(), font, WHITE, "krgamestudios.com"); //TODO: (9) click to open the website/update
//debug //debug
// //
@@ -93,11 +101,7 @@ void MainMenu::RenderFrame(SDL_Renderer* renderer) {
startButton.DrawTo(renderer); startButton.DrawTo(renderer);
optionsButton.DrawTo(renderer); optionsButton.DrawTo(renderer);
quitButton.DrawTo(renderer); quitButton.DrawTo(renderer);
textBox.DrawTo(renderer);
int h = -1;
SDL_RenderGetLogicalSize(GetRenderer(), nullptr, &h);
textBox.DrawTo(renderer, 50, h-50, -12);
} }
//------------------------- //-------------------------
+7 -3
View File
@@ -26,6 +26,8 @@
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
constexpr SDL_Color WHITE = {255, 255, 255, 255};
//------------------------- //-------------------------
//Public access members //Public access members
//------------------------- //-------------------------
@@ -46,14 +48,16 @@ OptionsMenu::OptionsMenu() {
//setup the button //setup the button
backButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture()); backButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture());
backButton.SetText(GetRenderer(), font, "Back", COLOR_WHITE); backButton.SetText(GetRenderer(), font, WHITE, "Back");
//set the button positions //set the button positions
backButton.SetX(50); backButton.SetX(50);
backButton.SetY(50); backButton.SetY(50);
//text line //text line
textLine.SetText(GetRenderer(), font, "This code is fucking hard to refactor.", {255, 255, 255, 255}); textLine.SetX(50);
textLine.SetY(30);
textLine.SetText(GetRenderer(), font, WHITE, "Am I making any progress?");
} }
OptionsMenu::~OptionsMenu() { OptionsMenu::~OptionsMenu() {
@@ -78,7 +82,7 @@ void OptionsMenu::FrameEnd() {
void OptionsMenu::RenderFrame(SDL_Renderer* renderer) { void OptionsMenu::RenderFrame(SDL_Renderer* renderer) {
backButton.DrawTo(renderer); backButton.DrawTo(renderer);
textLine.DrawTo(renderer, 50, 30); textLine.DrawTo(renderer);
} }
//------------------------- //-------------------------
+219 -68
View File
@@ -22,6 +22,7 @@
#include "world.hpp" #include "world.hpp"
#include "channels.hpp" #include "channels.hpp"
#include "culling_defines.hpp"
#include "ip_operators.hpp" #include "ip_operators.hpp"
#include "fatal_error.hpp" #include "fatal_error.hpp"
@@ -33,6 +34,8 @@
#include <sstream> #include <sstream>
#include <stdexcept> #include <stdexcept>
constexpr SDL_Color WHITE = {255, 255, 255, 255};
//------------------------- //-------------------------
//static functions //static functions
//------------------------- //-------------------------
@@ -71,9 +74,9 @@ World::World(int* const argClientIndex, int* const argAccountIndex):
//setup the buttons //setup the buttons
disconnectButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture()); disconnectButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture());
disconnectButton.SetText(GetRenderer(), font, "Disconnect", COLOR_WHITE); disconnectButton.SetText(GetRenderer(), font, WHITE, "Disconnect");
shutdownButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture()); shutdownButton.SetBackgroundTexture(GetRenderer(), buttonImage.GetTexture());
shutdownButton.SetText(GetRenderer(), font, "Shutdown", COLOR_WHITE); shutdownButton.SetText(GetRenderer(), font, WHITE, "Shutdown");
//set the button positions //set the button positions
disconnectButton.SetX(50); disconnectButton.SetX(50);
@@ -97,7 +100,28 @@ World::World(int* const argClientIndex, int* const argAccountIndex):
SDL_RenderGetLogicalSize(GetRenderer(), &camera.width, &camera.height); SDL_RenderGetLogicalSize(GetRenderer(), &camera.width, &camera.height);
//debug //debug
// std::list<std::string> slotNames = {
"slot 1 green.png",
"slot 2 green.png",
"slot 3 green.png",
"slot 4 green.png",
"slot 5 green.png",
"slot 6 green.png",
"slot 7 green.png",
"slot 8 green.png",
"slot 1 red.png",
"slot 2 red.png",
"slot 3 red.png",
"slot 4 red.png",
"slot 5 red.png",
"slot 6 red.png",
"slot 7 red.png",
"slot 8 red.png"
};
barrierMgr.LoadBaseImage(GetRenderer(), config["dir.sprites"] + "barrier/base.png");
barrierMgr.LoadTemplateImages(GetRenderer(), config["dir.sprites"] + "barrier/", slotNames);
std::cout << "Templates loaded: " << barrierMgr.GetTemplateContainer()->size() << std::endl;
} }
World::~World() { World::~World() {
@@ -137,7 +161,12 @@ void World::Update() {
delete reinterpret_cast<char*>(packetBuffer); delete reinterpret_cast<char*>(packetBuffer);
//heartbeat system //heartbeat system
CheckHeartBeat(); if (heartbeatUtility.CheckHeartBeat()) {
//escape to the disconnect screen
SendDisconnectRequest();
SetSceneSignal(SceneSignal::DISCONNECTEDSCREEN);
ConfigUtility::GetSingleton()["client.disconnectMessage"] = "Error: Lost connection to the server";
}
//update all entities //update all entities
for (auto& it : characterMap) { for (auto& it : characterMap) {
@@ -163,6 +192,42 @@ void World::Update() {
return; return;
} }
//TODO: (0) regular query interval
if (Clock::now() - queryTime > std::chrono::seconds(3)) {
queryTime = Clock::now();
//query the world state (room)
CharacterPacket characterPacket;
memset(&characterPacket, 0, MAX_PACKET_SIZE);
characterPacket.type = SerialPacketType::QUERY_CHARACTER_EXISTS;
characterPacket.roomIndex = roomIndex;
network.SendTo(Channels::SERVER, &characterPacket);
CreaturePacket creaturePacket;
creaturePacket.type = SerialPacketType::QUERY_CREATURE_EXISTS;
creaturePacket.roomIndex = roomIndex;
network.SendTo(Channels::SERVER, &creaturePacket);
BarrierPacket barrierPacket;
barrierPacket.type = SerialPacketType::QUERY_BARRIER_EXISTS;
barrierPacket.roomIndex = roomIndex;
network.SendTo(Channels::SERVER, &barrierPacket);
}
//cull creatures
for (std::map<int, BaseCreature>::iterator it = creatureMap.begin(); it != creatureMap.end(); /* */) {
if ( (localCharacter->GetOrigin() - it->second.GetOrigin()).Length() > INFLUENCE_RADIUS) {
creatureMap.erase(it++);
}
else {
it++;
}
}
//cull barriers
barrierMgr.UnloadIf([&](std::pair<const int, BaseBarrier const&> barrierIt) -> bool {
return (localCharacter->GetOrigin() - barrierIt.second.GetOrigin()).Length() > INFLUENCE_RADIUS;
});
//get the collidable boxes //get the collidable boxes
std::list<BoundingBox> boxList = GenerateCollisionGrid(localCharacter, tileSheet.GetTileW(), tileSheet.GetTileH()); std::list<BoundingBox> boxList = GenerateCollisionGrid(localCharacter, tileSheet.GetTileW(), tileSheet.GetTileH());
@@ -196,18 +261,19 @@ void World::RenderFrame(SDL_Renderer* renderer) {
for (auto& it : creatureMap) { for (auto& it : creatureMap) {
it.second.DrawTo(renderer, camera.x, camera.y); it.second.DrawTo(renderer, camera.x, camera.y);
} }
barrierMgr.DrawTo(renderer, camera.x, camera.y);
//draw UI //draw UI
disconnectButton.DrawTo(renderer); disconnectButton.DrawTo(renderer);
shutdownButton.DrawTo(renderer); shutdownButton.DrawTo(renderer);
//FPS //FPS
fpsTextLine.DrawTo(renderer, 0, 0); fpsTextLine.DrawTo(renderer);
int fpsRet = fps.Calculate(); int fpsRet = fps.Calculate();
if (fpsRet != -1) { if (fpsRet != -1) {
std::ostringstream msg; std::ostringstream msg;
msg << "FPS: " << fpsRet; msg << "FPS: " << fpsRet;
fpsTextLine.SetText(renderer, font, msg.str(), {255, 255, 255, 255}); fpsTextLine.SetText(renderer, font, WHITE, msg.str());
} }
} }
@@ -350,10 +416,10 @@ void World::HandlePacket(SerialPacket* const argPacket) {
switch(argPacket->type) { switch(argPacket->type) {
//heartbeat system //heartbeat system
case SerialPacketType::PING: case SerialPacketType::PING:
hPing(static_cast<ServerPacket*>(argPacket)); heartbeatUtility.hPing(static_cast<ServerPacket*>(argPacket));
break; break;
case SerialPacketType::PONG: case SerialPacketType::PONG:
hPong(static_cast<ServerPacket*>(argPacket)); heartbeatUtility.hPong(static_cast<ServerPacket*>(argPacket));
break; break;
//game server connections //game server connections
@@ -412,6 +478,22 @@ void World::HandlePacket(SerialPacket* const argPacket) {
hCreatureMovement(static_cast<CreaturePacket*>(argPacket)); hCreatureMovement(static_cast<CreaturePacket*>(argPacket));
break; break;
//barrier management
case SerialPacketType::BARRIER_UPDATE:
hBarrierUpdate(static_cast<BarrierPacket*>(argPacket));
break;
case SerialPacketType::BARRIER_CREATE:
hBarrierCreate(static_cast<BarrierPacket*>(argPacket));
break;
case SerialPacketType::BARRIER_UNLOAD:
hBarrierUnload(static_cast<BarrierPacket*>(argPacket));
break;
case SerialPacketType::QUERY_BARRIER_EXISTS:
hQueryBarrierExists(static_cast<BarrierPacket*>(argPacket));
break;
//chat //chat
case SerialPacketType::TEXT_BROADCAST: case SerialPacketType::TEXT_BROADCAST:
hTextBroadcast(static_cast<TextPacket*>(argPacket)); hTextBroadcast(static_cast<TextPacket*>(argPacket));
@@ -443,44 +525,6 @@ void World::HandlePacket(SerialPacket* const argPacket) {
} }
} }
//-------------------------
//heartbeat system
//-------------------------
void World::hPing(ServerPacket* const argPacket) {
ServerPacket newPacket;
newPacket.type = SerialPacketType::PONG;
network.SendTo(argPacket->srcAddress, &newPacket);
}
void World::hPong(ServerPacket* const argPacket) {
if (*network.GetIPAddress(Channels::SERVER) != argPacket->srcAddress) {
throw(std::runtime_error("Heartbeat message received from an unknown source"));
}
attemptedBeats = 0;
lastBeat = Clock::now();
}
void World::CheckHeartBeat() {
//check the connection (heartbeat)
if (Clock::now() - lastBeat > std::chrono::seconds(3)) {
if (attemptedBeats > 2) {
//escape to the disconnect screen
SendDisconnectRequest();
SetSceneSignal(SceneSignal::DISCONNECTEDSCREEN);
ConfigUtility::GetSingleton()["client.disconnectMessage"] = "Error: Lost connection to the server";
}
else {
ServerPacket newPacket;
newPacket.type = SerialPacketType::PING;
network.SendTo(Channels::SERVER, &newPacket);
attemptedBeats++;
lastBeat = Clock::now();
}
}
}
//------------------------- //-------------------------
//Connection control //Connection control
//------------------------- //-------------------------
@@ -675,6 +719,9 @@ void World::hCharacterCreate(CharacterPacket* const argPacket) {
if (character->GetOwner() == accountIndex) { if (character->GetOwner() == accountIndex) {
localCharacter = static_cast<LocalCharacter*>(character); localCharacter = static_cast<LocalCharacter*>(character);
//reset queries
queryTime = Clock::now() - std::chrono::seconds(4); //back 4 seconds to trigger automatically
//focus the camera on this character's sprite //focus the camera on this character's sprite
camera.marginX = (camera.width / 2 - localCharacter->GetSprite()->GetClipW() / 2); camera.marginX = (camera.width / 2 - localCharacter->GetSprite()->GetClipW() / 2);
camera.marginY = (camera.height/ 2 - localCharacter->GetSprite()->GetClipH() / 2); camera.marginY = (camera.height/ 2 - localCharacter->GetSprite()->GetClipH() / 2);
@@ -682,18 +729,6 @@ void World::hCharacterCreate(CharacterPacket* const argPacket) {
//focus on this character's info //focus on this character's info
characterIndex = argPacket->characterIndex; characterIndex = argPacket->characterIndex;
roomIndex = argPacket->roomIndex; roomIndex = argPacket->roomIndex;
//query the world state (room)
CharacterPacket characterPacket;
memset(&characterPacket, 0, MAX_PACKET_SIZE);
characterPacket.type = SerialPacketType::QUERY_CHARACTER_EXISTS;
characterPacket.roomIndex = roomIndex;
network.SendTo(Channels::SERVER, &characterPacket);
CreaturePacket creaturePacket;
creaturePacket.type = SerialPacketType::QUERY_CREATURE_EXISTS;
creaturePacket.roomIndex = roomIndex;
network.SendTo(Channels::SERVER, &creaturePacket);
} }
//debug //debug
@@ -715,9 +750,10 @@ void World::hCharacterUnload(CharacterPacket* const argPacket) {
camera.marginX = 0; camera.marginX = 0;
camera.marginY = 0; camera.marginY = 0;
//clear the room //clear/reset the room
roomIndex = -1; roomIndex = -1;
regionPager.UnloadAll(); regionPager.UnloadAll();
barrierMgr.UnloadAll();
characterMap.clear(); characterMap.clear();
creatureMap.clear(); creatureMap.clear();
} }
@@ -733,12 +769,12 @@ void World::hCharacterUnload(CharacterPacket* const argPacket) {
void World::hQueryCharacterExists(CharacterPacket* const argPacket) { void World::hQueryCharacterExists(CharacterPacket* const argPacket) {
//prevent a double message about this player's character //prevent a double message about this player's character
//TODO: why is this commented out? //TODO: why is this commented out?
// if (argPacket->accountIndex == accountIndex) { if (argPacket->accountIndex == accountIndex) {
// return; return;
// } }
//ignore characters in a different room (sub-optimal) //ignore characters in a different room (sub-optimal)
if (argPacket->roomIndex != roomIndex) { if (argPacket->roomIndex != roomIndex || (localCharacter->GetOrigin() - argPacket->origin).Length() > INFLUENCE_RADIUS) {
return; return;
} }
@@ -779,10 +815,18 @@ void World::hCharacterMovement(CharacterPacket* const argPacket) {
//------------------------- //-------------------------
void World::hCreatureUpdate(CreaturePacket* const argPacket) { void World::hCreatureUpdate(CreaturePacket* const argPacket) {
std::cout << "hCreatureUpdate" << std::endl; //BUGFIX: Sometimes crash on exit
//TODO: (1) Authentication if (!localCharacter) {
return;
}
//check that this character exists //Cull creatures that are too far away
if ( (localCharacter->GetOrigin() - argPacket->origin).Length() > INFLUENCE_RADIUS) {
//ignore beyond 1000 units
return;
}
//check if this creature exists
std::map<int, BaseCreature>::iterator creatureIt = creatureMap.find(argPacket->creatureIndex); std::map<int, BaseCreature>::iterator creatureIt = creatureMap.find(argPacket->creatureIndex);
if (creatureIt != creatureMap.end()) { if (creatureIt != creatureMap.end()) {
//update the origin and motion, if there's a difference //update the origin and motion, if there's a difference
@@ -847,10 +891,12 @@ void World::hCreatureUnload(CreaturePacket* const argPacket) {
} }
void World::hQueryCreatureExists(CreaturePacket* const argPacket) { void World::hQueryCreatureExists(CreaturePacket* const argPacket) {
std::cout << "Creature Query" << std::endl; if (!localCharacter) {
return;
}
//ignore creatures in a different room (sub-optimal) //ignore creatures in a different room (sub-optimal)
if (argPacket->roomIndex != roomIndex) { if (argPacket->roomIndex != roomIndex || (localCharacter->GetOrigin() - argPacket->origin).Length() > INFLUENCE_RADIUS) {
return; return;
} }
@@ -881,6 +927,106 @@ void World::hCreatureMovement(CreaturePacket* const argPacket) {
creatureIt->second.SetMotion(argPacket->motion); creatureIt->second.SetMotion(argPacket->motion);
} }
//-------------------------
//barrier management
//-------------------------
void World::hBarrierUpdate(BarrierPacket* const argPacket) {
//BUGFIX: Sometimes crash on exit
if (!localCharacter) {
return;
}
//Cull barriers that are too far away
if ( (localCharacter->GetOrigin() - argPacket->origin).Length() > INFLUENCE_RADIUS) {
//ignore beyond 1000 units
return;
}
//check if this barrier exists
BaseBarrier* barrier = barrierMgr.Find(argPacket->barrierIndex);
if (!barrier) {
hBarrierCreate(argPacket);
return;
}
//update the origin and motion, if there's a difference
if (barrier->GetOrigin() != argPacket->origin) {
barrier->SetOrigin(argPacket->origin);
}
barrier->SetStatusArray(argPacket->status);
barrier->CorrectSprite();
}
void World::hBarrierCreate(BarrierPacket* const argPacket) {
//check for logic errors
//ignore barriers from other rooms
if (roomIndex != argPacket->roomIndex) {
//temporary error checking
std::ostringstream msg;
msg << "Barrier from the wrong room received: ";
msg << "barrierIndex: " << argPacket->barrierIndex << ", roomIndex: " << argPacket->roomIndex;
throw(std::runtime_error(msg.str()));
}
BaseBarrier* barrier = barrierMgr.Find(argPacket->barrierIndex);
if (barrier) {
std::ostringstream msg;
msg << "Double barrier creation event; ";
msg << "Index: " << argPacket->barrierIndex;
throw(std::runtime_error(msg.str()));
}
barrier = barrierMgr.Create(argPacket->barrierIndex);
//fill the barrier's info
barrier->SetBounds(argPacket->bounds);
barrier->SetOrigin(argPacket->origin);
barrier->SetStatusArray(argPacket->status);
barrier->CorrectSprite();
//debug
std::cout << "Barrier Create, total: " << barrierMgr.Size() << std::endl;
}
void World::hBarrierUnload(BarrierPacket* const argPacket) {
//ignore if this barrier doesn't exist
barrierMgr.Unload(argPacket->barrierIndex);
//debug
std::cout << "Barrier Unload, total: " << barrierMgr.Size() << std::endl;
}
void World::hQueryBarrierExists(BarrierPacket* const argPacket) {
if (!localCharacter) {
return;
}
//ignore barriers in a different room (sub-optimal)
if (argPacket->roomIndex != roomIndex || (localCharacter->GetOrigin() - argPacket->origin).Length() > INFLUENCE_RADIUS) {
return;
}
//implicitly create the element
BaseBarrier* barrier = barrierMgr.Find(argPacket->barrierIndex);
if (!barrier) {
barrier = barrierMgr.Create(argPacket->barrierIndex);
}
//fill the barrier's info
barrier->SetBounds(argPacket->bounds);
barrier->SetOrigin(argPacket->origin);
barrier->SetStatusArray(argPacket->status);
barrier->CorrectSprite();
//debug
std::cout << "Barrier Query, total: " << barrierMgr.Size() << std::endl;
}
//------------------------- //-------------------------
//chat //chat
//------------------------- //-------------------------
@@ -902,6 +1048,11 @@ void World::hTextWhisper(TextPacket* const argPacket) {
//------------------------- //-------------------------
void World::SendLocalCharacterMovement() { void World::SendLocalCharacterMovement() {
//BUGFIX: Sometimes crash on exit
if (!localCharacter) {
return;
}
CharacterPacket newPacket; CharacterPacket newPacket;
newPacket.type = SerialPacketType::CHARACTER_MOVEMENT; newPacket.type = SerialPacketType::CHARACTER_MOVEMENT;
+12 -9
View File
@@ -39,8 +39,11 @@
#include "frame_rate.hpp" #include "frame_rate.hpp"
//client //client
#include "barrier_manager.hpp"
#include "base_scene.hpp" #include "base_scene.hpp"
#include "base_barrier.hpp"
#include "base_creature.hpp" #include "base_creature.hpp"
#include "heartbeat_utility.hpp"
#include "local_character.hpp" #include "local_character.hpp"
#include "SDL2/SDL.h" #include "SDL2/SDL.h"
@@ -78,12 +81,6 @@ private:
//handle incoming traffic //handle incoming traffic
void HandlePacket(SerialPacket* const); void HandlePacket(SerialPacket* const);
//heartbeat system
void hPing(ServerPacket* const);
void hPong(ServerPacket* const);
void CheckHeartBeat();
//basic connections //basic connections
void SendLogoutRequest(); void SendLogoutRequest();
void SendDisconnectRequest(); void SendDisconnectRequest();
@@ -113,6 +110,12 @@ private:
void hQueryCreatureExists(CreaturePacket* const); void hQueryCreatureExists(CreaturePacket* const);
void hCreatureMovement(CreaturePacket* const); void hCreatureMovement(CreaturePacket* const);
//barrier management
void hBarrierUpdate(BarrierPacket* const);
void hBarrierCreate(BarrierPacket* const);
void hBarrierUnload(BarrierPacket* const);
void hQueryBarrierExists(BarrierPacket* const);
//chat //chat
//TODO: ui chat engine //TODO: ui chat engine
void hTextBroadcast(TextPacket* const); void hTextBroadcast(TextPacket* const);
@@ -151,15 +154,15 @@ private:
} camera; } camera;
//entities //entities
BarrierManager barrierMgr;
std::map<int, BaseCharacter> characterMap; std::map<int, BaseCharacter> characterMap;
std::map<int, BaseCreature> creatureMap; std::map<int, BaseCreature> creatureMap;
LocalCharacter* localCharacter = nullptr; LocalCharacter* localCharacter = nullptr;
//heartbeat //heartbeat
//TODO: (2) Heartbeat needs it's own utility HeartbeatUtility heartbeatUtility;
typedef std::chrono::steady_clock Clock; typedef std::chrono::steady_clock Clock;
Clock::time_point lastBeat = Clock::now(); Clock::time_point queryTime = Clock::now() - std::chrono::seconds(4); //back 4 seconds to trigger automatically
int attemptedBeats = 0;
//ugly references; I hate this //ugly references; I hate this
ConfigUtility& config = ConfigUtility::GetSingleton(); ConfigUtility& config = ConfigUtility::GetSingleton();
+28
View File
@@ -0,0 +1,28 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
//the bounds for the objects, mapped to the default sprites
constexpr int BARRIER_BOUNDS_X = 0;
constexpr int BARRIER_BOUNDS_Y = 0;
constexpr int BARRIER_BOUNDS_WIDTH = 96;
constexpr int BARRIER_BOUNDS_HEIGHT = 96;
+39
View File
@@ -0,0 +1,39 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include <cmath>
//the speeds that the characters move
constexpr double CREATURE_WALKING_SPEED = 1.0;
constexpr double CREATURE_WALKING_MOD = 1.0/sqrt(2.0);
constexpr double CREATURE_WALKING_NEGATIVE_MOD = 1.0 - CREATURE_WALKING_MOD;
//the bounds for the character objects, mapped to the default sprites
constexpr int CREATURE_BOUNDS_X = 0;
constexpr int CREATURE_BOUNDS_Y = 0;
constexpr int CREATURE_BOUNDS_WIDTH = 32;
constexpr int CREATURE_BOUNDS_HEIGHT = 32;
//the character's sprite format
constexpr int CREATURE_CELLS_X = 4;
constexpr int CREATURE_CELLS_Y = 4;
+24
View File
@@ -0,0 +1,24 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
constexpr int INFLUENCE_RADIUS = 1000;
+32
View File
@@ -0,0 +1,32 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
enum ItemType {
//basics
POTION = 101,
//weapons
SWORD = 201,
DAGGER = 202,
STAFF = 203
};
+20 -20
View File
@@ -21,6 +21,8 @@
*/ */
#include "button.hpp" #include "button.hpp"
#include "render_text_texture.hpp"
#include <stdexcept> #include <stdexcept>
void Button::DrawTo(SDL_Renderer* renderer) { void Button::DrawTo(SDL_Renderer* renderer) {
@@ -51,19 +53,9 @@ void Button::SetBackgroundTexture(SDL_Renderer* renderer, SDL_Texture* texture)
image.SetClipH(image.GetClipH() / 3); image.SetClipH(image.GetClipH() / 3);
} }
void Button::SetText(SDL_Renderer* renderer, TTF_Font* font, std::string s, SDL_Color color) { void Button::SetText(SDL_Renderer* renderer, TTF_Font* font, SDL_Color color, std::string s) {
//make the surface (from SDL_ttf)
SDL_Surface* surf = TTF_RenderText_Solid(font, s.c_str(), color);
if (!surf) {
throw(std::runtime_error("Failed to create a TTF surface"));
}
//convert to texture //convert to texture
SDL_Texture* text = SDL_CreateTextureFromSurface(renderer, surf); SDL_Texture* text = renderTextTexture(renderer, font, color, s);
SDL_FreeSurface(surf);
if (!text) {
throw(std::runtime_error("Failed to create a TTF texture"));
}
//get the dimensions & rects //get the dimensions & rects
int x, y, w, h; int x, y, w, h;
@@ -87,14 +79,6 @@ void Button::SetText(SDL_Renderer* renderer, TTF_Font* font, std::string s, SDL_
SDL_DestroyTexture(text); SDL_DestroyTexture(text);
} }
void Button::SetX(int x) {
posX = x;
}
void Button::SetY(int y) {
posY = y;
}
Button::State Button::MouseMotion(SDL_MouseMotionEvent const& event) { Button::State Button::MouseMotion(SDL_MouseMotionEvent const& event) {
//if out of bounds, exit //if out of bounds, exit
if (!CheckBounds(event.x, event.y)) { if (!CheckBounds(event.x, event.y)) {
@@ -156,6 +140,22 @@ Button::State Button::GetState() {
return state; return state;
} }
int Button::SetX(int i) {
return posX = i;
}
int Button::SetY(int i) {
return posY = i;
}
int Button::GetX() const {
return posX;
}
int Button::GetY() const {
return posY;
}
bool Button::CheckBounds(int x, int y) { bool Button::CheckBounds(int x, int y) {
//return if true (x, y) is within bounds, otherwise return false //return if true (x, y) is within bounds, otherwise return false
return !( return !(
+8 -9
View File
@@ -27,11 +27,6 @@
#include <string> #include <string>
constexpr SDL_Color COLOR_WHITE = {255, 255, 255, 255};
constexpr SDL_Color COLOR_RED = {255, 0, 0, 255};
constexpr SDL_Color COLOR_ORANGE = {255, 127, 0, 255};
constexpr SDL_Color COLOR_BLUE = {0, 0, 255, 255};
class Button { class Button {
public: public:
enum State { enum State {
@@ -46,9 +41,7 @@ public:
//setup //setup
void SetBackgroundTexture(SDL_Renderer*, SDL_Texture*); void SetBackgroundTexture(SDL_Renderer*, SDL_Texture*);
void SetText(SDL_Renderer*, TTF_Font*, std::string, SDL_Color); void SetText(SDL_Renderer*, TTF_Font*, SDL_Color, std::string);
void SetX(int x);
void SetY(int y);
//capture input //capture input
State MouseMotion(SDL_MouseMotionEvent const&); State MouseMotion(SDL_MouseMotionEvent const&);
@@ -59,10 +52,16 @@ public:
void SetState(State); //TODO: idle, busy or disabled void SetState(State); //TODO: idle, busy or disabled
State GetState(); State GetState();
//accessors & mutators
int SetX(int x);
int SetY(int y);
int GetX() const;
int GetY() const;
protected: protected:
bool CheckBounds(int x, int y); bool CheckBounds(int x, int y);
Image image; Image image;
int posX = 0, posY = 0;
State state = State::IDLE; State state = State::IDLE;
int posX = 0, posY = 0;
}; };
+145
View File
@@ -0,0 +1,145 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "image.hpp"
#include <list>
#include <map>
#include <string>
template<typename T = class Image>
class CompositeImage {
public:
CompositeImage() = default;
~CompositeImage() = default;
void Load(SDL_Renderer* const, std::string spriteDir, std::list<std::string> nameList);
void SetTextures(std::map<std::string, Image>& templateImages);
void Free();
void DrawTo(SDL_Renderer* const, Sint16 x, Sint16 y, double scaleX = 1.0, double scaleY = 1.0);
//accessors & mutators
T* Find(std::string name);
bool Enable(std::string name);
bool Disable(std::string name);
void EnableAll();
void DisableAll();
std::map<std::string, std::pair<bool, T>>* GetTemplateImages();
private:
std::map<std::string, std::pair<bool, T>> imageMap;
};
template<typename T>
void CompositeImage<T>::Load(SDL_Renderer* const renderer, std::string spriteDir, std::list<std::string> nameList) {
for (auto& it : nameList) {
imageMap[it].first = true;
imageMap[it].second.Load(renderer, spriteDir + it);
}
}
template<typename T>
void CompositeImage<T>::SetTextures(std::map<std::string, Image>& templateImages) {
for (auto& it : templateImages) {
imageMap[it.first].first = true;
imageMap[it.first].second.SetTexture(it.second.GetTexture());
}
}
template<typename T>
void CompositeImage<T>::Free() {
imageMap.clear();
}
template<typename T>
void CompositeImage<T>::DrawTo(SDL_Renderer* const dest, Sint16 x, Sint16 y, double scaleX, double scaleY) {
//draw all members, regardless of internal ordering
for (auto& it : imageMap) {
if (it.second.first) {
it.second.second.DrawTo(dest, x, y, scaleX, scaleY);
}
}
}
//-------------------------
//accessors & mutators
//-------------------------
template<typename T>
T* CompositeImage<T>::Find(std::string name) {
auto it = imageMap.find(name);
if (it == imageMap.end()) {
return nullptr;
}
else {
return &it->second.second;
}
}
template<typename T>
bool CompositeImage<T>::Enable(std::string name) {
auto it = imageMap.find(name);
if (it == imageMap.end()) {
return false;
}
else {
imageMap[name].first = true;
return true;
}
}
template<typename T>
bool CompositeImage<T>::Disable(std::string name) {
auto it = imageMap.find(name);
if (it == imageMap.end()) {
return false;
}
else {
imageMap[name].first = false;
return true;
}
}
template<typename T>
void CompositeImage<T>::EnableAll() {
for (auto& it : imageMap) {
it.second.first = true;
}
}
template<typename T>
void CompositeImage<T>::DisableAll() {
for (auto& it : imageMap) {
it.second.first = false;
}
}
template<typename T>
std::map<std::string, std::pair<bool, T>>* CompositeImage<T>::GetTemplateImages() {
return &imageMap;
}
+1 -1
View File
@@ -161,7 +161,7 @@ SDL_Texture* Image::SetTexture(SDL_Texture* ptr) {
clip.y = 0; clip.y = 0;
if (SDL_QueryTexture(texture, nullptr, nullptr, &clip.w, &clip.h)) { if (SDL_QueryTexture(texture, nullptr, nullptr, &clip.w, &clip.h)) {
std::ostringstream msg; std::ostringstream msg;
msg << "Failed to record metadata for a newly image image"; msg << "Failed to record metadata for a newly set image";
msg << "; " << SDL_GetError(); msg << "; " << SDL_GetError();
throw(std::runtime_error(msg.str())); throw(std::runtime_error(msg.str()));
} }
+1 -1
View File
@@ -1,5 +1,5 @@
#config #config
INCLUDES+=. INCLUDES+=. ../utilities
LIBS+= LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES)) CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
+46
View File
@@ -0,0 +1,46 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "render_text_texture.hpp"
#include <stdexcept>
SDL_Texture* renderTextTexture(SDL_Renderer* renderer, TTF_Font* font, SDL_Color color, std::string str) {
//make the surface (from SDL_ttf)
SDL_Surface* surface = TTF_RenderText_Solid(font, str.c_str(), color);
if (!surface) {
throw(std::runtime_error("Failed to create a TTF surface"));
}
//convert to texture
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
//cleanup
SDL_FreeSurface(surface);
//check
if (!texture) {
throw(std::runtime_error("Failed to create a TTF texture"));
}
//NOTE: free the texture yourself
return texture;
}
+29
View File
@@ -0,0 +1,29 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "SDL2/SDL.h"
#include "SDL2/SDL_ttf.h"
#include <string>
SDL_Texture* renderTextTexture(SDL_Renderer*, TTF_Font*, SDL_Color color, std::string);
+25 -6
View File
@@ -31,15 +31,18 @@ TextBox::~TextBox() {
// //
} }
void TextBox::DrawTo(SDL_Renderer* renderer, int posX, int posY, int pointSize) { void TextBox::DrawTo(SDL_Renderer* renderer) {
int renderY = posY;
for (std::list<TextLine>::iterator it = lineList.begin(); it != lineList.end(); it++) { for (std::list<TextLine>::iterator it = lineList.begin(); it != lineList.end(); it++) {
it->DrawTo(renderer, posX, posY); it->SetX(posX);
posY += pointSize; it->SetY(renderY);
it->DrawTo(renderer);
renderY += it->GetPointHeight();
} }
} }
void TextBox::PushLine(SDL_Renderer* renderer, TTF_Font* font, std::string str, SDL_Color color) { void TextBox::PushLine(SDL_Renderer* renderer, TTF_Font* font, SDL_Color color, std::string str) {
lineList.emplace_front(renderer, font, str, color); lineList.emplace_back(renderer, font, color, str, 0, 0);
} }
void TextBox::PopLine(int num) { void TextBox::PopLine(int num) {
@@ -47,10 +50,26 @@ void TextBox::PopLine(int num) {
num < lineList.size() ? num : lineList.size(); num < lineList.size() ? num : lineList.size();
for (int i = 0; i < num; ++i) { for (int i = 0; i < num; ++i) {
lineList.pop_back(); lineList.pop_front();
} }
} }
void TextBox::ClearLines() { void TextBox::ClearLines() {
lineList.clear(); lineList.clear();
} }
int TextBox::SetX(int i) {
return posX = i;
}
int TextBox::SetY(int i) {
return posY = i;
}
int TextBox::GetX() const {
return posX;
}
int TextBox::GetY() const {
return posY;
}
+8 -2
View File
@@ -34,12 +34,18 @@ public:
TextBox(); TextBox();
~TextBox(); ~TextBox();
void DrawTo(SDL_Renderer*, int posX, int posY, int pointSize); void DrawTo(SDL_Renderer*);
void PushLine(SDL_Renderer*, TTF_Font*, std::string, SDL_Color color); void PushLine(SDL_Renderer*, TTF_Font*, SDL_Color color, std::string);
void PopLine(int num = 1); void PopLine(int num = 1);
void ClearLines(); void ClearLines();
int SetX(int i);
int SetY(int i);
int GetX() const;
int GetY() const;
private: private:
std::list<TextLine> lineList; std::list<TextLine> lineList;
int posX = 0, posY = 0;
}; };
+109
View File
@@ -0,0 +1,109 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "text_field.hpp"
#include "render_text_texture.hpp"
TextField::TextField() {
//
}
TextField::~TextField() {
SDL_DestroyTexture(texture);
}
void TextField::DrawTo(SDL_Renderer* renderer) {
if (!texture) {
return;
}
SDL_Rect dclip = {posX, posY, 0, 0};
SDL_QueryTexture(texture, nullptr, nullptr, &dclip.w, &dclip.h);
SDL_RenderCopy(renderer, texture, nullptr, &dclip);
}
std::string TextField::PushText(SDL_Renderer* renderer, TTF_Font* font, SDL_Color color, std::string s) {
text += s;
return SetText(renderer, font, color, text);
}
std::string TextField::SetText(SDL_Renderer* renderer, TTF_Font* font, SDL_Color color, std::string s) {
text = s;
SDL_DestroyTexture(texture);
if (text.size()) {
texture = renderTextTexture(renderer, font, color, text);
}
else {
texture = nullptr;
}
return text;
}
std::string TextField::PopChars(SDL_Renderer* renderer, TTF_Font* font, SDL_Color color, int i) {
if (text.size() > 0) {
text.erase(text.size() - i);
}
return SetText(renderer, font, color, text);
}
std::string TextField::GetText() {
return text;
}
bool TextField::MouseButtonDown(SDL_MouseButtonEvent const& event) {
BoundingBox cursorBox = {event.x, event.y, 0, 0};
BoundingBox fieldBox = bounds;
fieldBox.x += posX;
fieldBox.y += posY;
return focus = fieldBox.CheckOverlap(cursorBox);
}
BoundingBox TextField::SetBounds(BoundingBox b) {
return bounds = b;
}
BoundingBox TextField::GetBounds() {
return bounds;
}
bool TextField::SetFocus(bool b) {
return focus = b;
}
bool TextField::GetFocus() {
return focus;
}
int TextField::SetX(int i) {
return posX = i;
}
int TextField::SetY(int i) {
return posY = i;
}
int TextField::GetX() const {
return posX;
}
int TextField::GetY() const {
return posY;
}
+65
View File
@@ -0,0 +1,65 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "bounding_box.hpp"
#include "SDL2/SDL.h"
#include "SDL2/SDL_ttf.h"
#include <string>
class TextField {
public:
TextField();
~TextField();
void DrawTo(SDL_Renderer*);
//input
std::string PushText(SDL_Renderer*, TTF_Font*, SDL_Color color, std::string);
std::string SetText(SDL_Renderer*, TTF_Font*, SDL_Color color, std::string);
std::string PopChars(SDL_Renderer*, TTF_Font*, SDL_Color color, int i);
std::string GetText();
bool MouseButtonDown(SDL_MouseButtonEvent const& event);
BoundingBox SetBounds(BoundingBox b);
BoundingBox GetBounds();
bool SetFocus(bool b);
bool GetFocus();
//accessors & mutators
int SetX(int i);
int SetY(int i);
int GetX() const;
int GetY() const;
private:
SDL_Texture* texture = nullptr;
std::string text;
BoundingBox bounds;
bool focus = false;
int posX = 0, posY = 0;
};
+33 -25
View File
@@ -21,50 +21,58 @@
*/ */
#include "text_line.hpp" #include "text_line.hpp"
#include "render_text_texture.hpp"
#include <stdexcept> #include <stdexcept>
SDL_Texture* renderTextTexture(SDL_Renderer* renderer, TTF_Font* font, std::string str, SDL_Color color) {
//make the surface (from SDL_ttf)
SDL_Surface* surface = TTF_RenderText_Solid(font, str.c_str(), color);
if (!surface) {
throw(std::runtime_error("Failed to create a TTF surface"));
}
//convert to texture
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
//cleanup
SDL_FreeSurface(surface);
//check
if (!texture) {
throw(std::runtime_error("Failed to create a TTF texture"));
}
//NOTE: free the texture yourself
return texture;
}
TextLine::TextLine() { TextLine::TextLine() {
// //
} }
TextLine::TextLine(SDL_Renderer* renderer, TTF_Font* font, SDL_Color color, std::string str, int x, int y) {
SetText(renderer, font, color, str);
posX = x;
posY = y;
}
TextLine::~TextLine() { TextLine::~TextLine() {
ClearText(); ClearText();
} }
void TextLine::DrawTo(SDL_Renderer* renderer, int posX, int posY) { void TextLine::DrawTo(SDL_Renderer* renderer) {
SDL_Rect dclip = {posX, posY, 0, 0}; SDL_Rect dclip = {posX, posY, 0, 0};
SDL_QueryTexture(texture, nullptr, nullptr, &dclip.w, &dclip.h); SDL_QueryTexture(texture, nullptr, nullptr, &dclip.w, &dclip.h);
SDL_RenderCopy(renderer, texture, nullptr, &dclip); SDL_RenderCopy(renderer, texture, nullptr, &dclip);
} }
void TextLine::SetText(SDL_Renderer* renderer, TTF_Font* font, std::string str, SDL_Color color) { void TextLine::SetText(SDL_Renderer* renderer, TTF_Font* font, SDL_Color color, std::string str) {
//just use the above global function //just use the above global function
SDL_DestroyTexture(texture); SDL_DestroyTexture(texture);
texture = renderTextTexture(renderer, font, str, color); texture = renderTextTexture(renderer, font, color, str);
pointHeight = TTF_FontHeight(font);
} }
void TextLine::ClearText() { void TextLine::ClearText() {
SDL_DestroyTexture(texture); SDL_DestroyTexture(texture);
pointHeight = 0;
}
int TextLine::SetX(int i) {
return posX = i;
}
int TextLine::SetY(int i) {
return posY = i;
}
int TextLine::GetX() const {
return posX;
}
int TextLine::GetY() const {
return posY;
}
int TextLine::GetPointHeight() {
return pointHeight;
} }
+14 -6
View File
@@ -26,20 +26,28 @@
#include <string> #include <string>
SDL_Texture* renderTextTexture(SDL_Renderer*, TTF_Font*, std::string, SDL_Color color);
class TextLine { class TextLine {
public: public:
TextLine(); TextLine();
TextLine(SDL_Renderer* r, TTF_Font* f, std::string s, SDL_Color c) TextLine(SDL_Renderer*, TTF_Font*, SDL_Color, std::string, int x, int y);
{ SetText(r, f, s, c); }
virtual ~TextLine(); virtual ~TextLine();
void DrawTo(SDL_Renderer*, int posX, int posY); void DrawTo(SDL_Renderer*);
void SetText(SDL_Renderer*, TTF_Font*, std::string, SDL_Color color); void SetText(SDL_Renderer*, TTF_Font*, SDL_Color, std::string);
void ClearText(); void ClearText();
//accessors & mutators
int SetX(int i);
int SetY(int i);
int GetX() const;
int GetY() const;
//utility
int GetPointHeight();
protected: protected:
SDL_Texture* texture = nullptr; SDL_Texture* texture = nullptr;
int posX = 0, posY = 0;
int pointHeight = 0; //internal use for TextBox
}; };
@@ -0,0 +1,72 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "barrier_packet.hpp"
#include "serial_utility.hpp"
void serializeBarrier(void* buffer, BarrierPacket* packet) {
serialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//identify the barrier
serialCopy(&buffer, &packet->barrierIndex, sizeof(int));
//bounds
serialCopy(&buffer, &packet->bounds.x, sizeof(int));
serialCopy(&buffer, &packet->bounds.y, sizeof(int));
serialCopy(&buffer, &packet->bounds.w, sizeof(int));
serialCopy(&buffer, &packet->bounds.h, sizeof(int));
//location
serialCopy(&buffer, &packet->roomIndex, sizeof(int));
serialCopy(&buffer, &packet->origin.x, sizeof(double));
serialCopy(&buffer, &packet->origin.y, sizeof(double));
serialCopy(&buffer, &packet->motion.x, sizeof(double));
serialCopy(&buffer, &packet->motion.y, sizeof(double));
//graphical data
serialCopy(&buffer, packet->status, sizeof(int) * 8);
}
void deserializeBarrier(void* buffer, BarrierPacket* packet) {
deserialCopy(&buffer, &packet->type, sizeof(SerialPacketType));
//identify the barrier
deserialCopy(&buffer, &packet->barrierIndex, sizeof(int));
//bounds
deserialCopy(&buffer, &packet->bounds.x, sizeof(int));
deserialCopy(&buffer, &packet->bounds.y, sizeof(int));
deserialCopy(&buffer, &packet->bounds.w, sizeof(int));
deserialCopy(&buffer, &packet->bounds.h, sizeof(int));
//location
deserialCopy(&buffer, &packet->roomIndex, sizeof(int));
deserialCopy(&buffer, &packet->origin.x, sizeof(double));
deserialCopy(&buffer, &packet->origin.y, sizeof(double));
deserialCopy(&buffer, &packet->motion.x, sizeof(double));
deserialCopy(&buffer, &packet->motion.y, sizeof(double));
//graphical data
deserialCopy(&buffer, packet->status, sizeof(int) * 8);
}
@@ -0,0 +1,44 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "serial_packet_base.hpp"
#include "bounding_box.hpp"
#include "vector2.hpp"
struct BarrierPacket : SerialPacketBase {
//identify the barrier
int barrierIndex;
BoundingBox bounds;
//location
int roomIndex;
Vector2 origin;
Vector2 motion;
//graphical data: 0 blank, 1 green, 2 red
int status[8];
};
void serializeBarrier(void* buffer, BarrierPacket* packet);
void deserializeBarrier(void* buffer, BarrierPacket* packet);
+9 -7
View File
@@ -22,6 +22,7 @@
#pragma once #pragma once
#include "serial_packet_base.hpp" #include "serial_packet_base.hpp"
#include "barrier_packet.hpp"
#include "character_packet.hpp" #include "character_packet.hpp"
#include "client_packet.hpp" #include "client_packet.hpp"
#include "creature_packet.hpp" #include "creature_packet.hpp"
@@ -33,15 +34,16 @@
typedef SerialPacketBase SerialPacket; typedef SerialPacketBase SerialPacket;
//DOCS: NETWORK_VERSION is used to discern compatible servers and clients //DOCS: NETWORK_VERSION is used to discern compatible servers and clients
constexpr int NETWORK_VERSION = 20160321; constexpr int NETWORK_VERSION = 20160825;
union MaxPacket { union MaxPacket {
CharacterPacket a; BarrierPacket a;
ClientPacket b; CharacterPacket b;
CreaturePacket c; ClientPacket c;
RegionPacket d; CreaturePacket d;
ServerPacket e; RegionPacket e;
TextPacket f; ServerPacket f;
TextPacket g;
}; };
constexpr int MAX_PACKET_SIZE = sizeof(MaxPacket); constexpr int MAX_PACKET_SIZE = sizeof(MaxPacket);
+23 -1
View File
@@ -165,9 +165,31 @@ enum class SerialPacketType {
FORMAT_END_TEXT = 699, FORMAT_END_TEXT = 699,
//-------------------------
//BarrierPacket
// barrier index,
// bounds,
// roomIndex, origin, motion
// status
//-------------------------
FORMAT_BARRIER = 700,
BARRIER_UPDATE = 701,
BARRIER_CREATE = 702,
BARRIER_UNLOAD = 703,
QUERY_BARRIER_EXISTS = 704,
BARRIER_ENTRY = 705,
BARRIER_EXIT = 706,
FORMAT_END_BARRIER = 799,
//------------------------- //-------------------------
//not used //not used
//------------------------- //-------------------------
LAST = 700 LAST = 800
}; };
+9
View File
@@ -22,6 +22,7 @@
#include "serial_utility.hpp" #include "serial_utility.hpp"
//packet types //packet types
#include "barrier_packet.hpp"
#include "character_packet.hpp" #include "character_packet.hpp"
#include "client_packet.hpp" #include "client_packet.hpp"
#include "creature_packet.hpp" #include "creature_packet.hpp"
@@ -72,6 +73,10 @@ void serializePacket(void* buffer, SerialPacketBase* packet) {
if (BOUNDS(packet->type, SerialPacketType::FORMAT_TEXT, SerialPacketType::FORMAT_END_TEXT)) { if (BOUNDS(packet->type, SerialPacketType::FORMAT_TEXT, SerialPacketType::FORMAT_END_TEXT)) {
serializeText(buffer, static_cast<TextPacket*>(packet)); serializeText(buffer, static_cast<TextPacket*>(packet));
} }
if (BOUNDS(packet->type, SerialPacketType::FORMAT_BARRIER, SerialPacketType::FORMAT_END_BARRIER)) {
serializeBarrier(buffer, static_cast<BarrierPacket*>(packet));
}
} }
void deserializePacket(void* buffer, SerialPacketBase* packet) { void deserializePacket(void* buffer, SerialPacketBase* packet) {
@@ -102,4 +107,8 @@ void deserializePacket(void* buffer, SerialPacketBase* packet) {
if (BOUNDS(type, SerialPacketType::FORMAT_TEXT, SerialPacketType::FORMAT_END_TEXT)) { if (BOUNDS(type, SerialPacketType::FORMAT_TEXT, SerialPacketType::FORMAT_END_TEXT)) {
deserializeText(buffer, static_cast<TextPacket*>(packet)); deserializeText(buffer, static_cast<TextPacket*>(packet));
} }
if (BOUNDS(type, SerialPacketType::FORMAT_BARRIER, SerialPacketType::FORMAT_END_BARRIER)) {
deserializeBarrier(buffer, static_cast<BarrierPacket*>(packet));
}
} }
+125
View File
@@ -0,0 +1,125 @@
/* Copyright: (c) Kayne Ruse 2015
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
//DOCS: this is a generic CSV reading tool
//DOCS: empty lines and comment lines begining with '#' are ignored
//DOCS: whitespace characters are valid field values
//DOCS: if the file is invalid, then the behavior is undefined
#include <array>
#include <cstring>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
//define the container types
template<int N>
using CSVElement = std::array<std::string, N>;
template<int N>
using CSVObject = std::vector<CSVElement<N>>;
//read a file into an object
template<int N>
CSVObject<N> readCSV(std::string fname, char delim = ',') {
//open the file
std::ifstream is(fname);
if (!is.is_open()) {
std::ostringstream msg;
msg << "Failed to open file: " << fname;
throw(std::runtime_error(msg.str()));
}
//build the scanf format
std::ostringstream format;
format << "%[^\0" << delim << "]";
//read and store each record (one per line)
CSVObject<N> object;
while(!is.eof()) {
//get a line
std::string tmpLine;
getline(is, tmpLine);
//skip blank and comment lines
if (tmpLine.size() == 0 || tmpLine[0] == '#') {
continue;
}
//read and store each field
CSVElement<N> record;
for (int i = 0; i < N; ++i) {
//get a field
char tmpField[256];
memset(tmpField, 0, 256);
sscanf(tmpLine.c_str(), format.str().c_str(), tmpField);
//prune the input
int len = std::min(strlen(tmpField)+1, tmpLine.size());
tmpLine = tmpLine.substr(len);
//store the field
record[i] = tmpField;
}
object.push_back(record);
}
//finally, close the file
is.close();
return object;
}
template<int N>
void writeCSV(std::string fname, CSVObject<N> const& object, char delim = ',') {
//open the file
std::ofstream os(fname);
if (!os.is_open()) {
std::ostringstream msg;
msg << "Failed to open file: " << fname;
throw(std::runtime_error(msg.str()));
}
//write each record, one at a time
for(auto& record : object) {
//write each field, one at a time
for (int i = 0; i < N; i++) {
os << record[i];
//print delimiter
if (i != N -1) {
os << delim;
}
}
os << std::endl;
}
//finish
os.close();
}
+5
View File
@@ -0,0 +1,5 @@
#Format (4 columns): "name", type, "sprite.png", stackable
"Sword",weapon,"sword.png",false
"Staff",weapon,"staff.png",false
"Dagger",weapon,"dagger.png",false
"Potion",consumable,"potion.png",true
Can't render this file because it contains an unexpected character in line 1 and column 22.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1009 B

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 316 B

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 738 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 763 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 270 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 305 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 423 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 422 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 301 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 299 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 385 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 412 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 402 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 431 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 429 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 407 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 400 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 656 B

+2 -2
View File
@@ -64,7 +64,7 @@ function doorUtility.CreateDoorPair(handle, roomOne, Xone, Yone, roomTwo, Xtwo,
networkAPI.PumpCharacterUpdate(entity) networkAPI.PumpCharacterUpdate(entity)
--disable the other trigger --disable the other trigger
local triggerTwo = triggerManagerAPI.GetTrigger(roomAPI.GetTriggerMgr(roomTwo), handle) local triggerTwo = triggerManagerAPI.FindTrigger(roomAPI.GetTriggerMgr(roomTwo), handle)
triggerAPI.PushExclusionEntity(triggerTwo, entity) triggerAPI.PushExclusionEntity(triggerTwo, entity)
end end
@@ -77,7 +77,7 @@ function doorUtility.CreateDoorPair(handle, roomOne, Xone, Yone, roomTwo, Xtwo,
networkAPI.PumpCharacterUpdate(entity) networkAPI.PumpCharacterUpdate(entity)
--disable the other trigger --disable the other trigger
local triggerOne = triggerManagerAPI.GetTrigger(roomAPI.GetTriggerMgr(roomOne), handle) local triggerOne = triggerManagerAPI.FindTrigger(roomAPI.GetTriggerMgr(roomOne), handle)
triggerAPI.PushExclusionEntity(triggerOne, entity) triggerAPI.PushExclusionEntity(triggerOne, entity)
end end
+77 -7
View File
@@ -26,6 +26,12 @@
print("Lua script check") print("Lua script check")
entityAPI = require("entity")
for k, v in pairs(entityAPI) do
print(k, v)
end
--requirements --requirements
roomManagerAPI = require("room_manager") roomManagerAPI = require("room_manager")
roomAPI = require("room") roomAPI = require("room")
@@ -37,6 +43,8 @@ doorUtility = require("door_utility")
creatureAPI = require("creature") creatureAPI = require("creature")
creatureManagerAPI = require("creature_manager") creatureManagerAPI = require("creature_manager")
barrierAPI = require("barrier")
barrierManagerAPI = require("barrier_manager")
--testing creature tags --testing creature tags
local function bunnySquare(creature) local function bunnySquare(creature)
@@ -54,19 +62,23 @@ local function bunnySquare(creature)
creatureAPI.SetMotion(creature, 0, 1) creatureAPI.SetMotion(creature, 0, 1)
end end
--is it time to change direction? --is it time to change direction?
if os.time() - tonumber(timestamp) > 3 then if os.time() - tonumber(timestamp) >= 4 then
-- print("changing directions")
if string.match("south", direction) then if string.match("south", direction) then
direction = "east"
creatureAPI.SetMotion(creature, 1, 0)
else
if string.match("east", direction) then
direction = "north" direction = "north"
creatureAPI.SetMotion(creature, 0, -1) creatureAPI.SetMotion(creature, 0, -1)
else else
if string.match("north", direction) then
direction = "west"
creatureAPI.SetMotion(creature, -1, 0)
else --south is a default
direction = "south" direction = "south"
creatureAPI.SetMotion(creature, 0, 1) creatureAPI.SetMotion(creature, 0, 1)
end end end end
timestamp = tostring(os.time()) timestamp = tostring(os.time())
ret = 1 ret = 1
end end
@@ -76,13 +88,56 @@ local function bunnySquare(creature)
return ret return ret
end end
local function barrierTick(barrier)
local timestamp = barrierAPI.GetTag(barrier, "timestamp")
--initialize the timestamp
if string.len(timestamp) == 0 then
timestamp = tostring(os.time())
barrierAPI.SetTag(barrier, "timestamp", timestamp)
end
--is it time to change the display?
if os.time() - tonumber(timestamp) < 1 then
return 0
else
timestamp = tostring(os.time())
barrierAPI.SetTag(barrier, "timestamp", timestamp)
end
--binary tick
for i = 1, 8 do
if barrierAPI.GetStatus(barrier, i) == 0 then
barrierAPI.SetStatus(barrier, i, 1)
return 1
else
barrierAPI.SetStatus(barrier, i, 0)
end
end
return 0
end
--test the room hooks --test the room hooks
roomManagerAPI.SetOnCreate(function(room, index) roomManagerAPI.SetOnCreate(function(room, index)
print("", "Creating room: ", roomAPI.GetName(room), index) print("", "Creating room: ", roomAPI.GetName(room), index)
creatureManagerAPI.Create(roomAPI.GetCreatureMgr(room), "anibunny.png", bunnySquare) --creatureManager with SetOnCreate, SetOnUnload & create & unload
creatureManagerAPI.SetOnCreate(roomAPI.GetCreatureMgr(room), function(creature, index)
--
end)
creatureManagerAPI.SetOnUnload(roomAPI.GetCreatureMgr(room), function(creature)
--
end)
--creatureManager with SetOnCreate, SetOnUnload & create & unload
barrierManagerAPI.SetOnCreate(roomAPI.GetBarrierMgr(room), function(barrier)
barrierAPI.SetScript(barrier, barrierTick)
end)
roomAPI.SetOnTick(room, function(room) roomAPI.SetOnTick(room, function(room)
ret = 0
--placeholders
roomAPI.ForEachCharacter(room, function(character) roomAPI.ForEachCharacter(room, function(character)
-- --
end) end)
@@ -90,6 +145,20 @@ roomManagerAPI.SetOnCreate(function(room, index)
roomAPI.ForEachCreature(room, function(creature) roomAPI.ForEachCreature(room, function(creature)
-- --
end) end)
roomAPI.ForEachBarrier(room, function(creature)
--
end)
--respawn a new rabbit when needed
if creatureManagerAPI.GetLoadedCount(roomAPI.GetCreatureMgr(room)) < 1 and
barrierManagerAPI.GetLoadedCount(roomAPI.GetBarrierMgr(room)) < 2
then
--make a new creature
creatureManagerAPI.Create(roomAPI.GetCreatureMgr(room), "anibunny.png", bunnySquare)
ret = 1
end
return ret
end) end)
end) end)
@@ -106,3 +175,4 @@ roomAPI.Initialize(underworld, mapSaver.Load, mapSaver.Save, mapMaker.DebugGrass
--call the monstrosity --call the monstrosity
doorUtility.CreateDoorPair("pair 1", overworld, -64, -64, underworld, 64, 64) doorUtility.CreateDoorPair("pair 1", overworld, -64, -64, underworld, 64, 64)
+51 -87
View File
@@ -20,13 +20,23 @@
* distribution. * distribution.
*/ */
-------------------------
--defines
-------------------------
PRAGMA foreign_keys = ON;
-------------------------
--table definitions
-------------------------
CREATE TABLE IF NOT EXISTS UserAccounts ( CREATE TABLE IF NOT EXISTS UserAccounts (
uid INTEGER PRIMARY KEY AUTOINCREMENT, uid INTEGER PRIMARY KEY AUTOINCREMENT,
username varchar(100) UNIQUE, --TODO: (3) Swap username for email address username varchar(100) UNIQUE, --TODO: (3) Swap username for email address
--server-client security --server-client security
-- passhash varchar(100), passhash varchar(100),
-- passsalt varchar(100), passsalt varchar(100),
--server controls --server controls
blacklisted BIT DEFAULT 0, blacklisted BIT DEFAULT 0,
@@ -39,8 +49,8 @@ CREATE TABLE IF NOT EXISTS LiveCharacters (
uid INTEGER PRIMARY KEY AUTOINCREMENT, uid INTEGER PRIMARY KEY AUTOINCREMENT,
--metadata --metadata
owner INTEGER REFERENCES Accounts(uid), owner INTEGER REFERENCES UserAccounts(uid),
handle varchar(100) UNIQUE, handle varchar(100),
avatar varchar(100), avatar varchar(100),
birth timestamp NOT NULL DEFAULT (datetime()), birth timestamp NOT NULL DEFAULT (datetime()),
@@ -48,59 +58,8 @@ CREATE TABLE IF NOT EXISTS LiveCharacters (
roomIndex INTEGER DEFAULT 0, roomIndex INTEGER DEFAULT 0,
originX INTEGER DEFAULT 0, originX INTEGER DEFAULT 0,
originY INTEGER DEFAULT 0, originY INTEGER DEFAULT 0,
boundsX INTEGER DEFAULT 0,
boundsY INTEGER DEFAULT 0,
boundsW INTEGER DEFAULT 0,
boundsH INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS DeadCharacters ( --combat stats
uid INTEGER PRIMARY KEY,
--metadata
owner INTEGER REFERENCES Accounts(uid),
handle varchar(100),
avatar varchar(100),
birth timestamp NOT NULL
);
CREATE TABLE IF NOT EXISTS LiveMonsters (
uid INTEGER PRIMARY KEY AUTOINCREMENT,
--metadata
handle varchar(100) UNIQUE,
avatar varchar(100),
--actions
-- script
--physically exists in the world
roomIndex INTEGER DEFAULT 0,
originX INTEGER DEFAULT 0,
originY INTEGER DEFAULT 0,
boundsX INTEGER DEFAULT 0,
boundsY INTEGER DEFAULT 0,
boundsW INTEGER DEFAULT 0,
boundsH INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS DeadMonsters (
uid INTEGER PRIMARY KEY,
--metadata
handle varchar(100) UNIQUE,
avatar varchar(100)
);
-------------------------
--Utility tables
-------------------------
CREATE TABLE IF NOT EXISTS StatisticSets (
--metadata
uid INTEGER PRIMARY KEY AUTOINCREMENT,
--general use statistics
level INTEGER DEFAULT 0, level INTEGER DEFAULT 0,
exp INTEGER DEFAULT 0, exp INTEGER DEFAULT 0,
maxHP INTEGER DEFAULT 0, maxHP INTEGER DEFAULT 0,
@@ -111,48 +70,53 @@ CREATE TABLE IF NOT EXISTS StatisticSets (
defence INTEGER DEFAULT 0, defence INTEGER DEFAULT 0,
intelligence INTEGER DEFAULT 0, intelligence INTEGER DEFAULT 0,
resistance INTEGER DEFAULT 0, resistance INTEGER DEFAULT 0,
accuracy INTEGER DEFAULT 0,
evasion INTEGER DEFAULT 0,
speed INTEGER DEFAULT 0, speed INTEGER DEFAULT 0,
accuracy REAL DEFAULT 0.0, luck INTEGER DEFAULT 0
evasion REAL DEFAULT 0.0,
luck REAL DEFAULT 0.0
); );
CREATE TABLE IF NOT EXISTS InWorldItems ( CREATE TABLE IF NOT EXISTS DeadCharacters (
uid INTEGER PRIMARY KEY,
--metadata --metadata
uid INTEGER PRIMARY KEY AUTOINCREMENT, owner INTEGER REFERENCES UserAccounts(uid),
itemType INTEGER, handle varchar(100),
avatar varchar(100),
birth timestamp NOT NULL,
death timestamp NOT NULL DEFAULT (datetime()),
--position in the world --combat stats
roomIndex INTEGER DEFAULT 0, level INTEGER DEFAULT 0,
originX INTEGER DEFAULT 0, exp INTEGER DEFAULT 0,
originY INTEGER DEFAULT 0, maxHP INTEGER DEFAULT 0,
maxMP INTEGER DEFAULT 0,
--unique information attack INTEGER DEFAULT 0,
stackSize INTEGER DEFAULT 0, defence INTEGER DEFAULT 0,
durability INTEGER DEFAULT 0, intelligence INTEGER DEFAULT 0,
stats INTEGER REFERENCES StatisticSets(uid) resistance INTEGER DEFAULT 0,
accuracy INTEGER DEFAULT 0,
evasion INTEGER DEFAULT 0,
speed INTEGER DEFAULT 0,
luck INTEGER DEFAULT 0
); );
-------------------------
--global tables
-------------------------
CREATE TABLE IF NOT EXISTS InventoryItems ( CREATE TABLE IF NOT EXISTS InventoryItems (
--metadata --metadata
uid INTEGER PRIMARY KEY AUTOINCREMENT, uid INTEGER PRIMARY KEY AUTOINCREMENT,
owner INTEGER REFERENCES Characters(uid), name varchar(100) UNIQUE,
itemType INTEGER, type varchar(100), --tmp type
--unique information --unique information
stackSize INTEGER DEFAULT 0, durability INTEGER DEFAULT 0
durability INTEGER DEFAULT 0,
stats INTEGER REFERENCES StatisticSets(uid)
); );
CREATE TABLE IF NOT EXISTS WornEquipment ( -------------------------
--metadata --member tables
uid INTEGER PRIMARY KEY AUTOINCREMENT, -------------------------
owner INTEGER REFERENCES Characters(uid),
itemType INTEGER,
--unique information --TODO
durability INTEGER DEFAULT 0,
stats INTEGER REFERENCES StatisticSets(uid)
--attached script?
);
+23
View File
@@ -0,0 +1,23 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "inventory.hpp"
+35
View File
@@ -0,0 +1,35 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "item_data.hpp"
#include <list>
class Inventory {
public:
Inventory() = default;
~Inventory() = default;
private:
std::list<ItemData> itemList;
};
+23
View File
@@ -0,0 +1,23 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "inventory_manager.hpp"
+33
View File
@@ -0,0 +1,33 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "inventory.hpp"
class InventoryManager {
public:
InventoryManager() = default;
~InventoryManager() = default;
private:
//
};
+38
View File
@@ -0,0 +1,38 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "item_data.hpp"
ItemType ItemData::SetItemType(ItemType t) {
return type = t;
}
ItemType ItemData::GetItemType() {
return type;
}
int ItemData::SetQuantity(int i) {
return quantity = i;
}
int ItemData::GetQuantity() {
return quantity;
}
+41
View File
@@ -0,0 +1,41 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "item_type.hpp"
class ItemData {
public:
ItemData() = default;
~ItemData() = default;
//accessors and mutators
ItemType SetItemType(ItemType);
ItemType GetItemType();
int SetQuantity(int);
int GetQuantity();
private:
ItemType type;
int quantity = 1;
};
+32
View File
@@ -0,0 +1,32 @@
#config
INCLUDES+=. ../../common/gameplay
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=..
OUT=$(addprefix $(OUTDIR)/,server.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
+1 -1
View File
@@ -234,7 +234,7 @@ void AccountManager::UnloadIf(std::function<bool(std::pair<const int, AccountDat
//Define the accessors and mutators //Define the accessors and mutators
//------------------------- //-------------------------
AccountData* AccountManager::Get(int uid) { AccountData* AccountManager::Find(int uid) {
std::map<int, AccountData>::iterator it = elementMap.find(uid); std::map<int, AccountData>::iterator it = elementMap.find(uid);
if (it == elementMap.end()) { if (it == elementMap.end()) {
+1 -1
View File
@@ -42,7 +42,7 @@ public:
void UnloadIf(std::function<bool(std::pair<const int, AccountData const&>)> fn); void UnloadIf(std::function<bool(std::pair<const int, AccountData const&>)> fn);
//accessors and mutators //accessors and mutators
AccountData* Get(int uid); AccountData* Find(int uid);
int GetLoadedCount(); int GetLoadedCount();
int GetTotalCount(); int GetTotalCount();
std::map<int, AccountData>* GetContainer(); std::map<int, AccountData>* GetContainer();
+118
View File
@@ -0,0 +1,118 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "barrier_api.hpp"
#include "barrier_data.hpp"
#include "entity_api.hpp"
static int setScript(lua_State* L) {
BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
luaL_unref(L, LUA_REGISTRYINDEX, barrier->GetScriptReference());
barrier->SetScriptReference(luaL_ref(L, LUA_REGISTRYINDEX));
return 0;
}
static int getScript(lua_State* L) {
BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
lua_pushinteger(L, barrier->GetScriptReference());
lua_gettable(L, LUA_REGISTRYINDEX);
return 1;
}
static int setTag(lua_State* L) {
BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
barrier->SetTag(lua_tostring(L, 2), lua_tostring(L, 3));
return 0;
}
static int getTag(lua_State* L) {
BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
lua_pushstring(L, barrier->GetTag(lua_tostring(L, 2)).c_str());
return 1;
}
/*
static int setBattleIndex(lua_State* L) {
BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
barrier->SetBattleIndex(lua_tointeger(L, 2));
return 0;
}
*/
static int getBattleIndex(lua_State* L) {
BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
lua_pushinteger(L, barrier->GetBattleIndex());
return 1;
}
static int setStatus(lua_State* L) {
BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
barrier->SetStatus(lua_tointeger(L, 2) - 1, lua_tointeger(L, 3));
return 0;
}
static int getStatus(lua_State* L) {
BarrierData* barrier = static_cast<BarrierData*>(lua_touserdata(L, 1));
lua_pushinteger(L, barrier->GetStatus(lua_tointeger(L, 2) - 1));
return 1;
}
static const luaL_Reg barrierLib[] = {
{"SetScript", setScript},
{"GetScript", getScript},
{"SetTag", setTag},
{"GetTag", getTag},
// {"SetBattleIndex", setBattleIndex},
{"GetBattleIndex", getBattleIndex},
{"SetStatus", setStatus},
{"GetStatus", getStatus},
{nullptr, nullptr}
};
LUAMOD_API int openBarrierAPI(lua_State* L) {
//the local table
luaL_newlib(L, barrierLib);
//get the parent table
luaL_requiref(L, TORTUGA_ENTITY_API, openEntityAPI, false);
//merge the parent table into the local table
lua_pushnil(L); //first key
while(lua_next(L, -2)) {
//copy the key-value pair
lua_pushvalue(L, -2);
lua_pushvalue(L, -2);
//push the copy to the local table
lua_settable(L, -6);
//pop the original value before continuing
lua_pop(L, 1);
}
//remove the parent table, leaving the expanded local table
lua_pop(L, 1);
return 1;
}
+27
View File
@@ -0,0 +1,27 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "lua.hpp"
#define TORTUGA_BARRIER_API "barrier"
LUAMOD_API int openBarrierAPI(lua_State* L);
+112
View File
@@ -0,0 +1,112 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "barrier_data.hpp"
#include <cstring>
#include <sstream>
#include <stdexcept>
BarrierData::BarrierData(int i):
Entity::Entity("barrier")
{
battleIndex = i;
memset(status, 0, sizeof(int) * 8);
SetBounds({
BARRIER_BOUNDS_X,
BARRIER_BOUNDS_Y,
BARRIER_BOUNDS_WIDTH,
BARRIER_BOUNDS_HEIGHT
});
}
BarrierData::~BarrierData() {
//
}
int BarrierData::Update(lua_State* L) {
int ret = 0;
//NOTE: this is here mostly for the "barrier tick" effect
if (scriptRef != LUA_NOREF) {
//Call the script reference
lua_pushinteger(L, scriptRef);
lua_gettable(L, LUA_REGISTRYINDEX);
lua_pushlightuserdata(L, reinterpret_cast<void*>(this));
//check for errors
if(lua_pcall(L, 1, 1, 0) != LUA_OK) {
std::ostringstream msg;
msg << "Error running barrier script: " << lua_tostring(L, -1);
lua_pop(L, 1);
throw(std::runtime_error(msg.str()));
}
ret += lua_tonumber(L, -1);
}
Entity::Update();
return ret;
}
int BarrierData::SetScriptReference(int i) {
return scriptRef = i;
}
int BarrierData::GetScriptReference() {
return scriptRef;
}
std::string BarrierData::SetTag(std::string key, std::string value) {
return tags[key] = value;
}
std::string BarrierData::GetTag(std::string key) {
return tags[key];
}
int BarrierData::SetBattleIndex(int i) {
return battleIndex = i;
}
int BarrierData::GetBattleIndex() const {
return battleIndex;
}
int BarrierData::SetStatus(int k, int v) {
if (k < 0 || k >= 8) {
throw(std::runtime_error("Failed to set status"));
}
return status[k] = v;
}
int BarrierData::GetStatus(int k) {
if (k < 0 || k >= 8) {
throw(std::runtime_error("Failed to get status"));
}
return status[k];
}
int* BarrierData::GetStatusArray() {
return status;
}
+61
View File
@@ -0,0 +1,61 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "barrier_defines.hpp"
#include "entity.hpp"
#include "lua.hpp"
#include <map>
#include <string>
class BarrierData: public Entity {
public:
BarrierData(int battleIndex);
~BarrierData();
int Update(lua_State*);
int SetScriptReference(int);
int GetScriptReference();
//NOTE: Why does this have tags? Are the tags used?
std::string SetTag(std::string key, std::string value);
std::string GetTag(std::string key);
int SetBattleIndex(int i);
int GetBattleIndex() const;
int SetStatus(int k, int v);
int GetStatus(int k);
int* GetStatusArray();
private:
int scriptRef = LUA_NOREF;
std::map<std::string, std::string> tags;
int battleIndex;
int status[8];
};
+130
View File
@@ -0,0 +1,130 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "barrier_manager.hpp"
#include "lua_utilities.hpp"
BarrierManager::BarrierManager() {
//EMPTY
}
BarrierManager::~BarrierManager() {
UnloadAll();
}
//arg: a list of barriers to be updated in the clients
void BarrierManager::Update(std::list<std::pair<const int, BarrierData*>>* barrierList, bool updateAll) {
int ret;
for (auto& it : elementMap) {
ret = it.second.Update(lua);
if (ret || updateAll) {
barrierList->push_back(std::pair<const int, BarrierData*>(it.first, &it.second));
}
}
}
int BarrierManager::Create(int instanceIndex) {
//implicitly create the new object
elementMap.emplace( std::pair<int, BarrierData>(counter, BarrierData(instanceIndex)) );
runHook(lua, createRef, &elementMap.find(counter)->second, counter);
//TODO: do various things like saving to the database
return counter++;
}
//TODO: (1) combat load, save
void BarrierManager::Unload(int uid) {
runHook(lua, unloadRef, &elementMap.find(uid)->second, uid);
elementMap.erase(uid);
}
void BarrierManager::UnloadAll() {
for (std::map<int, BarrierData>::iterator it = elementMap.begin(); it != elementMap.end(); it++) {
runHook(lua, unloadRef, &it->second, it->first);
}
elementMap.clear();
}
void BarrierManager::UnloadIf(std::function<bool(std::pair<const int, BarrierData const&>)> fn) {
std::map<int, BarrierData>::iterator it = elementMap.begin();
while (it != elementMap.end()) {
if (fn(*it)) {
runHook(lua, unloadRef, &it->second, it->first);
it = elementMap.erase(it);
}
else {
++it;
}
}
}
BarrierData* BarrierManager::Find(int uid) {
std::map<int, BarrierData>::iterator it = elementMap.find(uid);
if (it == elementMap.end()) {
return nullptr;
}
return &it->second;
}
int BarrierManager::GetLoadedCount() {
return elementMap.size();
}
std::map<int, BarrierData>* BarrierManager::GetContainer() {
return &elementMap;
}
lua_State* BarrierManager::SetLuaState(lua_State* L) {
return lua = L;
}
lua_State* BarrierManager::GetLuaState() {
return lua;
}
sqlite3* BarrierManager::SetDatabase(sqlite3* db) {
return database = db;
}
sqlite3* BarrierManager::GetDatabase() {
return database;
}
int BarrierManager::SetCreateReference(int i) {
return createRef = i;
}
int BarrierManager::SetUnloadReference(int i) {
return unloadRef = i;
}
int BarrierManager::GetCreateReference() {
return createRef;
}
int BarrierManager::GetUnloadReference() {
return unloadRef;
}
+73
View File
@@ -0,0 +1,73 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "barrier_data.hpp"
#include "lua.hpp"
#include "sqlite3.h"
#include <algorithm>
#include <functional>
#include <list>
#include <map>
class BarrierManager {
public:
BarrierManager();
~BarrierManager();
//common public methods
void Update(std::list<std::pair<const int, BarrierData*>>* barrierList, bool updateAll);
int Create(int instanceIndex);
void Unload(int uid);
void UnloadAll();
void UnloadIf(std::function<bool(std::pair<const int, BarrierData const&>)> fn);
//accessors & mutators
BarrierData* Find(int uid);
int GetLoadedCount();
std::map<int, BarrierData>* GetContainer();
//hooks
lua_State* SetLuaState(lua_State* L);
lua_State* GetLuaState();
sqlite3* SetDatabase(sqlite3* db);
sqlite3* GetDatabase();
int SetCreateReference(int i);
int SetUnloadReference(int i);
int GetCreateReference();
int GetUnloadReference();
private:
//members
std::map<int, BarrierData> elementMap;
int counter = 0;
lua_State* lua = nullptr;
sqlite3* database = nullptr;
int createRef = LUA_NOREF;
int unloadRef = LUA_NOREF;
};
+124
View File
@@ -0,0 +1,124 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "barrier_manager_api.hpp"
#include "barrier_manager.hpp"
//args: mgr, avatar, script
static int create(lua_State* L) {
//register the function at the top of the stack
lua_pushinteger(L, luaL_ref(L, LUA_REGISTRYINDEX));
//create the actual barrier
BarrierManager* mgr = static_cast<BarrierManager* const>(lua_touserdata(L, 1));
int index = mgr->Create(-1);
BarrierData* barrier = mgr->Find(index);
lua_pushlightuserdata(L, static_cast<void*>(barrier));
lua_pushinteger(L, index);
return 2;
}
//TOOD: overload this to take the userdata as a parameter
static int unload(lua_State* L) {
BarrierManager* mgr = static_cast<BarrierManager* const>(lua_touserdata(L, 1));
mgr->Unload(lua_tointeger(L, 2));
return 0;
}
static int unloadAll(lua_State* L) {
BarrierManager* mgr = static_cast<BarrierManager* const>(lua_touserdata(L, 1));
mgr->UnloadAll();
return 0;
}
static int unloadIf(lua_State* L) {
BarrierManager* mgr = static_cast<BarrierManager* const>(lua_touserdata(L, 1));
//list of stuff to unload (don't invalidate iterators)
std::list<int> unloadList;
//unloadIf
for (auto it : *mgr->GetContainer()) {
//copy the function at the top
lua_pushvalue(L, -1);
//index & object as function parameters
lua_pushinteger(L, it.first);
lua_pushlightuserdata(L, &it.second);
//call
lua_pcall(L, 2, 1, 0);
//unload-ish
if (lua_toboolean(L, -1)) {
unloadList.push_back(it.first);
}
}
//actually unload
for (auto& it : unloadList) {
mgr->Unload(it);
}
return 0;
}
static int find(lua_State* L) {
BarrierManager* mgr = static_cast<BarrierManager* const>(lua_touserdata(L, 1));
BarrierData* barrier = mgr->Find(lua_tointeger(L, 2));
lua_pushlightuserdata(L, static_cast<void*>(barrier));
return 1;
}
static int getLoadedCount(lua_State* L) {
BarrierManager* mgr = static_cast<BarrierManager* const>(lua_touserdata(L, 1));
lua_pushinteger(L, mgr->GetLoadedCount());
return 1;
}
static int setOnCreate(lua_State* L) {
BarrierManager* mgr = static_cast<BarrierManager*>(lua_touserdata(L, 1));
mgr->SetCreateReference(luaL_ref(L, LUA_REGISTRYINDEX));
return 0;
}
static int setOnUnload(lua_State* L) {
BarrierManager* mgr = static_cast<BarrierManager*>(lua_touserdata(L, 1));
mgr->SetUnloadReference(luaL_ref(L, LUA_REGISTRYINDEX));
return 0;
}
static const luaL_Reg barrierManagerLib[] = {
{"Create", create},
{"Unload", unload},
{"UnloadAll", unloadAll},
{"UnloadIf", unloadIf},
{"Find", find},
{"GetLoadedCount", getLoadedCount},
{"SetOnCreate", setOnCreate},
{"SetOnUnload", setOnUnload},
{nullptr, nullptr}
};
LUAMOD_API int openBarrierManagerAPI(lua_State* L) {
luaL_newlib(L, barrierManagerLib);
return 1;
}
+27
View File
@@ -0,0 +1,27 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "lua.hpp"
#define TORTUGA_BARRIER_MANAGER_API "barrier_manager"
LUAMOD_API int openBarrierManagerAPI(lua_State* L);
+32
View File
@@ -0,0 +1,32 @@
#config
INCLUDES+=. .. ../characters ../creatures ../entities ../inventory ../../common/gameplay ../../common/utilities
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=..
OUT=$(addprefix $(OUTDIR)/,server.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
+75
View File
@@ -0,0 +1,75 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "battle_data.hpp"
#include <algorithm>
BattleData::BattleData() {
for (int i = 0; i < BATTLE_SIZE; i++) {
characterArray[i] = nullptr;
creatureArray[i] = nullptr;
}
}
BattleData::~BattleData() {
for (int i = 0; i < BATTLE_SIZE; i++) {
if (characterArray[i] != nullptr || creatureArray[i] != nullptr) {
//breaking a cardinal sin
throw(std::runtime_error("BattleData not empty on destruction"));
}
}
}
void BattleData::Update() {
//TODO: (0) EMPTY
}
//accessors and mutators
int BattleData::PushCharacter(CharacterData* const characterData) {
//push the character into the battle object
for (int i = 0; i < BATTLE_SIZE; i++) {
if (characterArray[i] == nullptr) {
characterArray[i] = characterData;
return 1;
}
}
return 0;
}
int BattleData::PopCharacter(CharacterData const * const characterData) {
//pop the character from the battle object
for (int i = 0; i < BATTLE_SIZE; i++) {
if (characterArray[i] == characterData) {
characterArray[i] = nullptr;
return 1;
}
}
return 0;
}
int BattleData::PushCreature(CreatureData* const creatureData) {
//TODO: (0) EMPTY
}
int BattleData::PopCreature(CreatureData const * const creatureData) {
//TODO: (0) EMPTY
}
+48
View File
@@ -0,0 +1,48 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "character_data.hpp"
#include "creature_data.hpp"
#include <functional>
class BattleData {
public:
constexpr static int BATTLE_SIZE = 8;
BattleData();
~BattleData();
void Update();
//accessors and mutators
int PushCharacter(CharacterData* const characterData);
int PopCharacter(CharacterData const * const characterData);
int PushCreature(CreatureData* const creatureData);
int PopCreature(CreatureData const * const creatureData);
private:
std::array<CharacterData*, BATTLE_SIZE> characterArray;
std::array<CreatureData*, BATTLE_SIZE> creatureArray;
};
+101
View File
@@ -0,0 +1,101 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#include "battle_manager.hpp"
BattleManager::BattleManager() {
//EMPTY
}
BattleManager::~BattleManager() {
UnloadAll();
}
//arg: a list of combats to be updated in the clients
void BattleManager::Update() {
for (auto& it : elementMap) {
it.second.Update();
}
}
int BattleManager::Create() {
//implicitly create the new object
elementMap.emplace( std::pair<int, BattleData>(counter, BattleData()) );
//TODO: do various things like saving to the database
return counter++;
}
//TODO: (1) combat load, save
void BattleManager::Unload(int uid) {
elementMap.erase(uid);
}
void BattleManager::UnloadAll() {
elementMap.clear();
}
void BattleManager::UnloadIf(std::function<bool(std::pair<const int, BattleData const&>)> fn) {
std::map<int, BattleData>::iterator it = elementMap.begin();
while (it != elementMap.end()) {
if (fn(*it)) {
it = elementMap.erase(it);
}
else {
++it;
}
}
}
BattleData* BattleManager::Find(int uid) {
std::map<int, BattleData>::iterator it = elementMap.find(uid);
if (it == elementMap.end()) {
return nullptr;
}
return &it->second;
}
int BattleManager::GetLoadedCount() {
return elementMap.size();
}
std::map<int, BattleData>* BattleManager::GetContainer() {
return &elementMap;
}
lua_State* BattleManager::SetLuaState(lua_State* L) {
return lua = L;
}
lua_State* BattleManager::GetLuaState() {
return lua;
}
sqlite3* BattleManager::SetDatabase(sqlite3* db) {
return database = db;
}
sqlite3* BattleManager::GetDatabase() {
return database;
}
+63
View File
@@ -0,0 +1,63 @@
/* Copyright: (c) Kayne Ruse 2013-2016
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
#pragma once
#include "battle_data.hpp"
#include "lua.hpp"
#include "sqlite3.h"
#include <algorithm>
#include <map>
class BattleManager {
public:
BattleManager();
~BattleManager();
//common public methods
void Update();
int Create();
void Unload(int uid);
void UnloadAll();
void UnloadIf(std::function<bool(std::pair<const int, BattleData const&>)> fn);
//accessors & mutators
BattleData* Find(int uid);
int GetLoadedCount();
std::map<int, BattleData>* GetContainer();
//hooks
lua_State* SetLuaState(lua_State* L);
lua_State* GetLuaState();
sqlite3* SetDatabase(sqlite3* db);
sqlite3* GetDatabase();
private:
//members
std::map<int, BattleData> elementMap;
int counter = 0;
lua_State* lua = nullptr;
sqlite3* database = nullptr;
};
+32
View File
@@ -0,0 +1,32 @@
#config
INCLUDES+=. .. ../characters ../creatures ../entities ../inventory ../../common/gameplay ../../common/utilities
LIBS+=
CXXFLAGS+=-std=c++11 $(addprefix -I,$(INCLUDES))
#source
CXXSRC=$(wildcard *.cpp)
#objects
OBJDIR=obj
OBJ+=$(addprefix $(OBJDIR)/,$(CXXSRC:.cpp=.o))
#output
OUTDIR=..
OUT=$(addprefix $(OUTDIR)/,server.a)
#targets
all: $(OBJ) $(OUT)
ar -crs $(OUT) $(OBJ)
$(OBJ): | $(OBJDIR)
$(OUT): | $(OUTDIR)
$(OBJDIR):
mkdir $(OBJDIR)
$(OUTDIR):
mkdir $(OUTDIR)
$(OBJDIR)/%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $<
+32 -33
View File
@@ -28,53 +28,51 @@
#include "server_utilities.hpp" #include "server_utilities.hpp"
#include <stdexcept> #include <stdexcept>
#include <iostream>
static int setRoom(lua_State* L) { static int setRoom(lua_State* L) {
//reverse engineer the character index //variables
int characterIndex = -1;
CharacterData* character = static_cast<CharacterData*>(lua_touserdata(L, 1)); CharacterData* character = static_cast<CharacterData*>(lua_touserdata(L, 1));
CharacterManager& characterMgr = CharacterManager::GetSingleton(); CharacterManager& characterMgr = CharacterManager::GetSingleton();
for (auto& it : *characterMgr.GetContainer()) {
if (character == &it.second) {
characterIndex = it.first;
break;
}
}
//error checking //error checking
if (characterIndex == -1) { if (characterMgr.Find(character->GetIndex()) != character) {
throw(std::runtime_error("Lua Error: Failed to find character index by reference")); throw(std::runtime_error("Lua Error: Failed to verify character index by reference"));
} }
//get the room index, depending on the parameter type //get the room index, depending on the parameter type
int roomIndex = -1; int roomIndex = -1;
RoomManager& roomMgr = RoomManager::GetSingleton();
switch(lua_type(L, 2)) { switch(lua_type(L, 2)) {
case LUA_TNUMBER: case LUA_TNUMBER:
//simple integer
roomIndex = lua_tointeger(L, 2); roomIndex = lua_tointeger(L, 2);
break; break;
case LUA_TLIGHTUSERDATA: case LUA_TLIGHTUSERDATA: {
//reverse engineer the room index //check that this is a room first
for (auto& it : *roomMgr.GetContainer()) { RoomData* room = static_cast<RoomData*>(lua_touserdata(L, 2));
if (lua_touserdata(L, 2) == &it.second) { RoomManager& roomMgr = RoomManager::GetSingleton();
roomIndex = it.first;
break;
}
}
break;
}
//error checking if (roomMgr.Find(room->GetRoomIndex()) != room) {
if (roomIndex == -1) { std::cout << room->GetRoomIndex() << std::endl;
throw(std::runtime_error("Lua Error: Failed to find room index by reference")); throw(std::runtime_error("Lua Error: Failed to verify room index by reference"));
}
roomIndex = room->GetRoomIndex();
}
break;
default:
throw(std::runtime_error("Lua Error: Failed to find room index by reference"));
} }
//send the delete & create messages //send the delete & create messages
pumpAndChangeRooms(character, roomIndex, characterIndex); pumpAndChangeRooms(character, roomIndex, character->GetIndex());
return 0; return 0;
} }
static int getIndex(lua_State* L) {
CharacterData* character = static_cast<CharacterData*>(lua_touserdata(L, 1));
lua_pushinteger(L, character->GetIndex());
return 1;
}
static int getOwner(lua_State* L) { static int getOwner(lua_State* L) {
CharacterData* character = static_cast<CharacterData*>(lua_touserdata(L, 1)); CharacterData* character = static_cast<CharacterData*>(lua_touserdata(L, 1));
lua_pushinteger(L, character->GetOwner()); lua_pushinteger(L, character->GetOwner());
@@ -95,6 +93,7 @@ static int getAvatar(lua_State* L) {
static const luaL_Reg characterLib[] = { static const luaL_Reg characterLib[] = {
{"SetRoom", setRoom}, {"SetRoom", setRoom},
{"GetIndex", getIndex},
// {"GetOwner", getOwner}, //unusable without account API // {"GetOwner", getOwner}, //unusable without account API
{"GetHandle", getHandle}, {"GetHandle", getHandle},
{"GetAvatar", getAvatar}, {"GetAvatar", getAvatar},
@@ -102,27 +101,27 @@ static const luaL_Reg characterLib[] = {
}; };
LUAMOD_API int openCharacterAPI(lua_State* L) { LUAMOD_API int openCharacterAPI(lua_State* L) {
//get the parent table
luaL_requiref(L, TORTUGA_ENTITY_API, openEntityAPI, false);
//the local table //the local table
luaL_newlib(L, characterLib); luaL_newlib(L, characterLib);
//merge the local table into the parent table //get the parent table
luaL_requiref(L, TORTUGA_ENTITY_API, openEntityAPI, false);
//merge the parent table into the local table
lua_pushnil(L); //first key lua_pushnil(L); //first key
while(lua_next(L, -2)) { while(lua_next(L, -2)) {
//copy the key-value pair //copy the key-value pair
lua_pushvalue(L, -2); lua_pushvalue(L, -2);
lua_pushvalue(L, -2); lua_pushvalue(L, -2);
//push the copy to the parent table //push the copy to the local table
lua_settable(L, -6); lua_settable(L, -6);
//pop the original value before continuing //pop the original value before continuing
lua_pop(L, 1); lua_pop(L, 1);
} }
//remove the local table, leaving the expanded parent table //remove the parent table, leaving the expanded local table
lua_pop(L, 1); lua_pop(L, 1);
return 1; return 1;
+18 -1
View File
@@ -22,7 +22,20 @@
#include "character_data.hpp" #include "character_data.hpp"
CharacterData::CharacterData(): Entity("character") { CharacterData::CharacterData(): Entity("character") {
//EMPTY SetBounds({
CHARACTER_BOUNDS_X,
CHARACTER_BOUNDS_Y,
CHARACTER_BOUNDS_WIDTH,
CHARACTER_BOUNDS_HEIGHT
});
}
//-------------------------
//database stuff
//-------------------------
int CharacterData::GetIndex() {
return index;
} }
int CharacterData::GetOwner() { int CharacterData::GetOwner() {
@@ -36,3 +49,7 @@ std::string CharacterData::GetHandle() {
std::string CharacterData::GetAvatar() { std::string CharacterData::GetAvatar() {
return avatar; return avatar;
} }
Inventory* CharacterData::GetInventory() {
return &inventory;
}
+6
View File
@@ -24,6 +24,7 @@
//components //components
#include "character_defines.hpp" #include "character_defines.hpp"
#include "entity.hpp" #include "entity.hpp"
#include "inventory.hpp"
//std namespace //std namespace
#include <string> #include <string>
@@ -35,14 +36,19 @@ public:
~CharacterData() = default; ~CharacterData() = default;
//database stuff //database stuff
int GetIndex();
int GetOwner(); int GetOwner();
std::string GetHandle(); std::string GetHandle();
std::string GetAvatar(); std::string GetAvatar();
Inventory* GetInventory();
private: private:
friend class CharacterManager; friend class CharacterManager;
//database stuff
int index = -1;
int owner = -1; int owner = -1;
std::string handle; std::string handle;
std::string avatar; std::string avatar;
Inventory inventory;
}; };
+12 -31
View File
@@ -39,12 +39,8 @@
static const char* CREATE_CHARACTER = "INSERT INTO LiveCharacters (" static const char* CREATE_CHARACTER = "INSERT INTO LiveCharacters ("
"owner, " "owner, "
"handle, " "handle, "
"avatar, " "avatar "
"boundsX, " ") VALUES (?1, ?2, ?3);";
"boundsY, "
"boundsW, "
"boundsH"
") VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7);";
static const char* LOAD_CHARACTER = "SELECT " static const char* LOAD_CHARACTER = "SELECT "
"uid, " "uid, "
@@ -53,21 +49,13 @@ static const char* LOAD_CHARACTER = "SELECT "
"avatar, " "avatar, "
"roomIndex, " "roomIndex, "
"originX, " "originX, "
"originY, " "originY "
"boundsX, "
"boundsY, "
"boundsW, "
"boundsH "
"FROM LiveCharacters WHERE handle = ?;"; "FROM LiveCharacters WHERE handle = ?;";
static const char* SAVE_CHARACTER = "UPDATE OR FAIL LiveCharacters SET " static const char* SAVE_CHARACTER = "UPDATE OR FAIL LiveCharacters SET "
"roomIndex = ?2, " "roomIndex = ?2, "
"originX = ?3, " "originX = ?3, "
"originY = ?4, " "originY = ?4 "
"boundsX = ?5, "
"boundsY = ?6, "
"boundsW = ?7, "
"boundsH = ?8 "
"WHERE uid = ?1;"; "WHERE uid = ?1;";
static const char* DELETE_CHARACTER = "DELETE FROM LiveCharacters WHERE uid = ?;"; static const char* DELETE_CHARACTER = "DELETE FROM LiveCharacters WHERE uid = ?;";
@@ -93,10 +81,6 @@ int CharacterManager::Create(int owner, std::string handle, std::string avatar)
ret |= sqlite3_bind_int(statement, 1, owner); ret |= sqlite3_bind_int(statement, 1, owner);
ret |= sqlite3_bind_text(statement, 2, handle.c_str(), handle.size() + 1, SQLITE_STATIC); ret |= sqlite3_bind_text(statement, 2, handle.c_str(), handle.size() + 1, SQLITE_STATIC);
ret |= sqlite3_bind_text(statement, 3, avatar.c_str(), avatar.size() + 1, SQLITE_STATIC); ret |= sqlite3_bind_text(statement, 3, avatar.c_str(), avatar.size() + 1, SQLITE_STATIC);
ret |= sqlite3_bind_int(statement, 4, CHARACTER_BOUNDS_X);
ret |= sqlite3_bind_int(statement, 5, CHARACTER_BOUNDS_Y);
ret |= sqlite3_bind_int(statement, 6, CHARACTER_BOUNDS_WIDTH);
ret |= sqlite3_bind_int(statement, 7, CHARACTER_BOUNDS_HEIGHT);
//check for binding errors //check for binding errors
if (ret) { if (ret) {
@@ -157,6 +141,7 @@ int CharacterManager::Load(int owner, std::string handle, std::string avatar) {
CharacterData& newChar = elementMap[uid]; CharacterData& newChar = elementMap[uid];
//metadata //metadata
newChar.index = uid;
newChar.owner = owner; newChar.owner = owner;
newChar.handle = reinterpret_cast<const char*>(sqlite3_column_text(statement, 2)); newChar.handle = reinterpret_cast<const char*>(sqlite3_column_text(statement, 2));
newChar.avatar = reinterpret_cast<const char*>(sqlite3_column_text(statement, 3)); newChar.avatar = reinterpret_cast<const char*>(sqlite3_column_text(statement, 3));
@@ -167,10 +152,10 @@ int CharacterManager::Load(int owner, std::string handle, std::string avatar) {
newChar.origin.x = (double)sqlite3_column_int(statement, 5); newChar.origin.x = (double)sqlite3_column_int(statement, 5);
newChar.origin.y = (double)sqlite3_column_int(statement, 6); newChar.origin.y = (double)sqlite3_column_int(statement, 6);
//bounds //bounds
newChar.bounds.x = (int)sqlite3_column_int(statement, 7); newChar.bounds.x = CHARACTER_BOUNDS_X;
newChar.bounds.y = (int)sqlite3_column_int(statement, 8); newChar.bounds.y = CHARACTER_BOUNDS_Y;
newChar.bounds.w = (int)sqlite3_column_int(statement, 9); newChar.bounds.w = CHARACTER_BOUNDS_WIDTH;
newChar.bounds.h = (int)sqlite3_column_int(statement, 10); newChar.bounds.h = CHARACTER_BOUNDS_HEIGHT;
//gameplay components: equipment, items, buffs, debuffs... //gameplay components: equipment, items, buffs, debuffs...
@@ -212,12 +197,8 @@ int CharacterManager::Save(int uid) {
ret |= sqlite3_bind_int(statement, 2, character.roomIndex) != SQLITE_OK; ret |= sqlite3_bind_int(statement, 2, character.roomIndex) != SQLITE_OK;
ret |= sqlite3_bind_int(statement, 3, (int)character.origin.x) != SQLITE_OK; ret |= sqlite3_bind_int(statement, 3, (int)character.origin.x) != SQLITE_OK;
ret |= sqlite3_bind_int(statement, 4, (int)character.origin.y) != SQLITE_OK; ret |= sqlite3_bind_int(statement, 4, (int)character.origin.y) != SQLITE_OK;
ret |= sqlite3_bind_int(statement, 5, character.bounds.x) != SQLITE_OK;
ret |= sqlite3_bind_int(statement, 6, character.bounds.y) != SQLITE_OK;
ret |= sqlite3_bind_int(statement, 7, character.bounds.w) != SQLITE_OK;
ret |= sqlite3_bind_int(statement, 8, character.bounds.h) != SQLITE_OK;
//gameplay components: equipment, items, buffs, debuffs... //TODO: gameplay components: equipment, items, buffs, debuffs...
//check for binding errors //check for binding errors
if (ret) { if (ret) {
@@ -294,7 +275,7 @@ void CharacterManager::UnloadIf(std::function<bool(std::pair<const int, Characte
//Define the accessors and mutators //Define the accessors and mutators
//------------------------- //-------------------------
CharacterData* CharacterManager::Get(int uid) { CharacterData* CharacterManager::Find(int uid) {
std::map<int, CharacterData>::iterator it = elementMap.find(uid); std::map<int, CharacterData>::iterator it = elementMap.find(uid);
if (it == elementMap.end()) { if (it == elementMap.end()) {
@@ -304,7 +285,7 @@ CharacterData* CharacterManager::Get(int uid) {
return &it->second; return &it->second;
} }
CharacterData* CharacterManager::Get(std::string handle) { CharacterData* CharacterManager::Find(std::string handle) {
for (std::map<int, CharacterData>::iterator it = elementMap.begin(); it != elementMap.end(); ++it) { for (std::map<int, CharacterData>::iterator it = elementMap.begin(); it != elementMap.end(); ++it) {
if (it->second.GetHandle() == handle) { if (it->second.GetHandle() == handle) {
return &it->second; return &it->second;
+2 -2
View File
@@ -42,8 +42,8 @@ public:
void UnloadIf(std::function<bool(std::pair<const int, CharacterData const&>)> fn); void UnloadIf(std::function<bool(std::pair<const int, CharacterData const&>)> fn);
//accessors and mutators //accessors and mutators
CharacterData* Get(int uid); CharacterData* Find(int uid);
CharacterData* Get(std::string handle); CharacterData* Find(std::string handle);
int GetLoadedCount(); int GetLoadedCount();
int GetTotalCount(); int GetTotalCount();
std::map<int, CharacterData>* GetContainer(); std::map<int, CharacterData>* GetContainer();
+2 -2
View File
@@ -55,11 +55,11 @@ static int getCharacter(lua_State* L) {
switch(lua_type(L, 1)) { switch(lua_type(L, 1)) {
case LUA_TNUMBER: case LUA_TNUMBER:
characterData = characterMgr.Get(lua_tointeger(L, 1)); characterData = characterMgr.Find(lua_tointeger(L, 1));
break; break;
case LUA_TSTRING: case LUA_TSTRING:
//access characters via their handles //access characters via their handles
characterData = characterMgr.Get(lua_tostring(L, 1)); characterData = characterMgr.Find(lua_tostring(L, 1));
break; break;
} }

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