diff --git a/src/EglConfigPrinter.h b/src/EglConfigPrinter.h index dbf7ead..bd482d1 100755 --- a/src/EglConfigPrinter.h +++ b/src/EglConfigPrinter.h @@ -1,5 +1,4 @@ -#ifndef EGLCONFIGPRINTER_H__ -#define EGLCONFIGPRINTER_H__ +#pragma once #include #include @@ -122,4 +121,3 @@ public: } }; -#endif /*EGLCONFIGPRINTER_H__*/ \ No newline at end of file diff --git a/src/LicenseCodes.h b/src/LicenseCodes.h index f62f42b..e3ce2a9 100755 --- a/src/LicenseCodes.h +++ b/src/LicenseCodes.h @@ -1,40 +1,39 @@ -#ifndef LICENSECODES_H__ -#define LICENSECODES_H__ - -class LicenseCodes -{ -public: - // Something's not ready, call again later - static const int WAIT_PLATFORM_NOT_READY = -2; - static const int WAIT_SERVER_NOT_READY = -1; - - // License is ok - static const int LICENSE_OK = 0; - static const int LICENSE_TRIAL_OK = 1; - - // License is not working in one way or another - static const int LICENSE_VALIDATION_FAILED = 50; - static const int ITEM_NOT_FOUND = 51; - static const int LICENSE_NOT_FOUND = 52; - static const int ERROR_CONTENT_HANDLER = 100; - static const int ERROR_ILLEGAL_ARGUMENT = 101; - static const int ERROR_SECURITY = 102; - static const int ERROR_INPUT_OUTPUT = 103; - static const int ERROR_ILLEGAL_STATE = 104; - static const int ERROR_NULL_POINTER = 105; - static const int ERROR_GENERAL = 106; - static const int ERROR_UNABLE_TO_CONNECT_TO_CDS = 107; - - // The call went wrong so we didn't get a license value at all - static const int ERROR_EXCEPTION = 200; - - static bool isOk(int i) { - return (i == 0) || (i == 1); - } - static bool isReady(int i) { - return (i >= 0); - } -}; - -#endif /*LICENSECODES_H__ */ - +#pragma once + +class LicenseCodes +{ +public: + // Something's not ready, call again later + static const int WAIT_PLATFORM_NOT_READY = -2; + static const int WAIT_SERVER_NOT_READY = -1; + + // License is ok + static const int LICENSE_OK = 0; + static const int LICENSE_TRIAL_OK = 1; + + // License is not working in one way or another + static const int LICENSE_VALIDATION_FAILED = 50; + static const int ITEM_NOT_FOUND = 51; + static const int LICENSE_NOT_FOUND = 52; + static const int ERROR_CONTENT_HANDLER = 100; + static const int ERROR_ILLEGAL_ARGUMENT = 101; + static const int ERROR_SECURITY = 102; + static const int ERROR_INPUT_OUTPUT = 103; + static const int ERROR_ILLEGAL_STATE = 104; + static const int ERROR_NULL_POINTER = 105; + static const int ERROR_GENERAL = 106; + static const int ERROR_UNABLE_TO_CONNECT_TO_CDS = 107; + + // The call went wrong so we didn't get a license value at all + static const int ERROR_EXCEPTION = 200; + + static bool isOk(int i) { + return (i == 0) || (i == 1); + } + static bool isReady(int i) { + return (i >= 0); + } +}; + +#endif /*LICENSECODES_H__ */ + diff --git a/src/Minecraft.h b/src/Minecraft.h index eb1a8af..1842493 100755 --- a/src/Minecraft.h +++ b/src/Minecraft.h @@ -1,140 +1,138 @@ -#ifndef NET_MINECRAFT_CLIENT__Minecraft_H__ -#define NET_MINECRAFT_CLIENT__Minecraft_H__ - -#include "client/Options.h" -#include "client/Timer.h" - -//#include "../network/RakNetInstance.h" -#include "world/phys/HitResult.h" - -#include "App.h" -#include - -class Level; -class LocalPlayer; -class IInputHolder; -class Mob; -class Player; -class Entity; -class ICreator; -class GameMode; -class CThread; -class LevelStorageSource; -class BuildActionIntention; -class PerfRenderer; -class LevelSettings; -class IRakNetInstance; -class NetEventCallback; -class CommandServer; -struct PingedCompatibleServer; - -class Minecraft: public App { -public: - using App::App; - virtual ~Minecraft(); - - virtual void init(); - virtual void update(); - virtual void restartServer(); - virtual void tick(int nTick, int maxTick); - - virtual bool isOnlineClient(); - virtual bool isOnline(); - - virtual void setIsCreativeMode(bool isCreative); - - virtual void optionUpdated(OptionId option, bool value); - virtual void optionUpdated(OptionId option, float value); - virtual void optionUpdated(OptionId option, int value); - - /** - * @brief Get public name that will be listed in JoinGame menu - */ - virtual std::string getServerName() { return "Unknown"; } - - void toggleDimension() {} - bool isCreativeMode(); - - virtual void selectLevel(const std::string& levelId, const std::string& levelName, const LevelSettings& settings); - virtual void setLevel(Level* level, const std::string& message = "", Player* forceInsertPlayer = NULL); - - virtual void onBlockDestroyed(Player* player, int x, int y, int z, int face) {} - - void generateLevel( const std::string& message, Level* level ); - LevelStorageSource* getLevelSource(); - - virtual void hostMultiplayer(int port=19132); - Player* respawnPlayer(int playerId); - void respawnPlayer(); - void resetPlayer(Player* player); - void doActuallyRespawnPlayer(); - - void prepareLevel(const std::string& message); - - int getProgressStatusId(); - const char* getProgressMessage(); - - ICreator* getCreator(); - - bool isLevelGenerated(); - -#ifdef __APPLE__ - bool _isSuperFast = false; - bool isSuperFast() { return _isSuperFast; } -#endif - -protected: - virtual void _levelGenerated(); - -private: - static void* prepareLevel_tspawn(void *p_param); -public: - Level* level = nullptr; - CommandServer* _commandServer = nullptr; - GameMode* gameMode = nullptr; - IRakNetInstance* raknetInstance = nullptr; - NetEventCallback* netCallback = nullptr; - - int commandPort = 4711; - - int lastTime = 0; - int lastTickTime = -1; - int missTime = 0; - int ticks = 0; - - CThread* generateLevelThread = nullptr; - // static int customDebugId; - - HitResult hitResult; - volatile int progressStagePercentage = 0; - - // This field is initialized in main() - // It sets the base path to where worlds can be written (sdcard on android) - std::string externalStoragePath; - std::string externalCacheStoragePath; -protected: - Timer timer{20}; - // @note @attn @warn: this is dangerous as fuck! - volatile bool isGeneratingLevel = false; - bool _hasSignaledGeneratingLevelFinished = true; - - LevelStorageSource* storageSource; - bool _running; - -protected: - volatile int progressStageStatusId = 0; - static const char* progressMessages[]; - - int _licenseId; - - bool _isCreativeMode; - Player* _pendingRemovePlayer; // @attn @todo @fix: remove this shait and fix the respawn behaviour - - // from NinecraftApp - bool _verbose = true; - int _lastTickMs = 0; - - static bool _hasInitedStatics; -}; - -#endif /*NET_MINECRAFT_CLIENT__Minecraft_H__*/ +#pragma once + +#include "client/Options.h" +#include "client/Timer.h" + +//#include "../network/RakNetInstance.h" +#include "world/phys/HitResult.h" + +#include "App.h" +#include + +class Level; +class LocalPlayer; +class IInputHolder; +class Mob; +class Player; +class Entity; +class ICreator; +class GameMode; +class CThread; +class LevelStorageSource; +class BuildActionIntention; +class PerfRenderer; +class LevelSettings; +class IRakNetInstance; +class NetEventCallback; +class CommandServer; +struct PingedCompatibleServer; + +class Minecraft: public App { +public: + using App::App; + virtual ~Minecraft(); + + virtual void init(); + virtual void update(); + virtual void restartServer(); + virtual void tick(int nTick, int maxTick); + + virtual bool isOnlineClient(); + virtual bool isOnline(); + + virtual void setIsCreativeMode(bool isCreative); + + virtual void optionUpdated(OptionId option, bool value); + virtual void optionUpdated(OptionId option, float value); + virtual void optionUpdated(OptionId option, int value); + + /** + * @brief Get public name that will be listed in JoinGame menu + */ + virtual std::string getServerName() { return "Unknown"; } + + void toggleDimension() {} + bool isCreativeMode(); + + virtual void selectLevel(const std::string& levelId, const std::string& levelName, const LevelSettings& settings); + virtual void setLevel(Level* level, const std::string& message = "", Player* forceInsertPlayer = NULL); + + virtual void onBlockDestroyed(Player* player, int x, int y, int z, int face) {} + + void generateLevel( const std::string& message, Level* level ); + LevelStorageSource* getLevelSource(); + + virtual void hostMultiplayer(int port=19132); + Player* respawnPlayer(int playerId); + void respawnPlayer(); + void resetPlayer(Player* player); + void doActuallyRespawnPlayer(); + + void prepareLevel(const std::string& message); + + int getProgressStatusId(); + const char* getProgressMessage(); + + ICreator* getCreator(); + + bool isLevelGenerated(); + +#ifdef __APPLE__ + bool _isSuperFast = false; + bool isSuperFast() { return _isSuperFast; } +#endif + +protected: + virtual void _levelGenerated(); + +private: + static void* prepareLevel_tspawn(void *p_param); +public: + Level* level = nullptr; + CommandServer* _commandServer = nullptr; + GameMode* gameMode = nullptr; + IRakNetInstance* raknetInstance = nullptr; + NetEventCallback* netCallback = nullptr; + + int commandPort = 4711; + + int lastTime = 0; + int lastTickTime = -1; + int missTime = 0; + int ticks = 0; + + CThread* generateLevelThread = nullptr; + // static int customDebugId; + + HitResult hitResult; + volatile int progressStagePercentage = 0; + + // This field is initialized in main() + // It sets the base path to where worlds can be written (sdcard on android) + std::string externalStoragePath; + std::string externalCacheStoragePath; +protected: + Timer timer{20}; + // @note @attn @warn: this is dangerous as fuck! + volatile bool isGeneratingLevel = false; + bool _hasSignaledGeneratingLevelFinished = true; + + LevelStorageSource* storageSource; + bool _running; + +protected: + volatile int progressStageStatusId = 0; + static const char* progressMessages[]; + + int _licenseId; + + bool _isCreativeMode; + Player* _pendingRemovePlayer; // @attn @todo @fix: remove this shait and fix the respawn behaviour + + // from NinecraftApp + bool _verbose = true; + int _lastTickMs = 0; + + static bool _hasInitedStatics; +}; + diff --git a/src/Performance.h b/src/Performance.h index c30d0d5..1eec129 100755 --- a/src/Performance.h +++ b/src/Performance.h @@ -1,12 +1,10 @@ -#ifndef PERFORMANCE_H__ -#define PERFORMANCE_H__ - -#include "platform/time.h" - -class Performance -{ -public: - static StopwatchHandler watches; -}; - -#endif /*PERFORMANCE_H__*/ +#pragma once + +#include "platform/time.h" + +class Performance +{ +public: + static StopwatchHandler watches; +}; + diff --git a/src/SharedConstants.h b/src/SharedConstants.h index f97ea36..55fcfd8 100755 --- a/src/SharedConstants.h +++ b/src/SharedConstants.h @@ -1,34 +1,32 @@ -#ifndef NET_MINECRAFT_SharedConstants_H__ -#define NET_MINECRAFT_SharedConstants_H__ - -#include - -enum LevelGeneratorVersion -{ - LGV_ORIGINAL = 0, -}; - -namespace Common { - std::string getGameVersionString(const std::string& versionSuffix = ""); -} - -namespace SharedConstants -{ - // 0.5.0 uses NPv8 - // 0.6.0 uses NPv9 - const int NetworkProtocolVersion = 9; - const int NetworkProtocolLowestSupportedVersion = 9; - const int GameProtocolVersion = 1; - const int GameProtocolLowestSupportedVersion = 1; - - const int StorageVersion = 3; - - const int MaxChatLength = 100; - - const int TicksPerSecond = 20; - - const int GeneratorVersion = (int)LGV_ORIGINAL; - //int FULLBRIGHT_LIGHTVALUE = 15 << 20 | 15 << 4; -} - -#endif /*NET_MINECRAFT_SharedConstants_H__*/ +#pragma once + +#include + +enum LevelGeneratorVersion +{ + LGV_ORIGINAL = 0, +}; + +namespace Common { + std::string getGameVersionString(const std::string& versionSuffix = ""); +} + +namespace SharedConstants +{ + // 0.5.0 uses NPv8 + // 0.6.0 uses NPv9 + const int NetworkProtocolVersion = 9; + const int NetworkProtocolLowestSupportedVersion = 9; + const int GameProtocolVersion = 1; + const int GameProtocolLowestSupportedVersion = 1; + + const int StorageVersion = 3; + + const int MaxChatLength = 100; + + const int TicksPerSecond = 20; + + const int GeneratorVersion = (int)LGV_ORIGINAL; + //int FULLBRIGHT_LIGHTVALUE = 15 << 20 | 15 << 4; +} + diff --git a/src/client/IConfigListener.h b/src/client/IConfigListener.h index 6e96a2b..9821c55 100755 --- a/src/client/IConfigListener.h +++ b/src/client/IConfigListener.h @@ -1,48 +1,46 @@ -#ifndef CONFIGLISTENER_H__ -#define CONFIGLISTENER_H__ - -#include "PixelCalc.h" -class Minecraft; -class Options; - -class Config { -public: - // Screen dimensions and world-to-screen conversion - void setScreenSize(int width, int height, float scale) { - this->width = width; - this->height = height; - this->guiScale = scale; - this->invGuiScale = 1.0f / scale; - this->guiWidth = (int)(width * invGuiScale); - this->guiHeight = (int)(height * invGuiScale); - } - - int width; - int height; - - float guiScale; - float invGuiScale; - int guiWidth; - int guiHeight; - - PixelCalc pixelCalc; - PixelCalc pixelCalcUi; - - Minecraft* minecraft; - Options* options; -}; - -Config createConfig(Minecraft* mc); - -// Interface for Configuration-Changed listener -// This can mean (for instance); -// - Screen has changed dimensions, or rotation if rotations are enabled -// - New input device or control mechanism -class IConfigListener -{ -public: - virtual ~IConfigListener() {} - virtual void onConfigChanged(const Config& config) = 0; -}; - -#endif /*CONFIGLISTENER_H__*/ +#pragma once + +#include "PixelCalc.h" +class Minecraft; +class Options; + +class Config { +public: + // Screen dimensions and world-to-screen conversion + void setScreenSize(int width, int height, float scale) { + this->width = width; + this->height = height; + this->guiScale = scale; + this->invGuiScale = 1.0f / scale; + this->guiWidth = (int)(width * invGuiScale); + this->guiHeight = (int)(height * invGuiScale); + } + + int width; + int height; + + float guiScale; + float invGuiScale; + int guiWidth; + int guiHeight; + + PixelCalc pixelCalc; + PixelCalc pixelCalcUi; + + Minecraft* minecraft; + Options* options; +}; + +Config createConfig(Minecraft* mc); + +// Interface for Configuration-Changed listener +// This can mean (for instance); +// - Screen has changed dimensions, or rotation if rotations are enabled +// - New input device or control mechanism +class IConfigListener +{ +public: + virtual ~IConfigListener() {} + virtual void onConfigChanged(const Config& config) = 0; +}; + diff --git a/src/client/MouseHandler.h b/src/client/MouseHandler.h index 32ff60c..13615eb 100755 --- a/src/client/MouseHandler.h +++ b/src/client/MouseHandler.h @@ -1,28 +1,26 @@ -#ifndef NET_MINECRAFT_CLIENT__MouseHandler_H__ -#define NET_MINECRAFT_CLIENT__MouseHandler_H__ - -//package net.minecraft.client; - -class ITurnInput; - -class MouseHandler -{ -public: - MouseHandler(ITurnInput* turnInput); - MouseHandler(); - ~MouseHandler(); - - void setTurnInput(ITurnInput* turnInput); - - void grab(); - void release(); - - void poll(); - - float xd, yd; -private: - int toSkip; - ITurnInput* _turnInput; -}; - -#endif /*NET_MINECRAFT_CLIENT__MouseHandler_H__*/ +#pragma once + +//package net.minecraft.client; + +class ITurnInput; + +class MouseHandler +{ +public: + MouseHandler(ITurnInput* turnInput); + MouseHandler(); + ~MouseHandler(); + + void setTurnInput(ITurnInput* turnInput); + + void grab(); + void release(); + + void poll(); + + float xd, yd; +private: + int toSkip; + ITurnInput* _turnInput; +}; + diff --git a/src/client/OptionStrings.h b/src/client/OptionStrings.h index 3f4e839..7dca051 100755 --- a/src/client/OptionStrings.h +++ b/src/client/OptionStrings.h @@ -1,5 +1,4 @@ -#ifndef NET_MINECRAFT_CLIENT__OptionStrings_H__ -#define NET_MINECRAFT_CLIENT__OptionStrings_H__ +#pragma once class OptionStrings { public: @@ -33,4 +32,3 @@ public: }; -#endif /*NET_MINECRAFT_CLIENT__OptionsStrings_H__*/ diff --git a/src/client/Options.h b/src/client/Options.h index 3f757d9..90435a5 100755 --- a/src/client/Options.h +++ b/src/client/Options.h @@ -1,166 +1,164 @@ -#ifndef NET_MINECRAFT_CLIENT__Options_H__ -#define NET_MINECRAFT_CLIENT__Options_H__ - -#define SOUND_MIN_VALUE 0.0f -#define SOUND_MAX_VALUE 1.0f -#define MUSIC_MIN_VALUE 0.0f -#define MUSIC_MAX_VALUE 1.0f -#define SENSITIVITY_MIN_VALUE 0.0f -#define SENSITIVITY_MAX_VALUE 1.0f -#define PIXELS_PER_MILLIMETER_MIN_VALUE 3.0f -#define PIXELS_PER_MILLIMETER_MAX_VALUE 4.0f - -//package net.minecraft.client; - -//#include "locale/Language.h" - -#include -#include -#include -#include "OptionsFile.h" -#include "Option.h" -#include - -enum OptionId { - // General - OPTIONS_DIFFICULTY, - OPTIONS_HIDEGUI, - OPTIONS_THIRD_PERSON_VIEW, - OPTIONS_GUI_SCALE, - OPTIONS_DESTROY_VIBRATION, - OPTIONS_MUSIC_VOLUME, - OPTIONS_SOUND_VOLUME, - OPTIONS_SKIN, - OPTIONS_USERNAME, - OPTIONS_SERVER_VISIBLE, - OPTIONS_BAR_ON_TOP, - OPTIONS_ALLOW_SPRINT, - OPTIONS_AUTOJUMP, - - // Graphics - OPTIONS_RENDER_DEBUG, - OPTIONS_SMOOTH_CAMERA, - OPTIONS_FIXED_CAMERA, - OPTIONS_VIEW_DISTANCE, - OPTIONS_VIEW_BOBBING, - OPTIONS_AMBIENT_OCCLUSION, - OPTIONS_ANAGLYPH_3D, - OPTIONS_LIMIT_FRAMERATE, - OPTIONS_VSYNC, - OPTIONS_FANCY_GRAPHICS, - - // Cheats / debug - OPTIONS_FLY_SPEED, - OPTIONS_CAMERA_SPEED, - OPTIONS_IS_FLYING, - - // Control - OPTIONS_USE_MOUSE_FOR_DIGGING, - OPTIONS_IS_LEFT_HANDED, - OPTIONS_IS_JOY_TOUCH_AREA, - OPTIONS_SENSITIVITY, - OPTIONS_INVERT_Y_MOUSE, - OPTIONS_USE_TOUCHSCREEN, - - OPTIONS_KEY_FORWARD, - OPTIONS_KEY_LEFT, - OPTIONS_KEY_BACK, - OPTIONS_KEY_RIGHT, - OPTIONS_KEY_JUMP, - OPTIONS_KEY_INVENTORY, - OPTIONS_KEY_SNEAK, - OPTIONS_KEY_DROP, - OPTIONS_KEY_CHAT, - OPTIONS_KEY_FOG, - OPTIONS_KEY_USE, - - OPTIONS_KEY_MENU_NEXT, - OPTIONS_KEY_MENU_PREV, - OPTIONS_KEY_MENU_OK, - OPTIONS_KEY_MENU_CANCEL, - - OPTIONS_FIRST_LAUNCH, - OPTIONS_LAST_IP, - - OPTIONS_RPI_CURSOR, - // Should be last! - OPTIONS_COUNT -}; - -class MinecraftClient; -typedef std::vector StringVector; - -class Options -{ -public: - static bool debugGl; - - Options(MinecraftClient& minecraft, const std::string& workingDirectory = "") - : minecraft(minecraft) { - // elements werent initialized so i was getting a garbage pointer and a crash - m_options.fill(nullptr); - initTable(); - // load() is deferred to init() where path is configured correctly - } - - void initTable(); - - int getIntValue(OptionId key) { - auto option = opt(key); - return (option)? option->get() : 0; - } - - std::string getStringValue(OptionId key) { - auto option = opt(key); - return (option)? option->get() : ""; - } - - float getProgressValue(OptionId key) { - auto option = opt(key); - return (option)? option->get() : 0.f; - } - - bool getBooleanValue(OptionId key) { - auto option = opt(key); - return (option)? option->get() : false; - } - - float getProgrssMin(OptionId key) { - auto option = opt(key); - return (option)? option->getMin() : 0.f; - } - - float getProgrssMax(OptionId key) { - auto option = opt(key); - return (option)? option->getMax() : 0.f; - } - - Option* getOpt(OptionId id) { return m_options[id]; } - - void load(); - void save(); - void set(OptionId key, int value); - void set(OptionId key, float value); - void set(OptionId key, const std::string& value); - void setOptionsFilePath(const std::string& path); - void toggle(OptionId key); - - void notifyOptionUpdate(OptionId key, bool value); - void notifyOptionUpdate(OptionId key, float value); - void notifyOptionUpdate(OptionId key, int value); - void notifyOptionUpdate(OptionId key, const std::string& value) {} - -private: - template - T* opt(OptionId key) { - if (m_options[key] == nullptr) return nullptr; - return dynamic_cast(m_options[key]); - } - - std::array m_options; - OptionsFile optionsFile; - - MinecraftClient& minecraft; -}; - -#endif /*NET_MINECRAFT_CLIENT__Options_H__*/ +#pragma once + +#define SOUND_MIN_VALUE 0.0f +#define SOUND_MAX_VALUE 1.0f +#define MUSIC_MIN_VALUE 0.0f +#define MUSIC_MAX_VALUE 1.0f +#define SENSITIVITY_MIN_VALUE 0.0f +#define SENSITIVITY_MAX_VALUE 1.0f +#define PIXELS_PER_MILLIMETER_MIN_VALUE 3.0f +#define PIXELS_PER_MILLIMETER_MAX_VALUE 4.0f + +//package net.minecraft.client; + +//#include "locale/Language.h" + +#include +#include +#include +#include "OptionsFile.h" +#include "Option.h" +#include + +enum OptionId { + // General + OPTIONS_DIFFICULTY, + OPTIONS_HIDEGUI, + OPTIONS_THIRD_PERSON_VIEW, + OPTIONS_GUI_SCALE, + OPTIONS_DESTROY_VIBRATION, + OPTIONS_MUSIC_VOLUME, + OPTIONS_SOUND_VOLUME, + OPTIONS_SKIN, + OPTIONS_USERNAME, + OPTIONS_SERVER_VISIBLE, + OPTIONS_BAR_ON_TOP, + OPTIONS_ALLOW_SPRINT, + OPTIONS_AUTOJUMP, + + // Graphics + OPTIONS_RENDER_DEBUG, + OPTIONS_SMOOTH_CAMERA, + OPTIONS_FIXED_CAMERA, + OPTIONS_VIEW_DISTANCE, + OPTIONS_VIEW_BOBBING, + OPTIONS_AMBIENT_OCCLUSION, + OPTIONS_ANAGLYPH_3D, + OPTIONS_LIMIT_FRAMERATE, + OPTIONS_VSYNC, + OPTIONS_FANCY_GRAPHICS, + + // Cheats / debug + OPTIONS_FLY_SPEED, + OPTIONS_CAMERA_SPEED, + OPTIONS_IS_FLYING, + + // Control + OPTIONS_USE_MOUSE_FOR_DIGGING, + OPTIONS_IS_LEFT_HANDED, + OPTIONS_IS_JOY_TOUCH_AREA, + OPTIONS_SENSITIVITY, + OPTIONS_INVERT_Y_MOUSE, + OPTIONS_USE_TOUCHSCREEN, + + OPTIONS_KEY_FORWARD, + OPTIONS_KEY_LEFT, + OPTIONS_KEY_BACK, + OPTIONS_KEY_RIGHT, + OPTIONS_KEY_JUMP, + OPTIONS_KEY_INVENTORY, + OPTIONS_KEY_SNEAK, + OPTIONS_KEY_DROP, + OPTIONS_KEY_CHAT, + OPTIONS_KEY_FOG, + OPTIONS_KEY_USE, + + OPTIONS_KEY_MENU_NEXT, + OPTIONS_KEY_MENU_PREV, + OPTIONS_KEY_MENU_OK, + OPTIONS_KEY_MENU_CANCEL, + + OPTIONS_FIRST_LAUNCH, + OPTIONS_LAST_IP, + + OPTIONS_RPI_CURSOR, + // Should be last! + OPTIONS_COUNT +}; + +class MinecraftClient; +typedef std::vector StringVector; + +class Options +{ +public: + static bool debugGl; + + Options(MinecraftClient& minecraft, const std::string& workingDirectory = "") + : minecraft(minecraft) { + // elements werent initialized so i was getting a garbage pointer and a crash + m_options.fill(nullptr); + initTable(); + // load() is deferred to init() where path is configured correctly + } + + void initTable(); + + int getIntValue(OptionId key) { + auto option = opt(key); + return (option)? option->get() : 0; + } + + std::string getStringValue(OptionId key) { + auto option = opt(key); + return (option)? option->get() : ""; + } + + float getProgressValue(OptionId key) { + auto option = opt(key); + return (option)? option->get() : 0.f; + } + + bool getBooleanValue(OptionId key) { + auto option = opt(key); + return (option)? option->get() : false; + } + + float getProgrssMin(OptionId key) { + auto option = opt(key); + return (option)? option->getMin() : 0.f; + } + + float getProgrssMax(OptionId key) { + auto option = opt(key); + return (option)? option->getMax() : 0.f; + } + + Option* getOpt(OptionId id) { return m_options[id]; } + + void load(); + void save(); + void set(OptionId key, int value); + void set(OptionId key, float value); + void set(OptionId key, const std::string& value); + void setOptionsFilePath(const std::string& path); + void toggle(OptionId key); + + void notifyOptionUpdate(OptionId key, bool value); + void notifyOptionUpdate(OptionId key, float value); + void notifyOptionUpdate(OptionId key, int value); + void notifyOptionUpdate(OptionId key, const std::string& value) {} + +private: + template + T* opt(OptionId key) { + if (m_options[key] == nullptr) return nullptr; + return dynamic_cast(m_options[key]); + } + + std::array m_options; + OptionsFile optionsFile; + + MinecraftClient& minecraft; +}; + diff --git a/src/client/OptionsFile.h b/src/client/OptionsFile.h index b2464a0..4e44a32 100755 --- a/src/client/OptionsFile.h +++ b/src/client/OptionsFile.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT__OptionsFile_H__ -#define NET_MINECRAFT_CLIENT__OptionsFile_H__ - -//package net.minecraft.client; -#include -#include -typedef std::vector StringVector; -class OptionsFile -{ -public: - OptionsFile(); - void save(const StringVector& settings); - StringVector getOptionStrings(); - void setOptionsPath(const std::string& path); - std::string getOptionsPath() const; - -private: - std::string settingsPath; -}; - -#endif /* NET_MINECRAFT_CLIENT__OptionsFile_H__ */ +#pragma once + +//package net.minecraft.client; +#include +#include +typedef std::vector StringVector; +class OptionsFile +{ +public: + OptionsFile(); + void save(const StringVector& settings); + StringVector getOptionStrings(); + void setOptionsPath(const std::string& path); + std::string getOptionsPath() const; + +private: + std::string settingsPath; +}; + diff --git a/src/client/Timer.h b/src/client/Timer.h index cb7a928..da51ef4 100755 --- a/src/client/Timer.h +++ b/src/client/Timer.h @@ -1,124 +1,122 @@ -#ifndef NET_MINECRAFT_CLIENT__Timer_H__ -#define NET_MINECRAFT_CLIENT__Timer_H__ - -//package net.minecraft.client; -#include "../platform/time.h" - -class Timer -{ -public: - Timer(float ticksPerSecond) - : ticksPerSecond(ticksPerSecond), - adjustTime(1.0f), - timeScale(1.0f), - passedTime(0) - { - lastMs = getTimeMs(); - lastMsSysTime = lastMs; - lastTime = lastMs / 1000.0f; - } - - void advanceTime() { - long nowMs = getTimeMs(); - long passedMs = nowMs - lastMs; - long msSysTime = nowMs;//System.nanoTime() / 1000000; - - if (passedMs > 1000) { - long passedMsSysTime = msSysTime - lastMsSysTime; - if (passedMsSysTime == 0) - passedMs = passedMsSysTime = 1; - - float adjustTimeT = passedMs / (float) passedMsSysTime; - adjustTime += (adjustTimeT - adjustTime) * 0.2f; - - lastMs = nowMs; - lastMsSysTime = msSysTime; - } - if (passedMs < 0) { - lastMs = nowMs; - lastMsSysTime = msSysTime; - } - - float now = msSysTime / 1000.0f; - float passedSeconds = (now - lastTime) * adjustTime; - lastTime = now; - - if (passedSeconds < 0) passedSeconds = 0; - if (passedSeconds > 1) passedSeconds = 1; - //LOGI("passed s: %f\n", passedSeconds); - - passedTime += passedSeconds * timeScale * ticksPerSecond; - - ticks = (int) passedTime; - passedTime -= ticks; - if (ticks > MAX_TICKS_PER_UPDATE) ticks = MAX_TICKS_PER_UPDATE; - a = passedTime; - } - - /** - * Advances time the max number of ticks per second. - */ - void advanceTimeQuickly() { - - float passedSeconds = (float) MAX_TICKS_PER_UPDATE / (float) ticksPerSecond; - - passedTime += passedSeconds * timeScale * ticksPerSecond; - ticks = (int) passedTime; - passedTime -= ticks; - a = passedTime; - - lastMs = getTimeMs();//System.currentTimeMillis(); - lastMsSysTime = lastMs; - } - - void skipTime() { - long nowMs = getTimeMs();//System.currentTimeMillis(); - long passedMs = nowMs - lastMs; - long msSysTime = nowMs;//System.nanoTime() / 1000000; - - if (passedMs > 1000) { - long passedMsSysTime = msSysTime - lastMsSysTime; - if (passedMsSysTime == 0) - passedMs = passedMsSysTime = 1; - - float adjustTimeT = passedMs / (float) passedMsSysTime; - adjustTime += (adjustTimeT - adjustTime) * 0.2f; - - lastMs = nowMs; - lastMsSysTime = msSysTime; - } - if (passedMs < 0) { - lastMs = nowMs; - lastMsSysTime = msSysTime; - } - - float now = msSysTime / 1000.0f; - float passedSeconds = (now - lastTime) * adjustTime; - lastTime = now; - - if (passedSeconds < 0) passedSeconds = 0; - if (passedSeconds > 1) passedSeconds = 1; - - passedTime += passedSeconds * timeScale * ticksPerSecond; - - ticks = (int) 0; - if (ticks > MAX_TICKS_PER_UPDATE) ticks = MAX_TICKS_PER_UPDATE; - passedTime -= ticks; - } - -public: - float ticksPerSecond; - int ticks; - float a; - float timeScale; - float passedTime; -private: - static const int MAX_TICKS_PER_UPDATE = 10; - - float lastTime; - long lastMs; - long lastMsSysTime; - float adjustTime; -}; - -#endif /*NET_MINECRAFT_CLIENT__Timer_H__*/ +#pragma once + +//package net.minecraft.client; +#include "../platform/time.h" + +class Timer +{ +public: + Timer(float ticksPerSecond) + : ticksPerSecond(ticksPerSecond), + adjustTime(1.0f), + timeScale(1.0f), + passedTime(0) + { + lastMs = getTimeMs(); + lastMsSysTime = lastMs; + lastTime = lastMs / 1000.0f; + } + + void advanceTime() { + long nowMs = getTimeMs(); + long passedMs = nowMs - lastMs; + long msSysTime = nowMs;//System.nanoTime() / 1000000; + + if (passedMs > 1000) { + long passedMsSysTime = msSysTime - lastMsSysTime; + if (passedMsSysTime == 0) + passedMs = passedMsSysTime = 1; + + float adjustTimeT = passedMs / (float) passedMsSysTime; + adjustTime += (adjustTimeT - adjustTime) * 0.2f; + + lastMs = nowMs; + lastMsSysTime = msSysTime; + } + if (passedMs < 0) { + lastMs = nowMs; + lastMsSysTime = msSysTime; + } + + float now = msSysTime / 1000.0f; + float passedSeconds = (now - lastTime) * adjustTime; + lastTime = now; + + if (passedSeconds < 0) passedSeconds = 0; + if (passedSeconds > 1) passedSeconds = 1; + //LOGI("passed s: %f\n", passedSeconds); + + passedTime += passedSeconds * timeScale * ticksPerSecond; + + ticks = (int) passedTime; + passedTime -= ticks; + if (ticks > MAX_TICKS_PER_UPDATE) ticks = MAX_TICKS_PER_UPDATE; + a = passedTime; + } + + /** + * Advances time the max number of ticks per second. + */ + void advanceTimeQuickly() { + + float passedSeconds = (float) MAX_TICKS_PER_UPDATE / (float) ticksPerSecond; + + passedTime += passedSeconds * timeScale * ticksPerSecond; + ticks = (int) passedTime; + passedTime -= ticks; + a = passedTime; + + lastMs = getTimeMs();//System.currentTimeMillis(); + lastMsSysTime = lastMs; + } + + void skipTime() { + long nowMs = getTimeMs();//System.currentTimeMillis(); + long passedMs = nowMs - lastMs; + long msSysTime = nowMs;//System.nanoTime() / 1000000; + + if (passedMs > 1000) { + long passedMsSysTime = msSysTime - lastMsSysTime; + if (passedMsSysTime == 0) + passedMs = passedMsSysTime = 1; + + float adjustTimeT = passedMs / (float) passedMsSysTime; + adjustTime += (adjustTimeT - adjustTime) * 0.2f; + + lastMs = nowMs; + lastMsSysTime = msSysTime; + } + if (passedMs < 0) { + lastMs = nowMs; + lastMsSysTime = msSysTime; + } + + float now = msSysTime / 1000.0f; + float passedSeconds = (now - lastTime) * adjustTime; + lastTime = now; + + if (passedSeconds < 0) passedSeconds = 0; + if (passedSeconds > 1) passedSeconds = 1; + + passedTime += passedSeconds * timeScale * ticksPerSecond; + + ticks = (int) 0; + if (ticks > MAX_TICKS_PER_UPDATE) ticks = MAX_TICKS_PER_UPDATE; + passedTime -= ticks; + } + +public: + float ticksPerSecond; + int ticks; + float a; + float timeScale; + float passedTime; +private: + static const int MAX_TICKS_PER_UPDATE = 10; + + float lastTime; + long lastMs; + long lastMsSysTime; + float adjustTime; +}; + diff --git a/src/client/gui/Font.h b/src/client/gui/Font.h index 69a0106..6b70ae5 100755 --- a/src/client/gui/Font.h +++ b/src/client/gui/Font.h @@ -1,63 +1,61 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__Font_H__ -#define NET_MINECRAFT_CLIENT_GUI__Font_H__ - -//package net.minecraft.client.gui; - -#include -#include - -#include "../renderer/gles.h" - -class Textures; -class Options; - -class Font -{ -public: - Font(Options* options, const std::string& name, Textures* textures); - //Font(Options* options, const std::string& name, Textures* textures, int imgW, int imgH, int x, int y, int cols, int rows, unsigned char charOffset); - - void init(Options* options); - void onGraphicsReset(); - - void draw(const char* str, float x, float y, int color); - void draw(const std::string& str, float x, float y, int color); - void draw(const char* str, float x, float y, int color, bool darken); - void draw(const std::string& str, float x, float y, int color, bool darken); - void drawShadow(const std::string& str, float x, float y, int color); - void drawShadow(const char* str, float x, float y, int color); - void drawWordWrap(const std::string& str, float x, float y, float w, int col); - - int width(const std::string& str); - int height(const std::string& str); - - static std::string sanitize(const std::string& str); -private: - void buildChar(unsigned char i, float x = 0, float y = 0); - void drawSlow(const std::string& str, float x, float y, int color, bool darken = false); - void drawSlow(const char* str, float x, float y, int color, bool darken = false); -public: - int fontTexture; - int lineHeight; - static const int DefaultLineHeight = 10; -private: - int charWidths[256]; - float fcharWidths[256]; - int listPos; - - int index; - int count; - GLuint lists[1024]; - - std::string fontName; - Textures* _textures; - - Options* options; - - int _x, _y; - int _cols; - int _rows; - unsigned char _charOffset; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI__Font_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include +#include + +#include "../renderer/gles.h" + +class Textures; +class Options; + +class Font +{ +public: + Font(Options* options, const std::string& name, Textures* textures); + //Font(Options* options, const std::string& name, Textures* textures, int imgW, int imgH, int x, int y, int cols, int rows, unsigned char charOffset); + + void init(Options* options); + void onGraphicsReset(); + + void draw(const char* str, float x, float y, int color); + void draw(const std::string& str, float x, float y, int color); + void draw(const char* str, float x, float y, int color, bool darken); + void draw(const std::string& str, float x, float y, int color, bool darken); + void drawShadow(const std::string& str, float x, float y, int color); + void drawShadow(const char* str, float x, float y, int color); + void drawWordWrap(const std::string& str, float x, float y, float w, int col); + + int width(const std::string& str); + int height(const std::string& str); + + static std::string sanitize(const std::string& str); +private: + void buildChar(unsigned char i, float x = 0, float y = 0); + void drawSlow(const std::string& str, float x, float y, int color, bool darken = false); + void drawSlow(const char* str, float x, float y, int color, bool darken = false); +public: + int fontTexture; + int lineHeight; + static const int DefaultLineHeight = 10; +private: + int charWidths[256]; + float fcharWidths[256]; + int listPos; + + int index; + int count; + GLuint lists[1024]; + + std::string fontName; + Textures* _textures; + + Options* options; + + int _x, _y; + int _cols; + int _rows; + unsigned char _charOffset; +}; + diff --git a/src/client/gui/Gui.h b/src/client/gui/Gui.h index 24c6741..b5084ee 100755 --- a/src/client/gui/Gui.h +++ b/src/client/gui/Gui.h @@ -1,133 +1,131 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__Gui_H__ -#define NET_MINECRAFT_CLIENT_GUI__Gui_H__ - -//package net.minecraft.client.gui; - -#include "GuiComponent.h" -#include "Font.h" -#include "../player/input/touchscreen/TouchAreaModel.h" -#include "../renderer/RenderChunk.h" -#include "../../util/Random.h" -#include "../IConfigListener.h" - -class MinecraftClient; -class ItemInstance; -class Textures; -class Tesselator; -struct IntRectangle; - -struct GuiMessage -{ - std::string message; - int ticks; -}; - -typedef std::vector GuiMessageList; - -class Gui: public GuiComponent, IConfigListener -{ -public: - Gui(MinecraftClient& minecraft); - ~Gui(); - - int getSlotIdAt(int x, int y); - void flashSlot(int slotId); - bool isInside(int x, int y); - RectangleArea getRectangleArea(int extendSide); - void getSlotPos(int slot, int& posX, int& posY); - int getNumSlots(); - - void handleClick(int button, int x, int y); - void handleKeyPressed( int key ); - void scrollChat(int delta); - - void tick(); - void render(float a, bool mouseFree, int xMouse, int yMouse); - - void renderToolBar( float a, int ySlot, const int screenWidth ); - - void renderChatMessages( const int screenHeight, unsigned int max, bool isChatting, Font* font ); - - // draw a string containing simple [color]...[/color] tags; color names are matched - // case-insensitively and default to white. alpha is applied to each segment. - // draw tagged string (ignores simple [color]…[/color] tags) - static void drawColoredString(Font* font, const std::string& text, float x, float y, int alpha); - static float getColoredWidth(Font* font, const std::string& text); - - void renderOnSelectItemNameText( const int screenWidth, Font* font, int ySlot ); - - void renderSleepAnimation( const int screenWidth, const int screenHeight ); - - void renderBubbles(); - void renderHearts(); - void renderDebugInfo(); - void renderPlayerList(Font* font, int screenWidth, int screenHeight); - - void renderProgressIndicator( const bool isTouchInterface, const int screenWidth, const int screenHeight, float a ); - - void addMessage(const std::string& string); - void clearMessages(); - void postError(int errCode); - - void onGraphicsReset(); - void inventoryUpdated(); - - void setNowPlaying(const std::string& string); - void displayClientMessage(const std::string& messageId); - void renderSlotText(const ItemInstance* item, float x, float y, bool hasFinite, bool shadow); - void texturesLoaded( Textures* textures ); - - void onConfigChanged(const Config& config); - void onLevelGenerated(); - - void setScissorRect(const IntRectangle& rect); - - static float floorAlignToScreenPixel(float); - static int itemCountItoa(char* buf, int count); -private: - void renderVignette(float br, int w, int h); - void renderSlot(int slot, int x, int y, float a); - void tickItemDrop(); - float cubeSmoothStep(float percentage, float min, float max); -public: - float progress = 0.f; - std::string selectedName; - static float InvGuiScale; - static float GuiScale; - -private: - //ItemRenderer itemRenderer; - GuiMessageList guiMessages; - int chatScrollOffset = 0; - Random random; - - MinecraftClient& minecraft; - int tickCount = 0; - float itemNameOverlayTime = 2; - std::string overlayMessageString; - int overlayMessageTime = 0; - bool animateOverlayMessageColor = false; - - float tbr = 1.f; - - RenderChunk _inventoryRc; - bool _inventoryNeedsUpdate = true; - - int _flashSlotId = -1; - float _flashSlotStartTime = -1; - - Font* _slotFont = nullptr; - int _numSlots = 4; - - RenderChunk rcFeedbackOuter; - RenderChunk rcFeedbackInner; - - // For dropping - static const float DropTicks; - float _currentDropTicks = -1; - int _currentDropSlot = -1; - - bool _openInventorySlot; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI__Gui_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include "GuiComponent.h" +#include "Font.h" +#include "../player/input/touchscreen/TouchAreaModel.h" +#include "../renderer/RenderChunk.h" +#include "../../util/Random.h" +#include "../IConfigListener.h" + +class MinecraftClient; +class ItemInstance; +class Textures; +class Tesselator; +struct IntRectangle; + +struct GuiMessage +{ + std::string message; + int ticks; +}; + +typedef std::vector GuiMessageList; + +class Gui: public GuiComponent, IConfigListener +{ +public: + Gui(MinecraftClient& minecraft); + ~Gui(); + + int getSlotIdAt(int x, int y); + void flashSlot(int slotId); + bool isInside(int x, int y); + RectangleArea getRectangleArea(int extendSide); + void getSlotPos(int slot, int& posX, int& posY); + int getNumSlots(); + + void handleClick(int button, int x, int y); + void handleKeyPressed( int key ); + void scrollChat(int delta); + + void tick(); + void render(float a, bool mouseFree, int xMouse, int yMouse); + + void renderToolBar( float a, int ySlot, const int screenWidth ); + + void renderChatMessages( const int screenHeight, unsigned int max, bool isChatting, Font* font ); + + // draw a string containing simple [color]...[/color] tags; color names are matched + // case-insensitively and default to white. alpha is applied to each segment. + // draw tagged string (ignores simple [color]…[/color] tags) + static void drawColoredString(Font* font, const std::string& text, float x, float y, int alpha); + static float getColoredWidth(Font* font, const std::string& text); + + void renderOnSelectItemNameText( const int screenWidth, Font* font, int ySlot ); + + void renderSleepAnimation( const int screenWidth, const int screenHeight ); + + void renderBubbles(); + void renderHearts(); + void renderDebugInfo(); + void renderPlayerList(Font* font, int screenWidth, int screenHeight); + + void renderProgressIndicator( const bool isTouchInterface, const int screenWidth, const int screenHeight, float a ); + + void addMessage(const std::string& string); + void clearMessages(); + void postError(int errCode); + + void onGraphicsReset(); + void inventoryUpdated(); + + void setNowPlaying(const std::string& string); + void displayClientMessage(const std::string& messageId); + void renderSlotText(const ItemInstance* item, float x, float y, bool hasFinite, bool shadow); + void texturesLoaded( Textures* textures ); + + void onConfigChanged(const Config& config); + void onLevelGenerated(); + + void setScissorRect(const IntRectangle& rect); + + static float floorAlignToScreenPixel(float); + static int itemCountItoa(char* buf, int count); +private: + void renderVignette(float br, int w, int h); + void renderSlot(int slot, int x, int y, float a); + void tickItemDrop(); + float cubeSmoothStep(float percentage, float min, float max); +public: + float progress = 0.f; + std::string selectedName; + static float InvGuiScale; + static float GuiScale; + +private: + //ItemRenderer itemRenderer; + GuiMessageList guiMessages; + int chatScrollOffset = 0; + Random random; + + MinecraftClient& minecraft; + int tickCount = 0; + float itemNameOverlayTime = 2; + std::string overlayMessageString; + int overlayMessageTime = 0; + bool animateOverlayMessageColor = false; + + float tbr = 1.f; + + RenderChunk _inventoryRc; + bool _inventoryNeedsUpdate = true; + + int _flashSlotId = -1; + float _flashSlotStartTime = -1; + + Font* _slotFont = nullptr; + int _numSlots = 4; + + RenderChunk rcFeedbackOuter; + RenderChunk rcFeedbackInner; + + // For dropping + static const float DropTicks; + float _currentDropTicks = -1; + int _currentDropSlot = -1; + + bool _openInventorySlot; +}; + diff --git a/src/client/gui/GuiComponent.h b/src/client/gui/GuiComponent.h index 1b8c468..d64a572 100755 --- a/src/client/gui/GuiComponent.h +++ b/src/client/gui/GuiComponent.h @@ -1,34 +1,32 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__GuiComponent_H__ -#define NET_MINECRAFT_CLIENT_GUI__GuiComponent_H__ - -//package net.minecraft.client.gui; - -#include -class Font; -class Minecraft; - -class GuiComponent -{ -public: - GuiComponent(); - virtual ~GuiComponent(); - - void drawString(Font* font, const std::string& str, int x, int y, int color); - void drawCenteredString(Font* font, const std::string& str, int x, int y, int color); - - void blit(int x, int y, int sx, int sy, int w, int h, int sw=0, int sh=0); - void blit(float x, float y, int sx, int sy, float w, float h, int sw=0, int sh=0); - -protected: - void fill(int x0, int y0, int x1, int y1, int col); - void fill(float x0, float y0, float x1, float y1, int col); - void fillGradient(int x0, int y0, int x1, int y1, int col1, int col2); - void fillGradient(float x0, float y0, float x1, float y1, int col1, int col2); - void fillHorizontalGradient(int x0, int y0, int x1, int y1, int col1, int col2); - void fillHorizontalGradient(float x0, float y0, float x1, float y1, int col1, int col2); - - float blitOffset; - -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI__GuiComponent_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include +class Font; +class Minecraft; + +class GuiComponent +{ +public: + GuiComponent(); + virtual ~GuiComponent(); + + void drawString(Font* font, const std::string& str, int x, int y, int color); + void drawCenteredString(Font* font, const std::string& str, int x, int y, int color); + + void blit(int x, int y, int sx, int sy, int w, int h, int sw=0, int sh=0); + void blit(float x, float y, int sx, int sy, float w, float h, int sw=0, int sh=0); + +protected: + void fill(int x0, int y0, int x1, int y1, int col); + void fill(float x0, float y0, float x1, float y1, int col); + void fillGradient(int x0, int y0, int x1, int y1, int col1, int col2); + void fillGradient(float x0, float y0, float x1, float y1, int col1, int col2); + void fillHorizontalGradient(int x0, int y0, int x1, int y1, int col1, int col2); + void fillHorizontalGradient(float x0, float y0, float x1, float y1, int col1, int col2); + + float blitOffset; + +}; + diff --git a/src/client/gui/Screen.h b/src/client/gui/Screen.h index be44d5c..c0cda99 100755 --- a/src/client/gui/Screen.h +++ b/src/client/gui/Screen.h @@ -1,83 +1,81 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__Screen_H__ -#define NET_MINECRAFT_CLIENT_GUI__Screen_H__ - -//package net.minecraft.client.gui; - -#include -#include "GuiComponent.h" - -class Font; -class Minecraft; -class Button; -class TextBox; -struct IntRectangle; - -class Screen: public GuiComponent -{ -public: - Screen(); - - virtual void render(int xm, int ym, float a); - - void init(Minecraft* minecraft, int width, int height); - virtual void init(); - - void setSize(int width, int height); - virtual void setupPositions() {}; - - virtual void updateEvents(); - virtual void mouseEvent(); - virtual void keyboardEvent(); - virtual void keyboardTextEvent(); - virtual bool handleBackEvent(bool isDown); - - virtual void tick() {} - - virtual void removed() {} - - virtual void renderBackground(); - virtual void renderBackground(int vo); - virtual void renderDirtBackground(int vo); - // query - virtual bool renderGameBehind(); - virtual bool hasClippingArea(IntRectangle& out); - - virtual bool isPauseScreen(); - virtual bool isErrorScreen(); - virtual bool isInGameScreen(); - virtual bool closeOnPlayerHurt(); - - virtual void confirmResult(bool result, int id) {} - virtual void lostFocus(); - virtual void toGUICoordinate(int& x, int& y); -protected: - void updateTabButtonSelection(); - - virtual void buttonClicked(Button* button) {} - virtual void mouseClicked(int x, int y, int buttonNum); - virtual void mouseReleased(int x, int y, int buttonNum); - - // mouse wheel movement (dx/dy are wheel deltas, xm/ym are GUI coords) - virtual void mouseWheel(int dx, int dy, int xm, int ym) {} - - virtual void keyPressed(int eventKey); - virtual void charPressed(char inputChar); -public: - int width; - int height; - bool passEvents; - //GuiParticles* particles; -protected: - Minecraft* minecraft; - std::vector buttons; - std::vector textBoxes; - - std::vector tabButtons; - int tabButtonIndex; - - Font* font; -private: - Button* clickedButton; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI__Screen_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include +#include "GuiComponent.h" + +class Font; +class Minecraft; +class Button; +class TextBox; +struct IntRectangle; + +class Screen: public GuiComponent +{ +public: + Screen(); + + virtual void render(int xm, int ym, float a); + + void init(Minecraft* minecraft, int width, int height); + virtual void init(); + + void setSize(int width, int height); + virtual void setupPositions() {}; + + virtual void updateEvents(); + virtual void mouseEvent(); + virtual void keyboardEvent(); + virtual void keyboardTextEvent(); + virtual bool handleBackEvent(bool isDown); + + virtual void tick() {} + + virtual void removed() {} + + virtual void renderBackground(); + virtual void renderBackground(int vo); + virtual void renderDirtBackground(int vo); + // query + virtual bool renderGameBehind(); + virtual bool hasClippingArea(IntRectangle& out); + + virtual bool isPauseScreen(); + virtual bool isErrorScreen(); + virtual bool isInGameScreen(); + virtual bool closeOnPlayerHurt(); + + virtual void confirmResult(bool result, int id) {} + virtual void lostFocus(); + virtual void toGUICoordinate(int& x, int& y); +protected: + void updateTabButtonSelection(); + + virtual void buttonClicked(Button* button) {} + virtual void mouseClicked(int x, int y, int buttonNum); + virtual void mouseReleased(int x, int y, int buttonNum); + + // mouse wheel movement (dx/dy are wheel deltas, xm/ym are GUI coords) + virtual void mouseWheel(int dx, int dy, int xm, int ym) {} + + virtual void keyPressed(int eventKey); + virtual void charPressed(char inputChar); +public: + int width; + int height; + bool passEvents; + //GuiParticles* particles; +protected: + Minecraft* minecraft; + std::vector buttons; + std::vector textBoxes; + + std::vector tabButtons; + int tabButtonIndex; + + Font* font; +private: + Button* clickedButton; +}; + diff --git a/src/client/gui/TweenData.h b/src/client/gui/TweenData.h index 0d63b8e..cf3516a 100755 --- a/src/client/gui/TweenData.h +++ b/src/client/gui/TweenData.h @@ -1,11 +1,9 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__TweenData_H__ -#define NET_MINECRAFT_CLIENT_GUI__TweenData_H__ - -typedef struct TweenData { - float cur; - float dur; - float start; - float stop; -} TweenData; - -#endif /*NET_MINECRAFT_CLIENT_GUI__TweenData_H__*/ +#pragma once + +typedef struct TweenData { + float cur; + float dur; + float start; + float stop; +} TweenData; + diff --git a/src/client/gui/components/Button.h b/src/client/gui/components/Button.h index 1b93ddc..c06b0fe 100755 --- a/src/client/gui/components/Button.h +++ b/src/client/gui/components/Button.h @@ -1,80 +1,78 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__Button_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__Button_H__ - -//package net.minecraft.client.gui; - -#include -#include "GuiElement.h" -#include "../../Options.h" - -class Font; -class Minecraft; - -class Button: public GuiElement -{ -public: - Button(int id, const std::string& msg); - Button(int id, int x, int y, const std::string& msg); - Button(int id, int x, int y, int w, int h, const std::string& msg); - virtual ~Button() {} - virtual void render(Minecraft* minecraft, int xm, int ym); - - virtual bool clicked(Minecraft* minecraft, int mx, int my); - virtual void released(int mx, int my); - virtual void setPressed(); - - bool isInside(int xm, int ym); -protected: - virtual int getYImage(bool hovered); - virtual void renderBg(Minecraft* minecraft, int xm, int ym); - - virtual void renderFace(Minecraft* minecraft, int xm, int ym); - bool hovered(Minecraft* minecraft, int xm, int ym); -public: - std::string msg; - int id; - - bool selected; -protected: - bool _currentlyDown; -}; - -// @note: A bit backwards, but this is a button that -// only reacts to clicks, but isn't rendered. -class BlankButton: public Button -{ - typedef Button super; -public: - BlankButton(int id); - BlankButton(int id, int x, int y, int w, int h); -}; - - -namespace Touch { -class TButton: public Button -{ - typedef Button super; -public: - TButton(int id, const std::string& msg); - TButton(int id, int x, int y, const std::string& msg); - TButton(int id, int x, int y, int w, int h, const std::string& msg); -protected: - virtual void renderBg(Minecraft* minecraft, int xm, int ym); -}; - -// "Header" in Touchscreen mode -class THeader: public Button { - typedef Button super; -public: - THeader(int id, const std::string& msg); - THeader(int id, int x, int y, const std::string& msg); - THeader(int id, int x, int y, int w, int h, const std::string& msg); -protected: - virtual void renderBg(Minecraft* minecraft, int xm, int ym); - void render( Minecraft* minecraft, int xm, int ym ); -public: - int xText; -}; -} - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__Button_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include +#include "GuiElement.h" +#include "../../Options.h" + +class Font; +class Minecraft; + +class Button: public GuiElement +{ +public: + Button(int id, const std::string& msg); + Button(int id, int x, int y, const std::string& msg); + Button(int id, int x, int y, int w, int h, const std::string& msg); + virtual ~Button() {} + virtual void render(Minecraft* minecraft, int xm, int ym); + + virtual bool clicked(Minecraft* minecraft, int mx, int my); + virtual void released(int mx, int my); + virtual void setPressed(); + + bool isInside(int xm, int ym); +protected: + virtual int getYImage(bool hovered); + virtual void renderBg(Minecraft* minecraft, int xm, int ym); + + virtual void renderFace(Minecraft* minecraft, int xm, int ym); + bool hovered(Minecraft* minecraft, int xm, int ym); +public: + std::string msg; + int id; + + bool selected; +protected: + bool _currentlyDown; +}; + +// @note: A bit backwards, but this is a button that +// only reacts to clicks, but isn't rendered. +class BlankButton: public Button +{ + typedef Button super; +public: + BlankButton(int id); + BlankButton(int id, int x, int y, int w, int h); +}; + + +namespace Touch { +class TButton: public Button +{ + typedef Button super; +public: + TButton(int id, const std::string& msg); + TButton(int id, int x, int y, const std::string& msg); + TButton(int id, int x, int y, int w, int h, const std::string& msg); +protected: + virtual void renderBg(Minecraft* minecraft, int xm, int ym); +}; + +// "Header" in Touchscreen mode +class THeader: public Button { + typedef Button super; +public: + THeader(int id, const std::string& msg); + THeader(int id, int x, int y, const std::string& msg); + THeader(int id, int x, int y, int w, int h, const std::string& msg); +protected: + virtual void renderBg(Minecraft* minecraft, int xm, int ym); + void render( Minecraft* minecraft, int xm, int ym ); +public: + int xText; +}; +} + diff --git a/src/client/gui/components/GButton.h b/src/client/gui/components/GButton.h index 8e9474e..758b4d3 100755 --- a/src/client/gui/components/GButton.h +++ b/src/client/gui/components/GButton.h @@ -1,55 +1,53 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__GButton_H__ -#define NET_MINECRAFT_CLIENT_GUI__GButton_H__ -#include "Button.h" - -class GButton: public Button { - typedef Button super; -public: - static const int LayerDefault = 1; - static const int LayerSelected = 2; - static const int LayerMax = 4; - - GButton(int id) - : super(id, "") - {} - ~GButton() { - for (unsigned int i = 0; i < layers.size(); ++i) { - delete layers[i].first; - } - } - - void addElement(int layerId, GuiElement* e) { - if (!e || layerId < 0 || layerId >= LayerMax) { - LOGE("Error @ GButton::element : Trying to add element %p at layer: %d\n", e, layerId); - return; - } - layers.push_back(std::make_pair(e, layerId)); - } - - void render( Minecraft* minecraft, int xm, int ym ) - { - if (!visible) return; - - bool isHovered = minecraft->isTouchscreen()? - (_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height): false; - - int layer = isHovered? LayerSelected : LayerDefault; - if (layer < 0) return; - - Tesselator& t = Tesselator::instance; - t.addOffset((float)x, (float)y, 0); - - for (unsigned int i = 0; i < layers.size(); ++i) { - if ((layers[i].second & layer) != 0) - layers[i].first->render(minecraft, 0, 0); - } - - t.addOffset((float)-x, (float)-y, 0); - } - -private: - std::vector > layers; -}; - - -#endif /*NET_MINECRAFT_CLIENT_GUI__GButton_H__*/ +#pragma once +#include "Button.h" + +class GButton: public Button { + typedef Button super; +public: + static const int LayerDefault = 1; + static const int LayerSelected = 2; + static const int LayerMax = 4; + + GButton(int id) + : super(id, "") + {} + ~GButton() { + for (unsigned int i = 0; i < layers.size(); ++i) { + delete layers[i].first; + } + } + + void addElement(int layerId, GuiElement* e) { + if (!e || layerId < 0 || layerId >= LayerMax) { + LOGE("Error @ GButton::element : Trying to add element %p at layer: %d\n", e, layerId); + return; + } + layers.push_back(std::make_pair(e, layerId)); + } + + void render( Minecraft* minecraft, int xm, int ym ) + { + if (!visible) return; + + bool isHovered = minecraft->isTouchscreen()? + (_currentlyDown && xm >= x && ym >= y && xm < x + width && ym < y + height): false; + + int layer = isHovered? LayerSelected : LayerDefault; + if (layer < 0) return; + + Tesselator& t = Tesselator::instance; + t.addOffset((float)x, (float)y, 0); + + for (unsigned int i = 0; i < layers.size(); ++i) { + if ((layers[i].second & layer) != 0) + layers[i].first->render(minecraft, 0, 0); + } + + t.addOffset((float)-x, (float)-y, 0); + } + +private: + std::vector > layers; +}; + + diff --git a/src/client/gui/components/GuiElement.h b/src/client/gui/components/GuiElement.h index f0a0a33..4df2b35 100755 --- a/src/client/gui/components/GuiElement.h +++ b/src/client/gui/components/GuiElement.h @@ -1,34 +1,32 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__GuiElement_H__ -#define NET_MINECRAFT_CLIENT_GUI__GuiElement_H__ -#include "../GuiComponent.h" - -class Tesselator; -class Minecraft; - -class GuiElement : public GuiComponent { -public: - GuiElement(bool active=false, bool visible=true, int x = 0, int y = 0, int width=24, int height=24); - virtual ~GuiElement() {} - - virtual void tick(Minecraft* minecraft) {} - virtual void render(Minecraft* minecraft, int xm, int ym) { } - virtual void setupPositions() {} - - virtual void mouseClicked(Minecraft* minecraft, int x, int y, int buttonNum) {} - virtual void mouseReleased(Minecraft* minecraft, int x, int y, int buttonNum) {} - virtual void keyPressed(Minecraft* minecraft, int key) {} - virtual void charPressed(Minecraft* minecraft, char key) {} - - virtual bool pointInside(int x, int y); - - void setVisible(bool visible); - - bool active; - bool visible; - int x; - int y; - int width; - int height; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI__GuiElement_H__*/ +#pragma once +#include "../GuiComponent.h" + +class Tesselator; +class Minecraft; + +class GuiElement : public GuiComponent { +public: + GuiElement(bool active=false, bool visible=true, int x = 0, int y = 0, int width=24, int height=24); + virtual ~GuiElement() {} + + virtual void tick(Minecraft* minecraft) {} + virtual void render(Minecraft* minecraft, int xm, int ym) { } + virtual void setupPositions() {} + + virtual void mouseClicked(Minecraft* minecraft, int x, int y, int buttonNum) {} + virtual void mouseReleased(Minecraft* minecraft, int x, int y, int buttonNum) {} + virtual void keyPressed(Minecraft* minecraft, int key) {} + virtual void charPressed(Minecraft* minecraft, char key) {} + + virtual bool pointInside(int x, int y); + + void setVisible(bool visible); + + bool active; + bool visible; + int x; + int y; + int width; + int height; +}; + diff --git a/src/client/gui/components/GuiElementContainer.h b/src/client/gui/components/GuiElementContainer.h index d20f9d3..2808163 100755 --- a/src/client/gui/components/GuiElementContainer.h +++ b/src/client/gui/components/GuiElementContainer.h @@ -1,28 +1,26 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__GuiElementContainer_H__ -#define NET_MINECRAFT_CLIENT_GUI__GuiElementContainer_H__ -#include "GuiElement.h" -#include -class Tesselator; -class Minecraft; - -class GuiElementContainer : public GuiElement { -public: - GuiElementContainer(bool active=false, bool visible=true, int x = 0, int y = 0, int width=24, int height=24); - virtual ~GuiElementContainer(); - virtual void render(Minecraft* minecraft, int xm, int ym); - virtual void setupPositions(); - virtual void addChild(GuiElement* element); - virtual void removeChild(GuiElement* element); - - virtual void tick( Minecraft* minecraft ); - - virtual void mouseClicked( Minecraft* minecraft, int x, int y, int buttonNum ); - virtual void mouseReleased( Minecraft* minecraft, int x, int y, int buttonNum ); - virtual void keyPressed(Minecraft* minecraft, int key); - virtual void charPressed(Minecraft* minecraft, char key); - -protected: - std::vector children; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI__GuiElementContainer_H__*/ +#pragma once +#include "GuiElement.h" +#include +class Tesselator; +class Minecraft; + +class GuiElementContainer : public GuiElement { +public: + GuiElementContainer(bool active=false, bool visible=true, int x = 0, int y = 0, int width=24, int height=24); + virtual ~GuiElementContainer(); + virtual void render(Minecraft* minecraft, int xm, int ym); + virtual void setupPositions(); + virtual void addChild(GuiElement* element); + virtual void removeChild(GuiElement* element); + + virtual void tick( Minecraft* minecraft ); + + virtual void mouseClicked( Minecraft* minecraft, int x, int y, int buttonNum ); + virtual void mouseReleased( Minecraft* minecraft, int x, int y, int buttonNum ); + virtual void keyPressed(Minecraft* minecraft, int key); + virtual void charPressed(Minecraft* minecraft, char key); + +protected: + std::vector children; +}; + diff --git a/src/client/gui/components/ImageButton.h b/src/client/gui/components/ImageButton.h index a1bd777..e0ec9f8 100755 --- a/src/client/gui/components/ImageButton.h +++ b/src/client/gui/components/ImageButton.h @@ -1,97 +1,95 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__ImageButton_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__ImageButton_H__ - -#include "Button.h" - -typedef struct IntRectangle { - IntRectangle() - : x(0), - y(0), - w(1), - h(1) - {} - IntRectangle(int x, int y, int w, int h) - : x(x), - y(y), - w(w), - h(h) - {} - - int x, y; - int w, h; -} IntRectangle; - -typedef struct ImageDef { - ImageDef() - : hasSrc(false), - x(0), - y(0), - width(16), - height(16) - {} - - std::string name; - int x; - int y; - float width; - float height; - - ImageDef& setSrc(const IntRectangle& srcRect) { - hasSrc = true; - src = srcRect; - return *this; - } - IntRectangle* getSrc() { - return hasSrc? &src : NULL; - } -protected: - IntRectangle src; - bool hasSrc; -} ImageDef; - - -class ImageButton: public Button -{ - typedef Button super; -public: - ImageButton(int id, const std::string& msg); - ImageButton(int id, const std::string& msg, const ImageDef& imageDef); - void setImageDef(const ImageDef& imageDef, bool setButtonSize); - - void render(Minecraft* minecraft, int xm, int ym); - void renderBg(Minecraft* minecraft, int xm, int ym) {} - -protected: - virtual void setupDefault(); - virtual bool isSecondImage(bool hovered) { return hovered; } - - ImageDef _imageDef; -public: - bool scaleWhenPressed; -}; - -// -// A toggleable Button -// -class OptionButton: public ImageButton -{ - typedef ImageButton super; -public: - OptionButton(OptionId optId); - - void toggle(Options* options); - void updateImage(Options* options); - - static const int ButtonId = 9999999; -protected: - bool isSecondImage(bool hovered) { return _secondImage; } - - virtual void mouseClicked( Minecraft* minecraft, int x, int y, int buttonNum ); - -private: - OptionId m_optId; - bool _secondImage; -}; - - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__ImageButton_H__*/ +#pragma once + +#include "Button.h" + +typedef struct IntRectangle { + IntRectangle() + : x(0), + y(0), + w(1), + h(1) + {} + IntRectangle(int x, int y, int w, int h) + : x(x), + y(y), + w(w), + h(h) + {} + + int x, y; + int w, h; +} IntRectangle; + +typedef struct ImageDef { + ImageDef() + : hasSrc(false), + x(0), + y(0), + width(16), + height(16) + {} + + std::string name; + int x; + int y; + float width; + float height; + + ImageDef& setSrc(const IntRectangle& srcRect) { + hasSrc = true; + src = srcRect; + return *this; + } + IntRectangle* getSrc() { + return hasSrc? &src : NULL; + } +protected: + IntRectangle src; + bool hasSrc; +} ImageDef; + + +class ImageButton: public Button +{ + typedef Button super; +public: + ImageButton(int id, const std::string& msg); + ImageButton(int id, const std::string& msg, const ImageDef& imageDef); + void setImageDef(const ImageDef& imageDef, bool setButtonSize); + + void render(Minecraft* minecraft, int xm, int ym); + void renderBg(Minecraft* minecraft, int xm, int ym) {} + +protected: + virtual void setupDefault(); + virtual bool isSecondImage(bool hovered) { return hovered; } + + ImageDef _imageDef; +public: + bool scaleWhenPressed; +}; + +// +// A toggleable Button +// +class OptionButton: public ImageButton +{ + typedef ImageButton super; +public: + OptionButton(OptionId optId); + + void toggle(Options* options); + void updateImage(Options* options); + + static const int ButtonId = 9999999; +protected: + bool isSecondImage(bool hovered) { return _secondImage; } + + virtual void mouseClicked( Minecraft* minecraft, int x, int y, int buttonNum ); + +private: + OptionId m_optId; + bool _secondImage; +}; + + diff --git a/src/client/gui/components/InventoryPane.h b/src/client/gui/components/InventoryPane.h index c80f754..22bc79a 100755 --- a/src/client/gui/components/InventoryPane.h +++ b/src/client/gui/components/InventoryPane.h @@ -1,62 +1,60 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__InventoryPane_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__InventoryPane_H__ - -#include "ScrollingPane.h" -#include "ImageButton.h" - -class Minecraft; -class ItemInstance; -class Font; -class IArea; - -namespace Touch { - -class IInventoryPaneCallback; - -class InventoryPane: public ScrollingPane -{ - typedef ScrollingPane super; -public: - InventoryPane(IInventoryPaneCallback* screen, Minecraft* mc, const IntRectangle& rect, int paneWidth, float clickMarginH, int numItems, int itemSize, int itemBorderSize); - ~InventoryPane(); - - void tick(); - void renderBatch( std::vector& item, float alpha ); - bool onSelect( int gridId, bool selected ); - void drawScrollBar( ScrollBar& hScroll ); - - void setRenderDecorations(bool value); - - IntRectangle rect; - int paneWidth; - IArea* _clickArea; - IInventoryPaneCallback* screen; - Minecraft* mc; - - int fillMarginX; - int fillMarginY; - - int markerType; - int markerIndex; - float markerShare; -private: - int lastItemIndex; - int lastItemTicks; - int BorderPixels; - bool renderDecorations; - - IntRectangle bg; -}; - -class IInventoryPaneCallback -{ -public: - virtual ~IInventoryPaneCallback() {} - virtual bool addItem(const InventoryPane* forPane, int index) = 0; - virtual bool isAllowed( int slot ) = 0; - virtual std::vector getItems(const InventoryPane* forPane) = 0; -}; - -} - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__InventoryPane_H__*/ +#pragma once + +#include "ScrollingPane.h" +#include "ImageButton.h" + +class Minecraft; +class ItemInstance; +class Font; +class IArea; + +namespace Touch { + +class IInventoryPaneCallback; + +class InventoryPane: public ScrollingPane +{ + typedef ScrollingPane super; +public: + InventoryPane(IInventoryPaneCallback* screen, Minecraft* mc, const IntRectangle& rect, int paneWidth, float clickMarginH, int numItems, int itemSize, int itemBorderSize); + ~InventoryPane(); + + void tick(); + void renderBatch( std::vector& item, float alpha ); + bool onSelect( int gridId, bool selected ); + void drawScrollBar( ScrollBar& hScroll ); + + void setRenderDecorations(bool value); + + IntRectangle rect; + int paneWidth; + IArea* _clickArea; + IInventoryPaneCallback* screen; + Minecraft* mc; + + int fillMarginX; + int fillMarginY; + + int markerType; + int markerIndex; + float markerShare; +private: + int lastItemIndex; + int lastItemTicks; + int BorderPixels; + bool renderDecorations; + + IntRectangle bg; +}; + +class IInventoryPaneCallback +{ +public: + virtual ~IInventoryPaneCallback() {} + virtual bool addItem(const InventoryPane* forPane, int index) = 0; + virtual bool isAllowed( int slot ) = 0; + virtual std::vector getItems(const InventoryPane* forPane) = 0; +}; + +} + diff --git a/src/client/gui/components/ItemPane.h b/src/client/gui/components/ItemPane.h index ebb0f31..db2dfd9 100755 --- a/src/client/gui/components/ItemPane.h +++ b/src/client/gui/components/ItemPane.h @@ -1,95 +1,93 @@ -#ifndef ITEMPANE_H__ -#define ITEMPANE_H__ - -#include -#include -#include "ScrollingPane.h" -#include "../../../world/item/ItemInstance.h" - -class Font; -class Textures; -class NinePatchLayer; -class Recipe; -class ItemPane; - -class CItem -{ -public: - CItem(const ItemInstance& ins, Recipe* recipe, const std::string& text) - : item(ins), - recipe(recipe), - text(text), - sortText(text), - //maxBuildCount(0), - numBuilt(0), - inventoryCount(0), - _canCraft(false) - { - } - - typedef struct ReqItem { - ReqItem() {} - ReqItem(const ItemInstance& needItem, int has) - : item(needItem), has(has) {} - ItemInstance item; - int has; - bool enough() { return has >= item.count; } - } ReqItem; - - bool canCraft() { - return _canCraft;// || maxBuildCount > 0; - } - void setCanCraft(bool status) { - _canCraft = status; - } - - ItemInstance item; - Recipe* recipe; - std::string text; - std::string sortText; - //int maxBuildCount; - int numBuilt; - int inventoryCount; - std::vector neededItems; -private: - bool _canCraft; -}; - -class IItemPaneCallback -{ -public: - virtual ~IItemPaneCallback() {} - virtual void onItemSelected(const ItemPane* forPane, int index) = 0; - virtual const std::vector& getItems(const ItemPane* forPane) = 0; -}; - -class ItemPane: public ScrollingPane -{ - typedef ScrollingPane super; -public: - ItemPane( IItemPaneCallback* screen, - Textures* textures, - const IntRectangle& rect, - int numItems, - int guiHeight, - int physicalScreenHeight, - bool isVertical = true); - ~ItemPane(); - - void renderBatch( std::vector& item, float alpha ); - bool onSelect( int gridId, bool selected ); - void drawScrollBar( ScrollBar& hScroll ); - //void setSize() - - Font* f; - Textures* textures; - IItemPaneCallback* screen; - - int physicalScreenHeight; // Needed for glScissor - bool isVertical; - - NinePatchLayer* guiSlotItem; - NinePatchLayer* guiSlotItemSelected; -}; - -#endif /*ITEMPANE_H__*/ +#pragma once + +#include +#include +#include "ScrollingPane.h" +#include "../../../world/item/ItemInstance.h" + +class Font; +class Textures; +class NinePatchLayer; +class Recipe; +class ItemPane; + +class CItem +{ +public: + CItem(const ItemInstance& ins, Recipe* recipe, const std::string& text) + : item(ins), + recipe(recipe), + text(text), + sortText(text), + //maxBuildCount(0), + numBuilt(0), + inventoryCount(0), + _canCraft(false) + { + } + + typedef struct ReqItem { + ReqItem() {} + ReqItem(const ItemInstance& needItem, int has) + : item(needItem), has(has) {} + ItemInstance item; + int has; + bool enough() { return has >= item.count; } + } ReqItem; + + bool canCraft() { + return _canCraft;// || maxBuildCount > 0; + } + void setCanCraft(bool status) { + _canCraft = status; + } + + ItemInstance item; + Recipe* recipe; + std::string text; + std::string sortText; + //int maxBuildCount; + int numBuilt; + int inventoryCount; + std::vector neededItems; +private: + bool _canCraft; +}; + +class IItemPaneCallback +{ +public: + virtual ~IItemPaneCallback() {} + virtual void onItemSelected(const ItemPane* forPane, int index) = 0; + virtual const std::vector& getItems(const ItemPane* forPane) = 0; +}; + +class ItemPane: public ScrollingPane +{ + typedef ScrollingPane super; +public: + ItemPane( IItemPaneCallback* screen, + Textures* textures, + const IntRectangle& rect, + int numItems, + int guiHeight, + int physicalScreenHeight, + bool isVertical = true); + ~ItemPane(); + + void renderBatch( std::vector& item, float alpha ); + bool onSelect( int gridId, bool selected ); + void drawScrollBar( ScrollBar& hScroll ); + //void setSize() + + Font* f; + Textures* textures; + IItemPaneCallback* screen; + + int physicalScreenHeight; // Needed for glScissor + bool isVertical; + + NinePatchLayer* guiSlotItem; + NinePatchLayer* guiSlotItemSelected; +}; + diff --git a/src/client/gui/components/LargeImageButton.h b/src/client/gui/components/LargeImageButton.h index 9a06d53..1078b8b 100755 --- a/src/client/gui/components/LargeImageButton.h +++ b/src/client/gui/components/LargeImageButton.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__LargeImageButton_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__LargeImageButton_H__ - -#include "ImageButton.h" - -class LargeImageButton: public ImageButton -{ - typedef ImageButton super; -public: - LargeImageButton(int id, const std::string& msg); - LargeImageButton(int id, const std::string& msg, ImageDef& imageDef); - - void render(Minecraft* minecraft, int xm, int ym); - -private: - void setupDefault(); - - float _buttonScale; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__LargeImageButton_H__*/ +#pragma once + +#include "ImageButton.h" + +class LargeImageButton: public ImageButton +{ + typedef ImageButton super; +public: + LargeImageButton(int id, const std::string& msg); + LargeImageButton(int id, const std::string& msg, ImageDef& imageDef); + + void render(Minecraft* minecraft, int xm, int ym); + +private: + void setupDefault(); + + float _buttonScale; +}; + diff --git a/src/client/gui/components/NinePatch.h b/src/client/gui/components/NinePatch.h index 3403f2b..1e55e07 100755 --- a/src/client/gui/components/NinePatch.h +++ b/src/client/gui/components/NinePatch.h @@ -1,78 +1,76 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__NinePatch_H__ -#define NET_MINECRAFT_CLIENT_GUI__NinePatch_H__ - -#include "ImageButton.h" -#include "../../renderer/TextureData.h" -#include "../../renderer/Textures.h" -#include "../../renderer/Tesselator.h" -#include "../../Minecraft.h" - -class Tesselator; - -class NinePatchDescription { -public: - NinePatchDescription& transformUVForImage(const TextureData& d); - NinePatchDescription& transformUVForImageSize(int w, int h); - - float u0, u1, u2, u3; - float v0, v1, v2, v3; - float w, e, n, s; - - static NinePatchDescription createSymmetrical(int texWidth, int texHeight, const IntRectangle& src, int xCutAt, int yCutAt); -private: - NinePatchDescription( float x, float y, float x1, float x2, float x3, float y1, float y2, float y3, - float w, float e, float n, float s); - - int imgW; - int imgH; -}; - -class NinePatchLayer: public GuiElement -{ - struct CachedQuad; -public: - NinePatchLayer(const NinePatchDescription& desc, const std::string& imageName, Textures* textures, float w = 32, float h = 32); - virtual ~NinePatchLayer() {}; - void setSize(float w, float h); - - void draw(Tesselator& t, float x, float y); - - NinePatchLayer* exclude(int excludeId); - NinePatchLayer* setExcluded(int exludeBits); - - float getWidth() { return w; } - float getHeight() { return h; } - -private: - void buildQuad(int qid); - void getPatchInfo(int xc, int yc, float& x0, float& x1, float& y0, float& y1); - - void d(Tesselator& t, const CachedQuad& q); - - float w, h; - NinePatchDescription desc; - std::string imageName; - Textures* textures; - int excluded; - - typedef struct CachedQuad { - float x0, x1, y0, y1, z; - float u0, u1, v0, v1; - } CachedQuad; - CachedQuad quads[9]; -}; - -class NinePatchFactory { -public: - NinePatchFactory(Textures* textures, const std::string& imageName ); - - NinePatchLayer* createSymmetrical(const IntRectangle& src, int xCutAt, int yCutAt, float w = 32.0f, float h = 32.0f); - -private: - Textures* textures; - std::string imageName; - int width; - int height; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI__NinePatch_H__*/ +#pragma once + +#include "ImageButton.h" +#include "../../renderer/TextureData.h" +#include "../../renderer/Textures.h" +#include "../../renderer/Tesselator.h" +#include "../../Minecraft.h" + +class Tesselator; + +class NinePatchDescription { +public: + NinePatchDescription& transformUVForImage(const TextureData& d); + NinePatchDescription& transformUVForImageSize(int w, int h); + + float u0, u1, u2, u3; + float v0, v1, v2, v3; + float w, e, n, s; + + static NinePatchDescription createSymmetrical(int texWidth, int texHeight, const IntRectangle& src, int xCutAt, int yCutAt); +private: + NinePatchDescription( float x, float y, float x1, float x2, float x3, float y1, float y2, float y3, + float w, float e, float n, float s); + + int imgW; + int imgH; +}; + +class NinePatchLayer: public GuiElement +{ + struct CachedQuad; +public: + NinePatchLayer(const NinePatchDescription& desc, const std::string& imageName, Textures* textures, float w = 32, float h = 32); + virtual ~NinePatchLayer() {}; + void setSize(float w, float h); + + void draw(Tesselator& t, float x, float y); + + NinePatchLayer* exclude(int excludeId); + NinePatchLayer* setExcluded(int exludeBits); + + float getWidth() { return w; } + float getHeight() { return h; } + +private: + void buildQuad(int qid); + void getPatchInfo(int xc, int yc, float& x0, float& x1, float& y0, float& y1); + + void d(Tesselator& t, const CachedQuad& q); + + float w, h; + NinePatchDescription desc; + std::string imageName; + Textures* textures; + int excluded; + + typedef struct CachedQuad { + float x0, x1, y0, y1, z; + float u0, u1, v0, v1; + } CachedQuad; + CachedQuad quads[9]; +}; + +class NinePatchFactory { +public: + NinePatchFactory(Textures* textures, const std::string& imageName ); + + NinePatchLayer* createSymmetrical(const IntRectangle& src, int xCutAt, int yCutAt, float w = 32.0f, float h = 32.0f); + +private: + Textures* textures; + std::string imageName; + int width; + int height; +}; + diff --git a/src/client/gui/components/OptionsGroup.h b/src/client/gui/components/OptionsGroup.h index 24d28bd..b5cf467 100755 --- a/src/client/gui/components/OptionsGroup.h +++ b/src/client/gui/components/OptionsGroup.h @@ -1,32 +1,30 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__ - -//package net.minecraft.client.gui; - -#include -#include "GuiElementContainer.h" -#include "ScrollingPane.h" -#include "../../Options.h" - -class Font; -class Minecraft; - -class OptionsGroup: public GuiElementContainer { - typedef GuiElementContainer super; -public: - OptionsGroup(std::string labelID); - virtual void setupPositions(); - virtual void render(Minecraft* minecraft, int xm, int ym); - OptionsGroup& addOptionItem(OptionId optId, Minecraft* minecraft); -protected: - - void createToggle(OptionId optId, Minecraft* minecraft); - void createProgressSlider(OptionId optId, Minecraft* minecraft); - void createStepSlider(OptionId optId, Minecraft* minecraft); - void createTextbox(OptionId optId, Minecraft* minecraft); - void createKey(OptionId optId, Minecraft* minecraft); - - std::string label; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsGroup_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include +#include "GuiElementContainer.h" +#include "ScrollingPane.h" +#include "../../Options.h" + +class Font; +class Minecraft; + +class OptionsGroup: public GuiElementContainer { + typedef GuiElementContainer super; +public: + OptionsGroup(std::string labelID); + virtual void setupPositions(); + virtual void render(Minecraft* minecraft, int xm, int ym); + OptionsGroup& addOptionItem(OptionId optId, Minecraft* minecraft); +protected: + + void createToggle(OptionId optId, Minecraft* minecraft); + void createProgressSlider(OptionId optId, Minecraft* minecraft); + void createStepSlider(OptionId optId, Minecraft* minecraft); + void createTextbox(OptionId optId, Minecraft* minecraft); + void createKey(OptionId optId, Minecraft* minecraft); + + std::string label; +}; + diff --git a/src/client/gui/components/OptionsItem.h b/src/client/gui/components/OptionsItem.h index 5add1ef..84ae5cb 100755 --- a/src/client/gui/components/OptionsItem.h +++ b/src/client/gui/components/OptionsItem.h @@ -1,27 +1,25 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsItem_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsItem_H__ - -#include -#include -#include "GuiElementContainer.h" -#include "../../../world/item/ItemInstance.h" -#include "../../../client/Options.h" -class Font; -class Textures; -class NinePatchLayer; -class ItemPane; - -class OptionsItem: public GuiElementContainer -{ - typedef GuiElementContainer super; -public: - OptionsItem(OptionId optionId, std::string label, GuiElement* element); - virtual void render(Minecraft* minecraft, int xm, int ym); - void setupPositions(); - -private: - OptionId m_optionId; - std::string m_label; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__OptionsItem_H__*/ +#pragma once + +#include +#include +#include "GuiElementContainer.h" +#include "../../../world/item/ItemInstance.h" +#include "../../../client/Options.h" +class Font; +class Textures; +class NinePatchLayer; +class ItemPane; + +class OptionsItem: public GuiElementContainer +{ + typedef GuiElementContainer super; +public: + OptionsItem(OptionId optionId, std::string label, GuiElement* element); + virtual void render(Minecraft* minecraft, int xm, int ym); + void setupPositions(); + +private: + OptionId m_optionId; + std::string m_label; +}; + diff --git a/src/client/gui/components/RolledSelectionListH.h b/src/client/gui/components/RolledSelectionListH.h index 28682c1..a6dea76 100755 --- a/src/client/gui/components/RolledSelectionListH.h +++ b/src/client/gui/components/RolledSelectionListH.h @@ -1,82 +1,80 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__RolledSelectionListH_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__RolledSelectionListH_H__ - -#include "../GuiComponent.h" -class MinecraftClient; -class Tesselator; - - -class RolledSelectionListH : public GuiComponent -{ - static const int NO_DRAG = -1; - static const int DRAG_OUTSIDE = -2; - static const int DRAG_NORMAL = 0; -public: - RolledSelectionListH(MinecraftClient& minecraft, int width, int height, int x0, int x1, int y0, int y1, int itemWidth); - - virtual int getItemAtPosition(int x, int y); - - virtual bool capXPosition(); - - virtual void tick(); - virtual void render(int xm, int ym, float a); - virtual void renderHoleBackground(/*float x0, float x1,*/ float y0, float y1, int a0, int a1); - virtual void setRenderSelection(bool _renderSelection); - virtual void setComponentSelected(bool selected); -protected: - void setRenderHeader(bool _renderHeader, int _headerHeight); - - virtual int getNumberOfItems() = 0; - - virtual void selectStart(int item, int localX, int localY) {} - virtual void selectCancel() {} - virtual void selectItem(int item, bool doubleClick) = 0; - virtual bool isSelectedItem(int item) = 0; - - virtual int getMaxPosition(); - virtual float getPos(float alpha); - virtual void touched(); - - virtual void renderItem(int i, int x, int y, int h, Tesselator& t) = 0; - virtual void renderHeader(int x, int y, Tesselator& t) {} - virtual void renderBackground() = 0; - virtual void renderDecorations(int mouseX, int mouseY) {} - - virtual void clickedHeader(int headerMouseX, int headerMouseY) {} - int getItemAtXPositionRaw(int x); -protected: - MinecraftClient& minecraft; - - float x0; - float x1; - int itemWidth; - int width; - int height; -//private: - float y0; - float y1; - - int dragState; - float xDrag; - float xo; - float xoo; - float xInertia; - float _xinertia; - - int selectionX; - bool renderSelection; - bool _componentSelected; - - bool _renderTopBorder; - bool _renderBottomBorder; - -private: - int headerWidth; - bool doRenderHeader; - long lastSelectionTime; - int lastSelection; - - float _lastxoo; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__RolledSelectionListH_H__*/ +#pragma once + +#include "../GuiComponent.h" +class MinecraftClient; +class Tesselator; + + +class RolledSelectionListH : public GuiComponent +{ + static const int NO_DRAG = -1; + static const int DRAG_OUTSIDE = -2; + static const int DRAG_NORMAL = 0; +public: + RolledSelectionListH(MinecraftClient& minecraft, int width, int height, int x0, int x1, int y0, int y1, int itemWidth); + + virtual int getItemAtPosition(int x, int y); + + virtual bool capXPosition(); + + virtual void tick(); + virtual void render(int xm, int ym, float a); + virtual void renderHoleBackground(/*float x0, float x1,*/ float y0, float y1, int a0, int a1); + virtual void setRenderSelection(bool _renderSelection); + virtual void setComponentSelected(bool selected); +protected: + void setRenderHeader(bool _renderHeader, int _headerHeight); + + virtual int getNumberOfItems() = 0; + + virtual void selectStart(int item, int localX, int localY) {} + virtual void selectCancel() {} + virtual void selectItem(int item, bool doubleClick) = 0; + virtual bool isSelectedItem(int item) = 0; + + virtual int getMaxPosition(); + virtual float getPos(float alpha); + virtual void touched(); + + virtual void renderItem(int i, int x, int y, int h, Tesselator& t) = 0; + virtual void renderHeader(int x, int y, Tesselator& t) {} + virtual void renderBackground() = 0; + virtual void renderDecorations(int mouseX, int mouseY) {} + + virtual void clickedHeader(int headerMouseX, int headerMouseY) {} + int getItemAtXPositionRaw(int x); +protected: + MinecraftClient& minecraft; + + float x0; + float x1; + int itemWidth; + int width; + int height; +//private: + float y0; + float y1; + + int dragState; + float xDrag; + float xo; + float xoo; + float xInertia; + float _xinertia; + + int selectionX; + bool renderSelection; + bool _componentSelected; + + bool _renderTopBorder; + bool _renderBottomBorder; + +private: + int headerWidth; + bool doRenderHeader; + long lastSelectionTime; + int lastSelection; + + float _lastxoo; +}; + diff --git a/src/client/gui/components/RolledSelectionListV.h b/src/client/gui/components/RolledSelectionListV.h index 09fb85f..a0338e8 100755 --- a/src/client/gui/components/RolledSelectionListV.h +++ b/src/client/gui/components/RolledSelectionListV.h @@ -1,94 +1,92 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__RolledSelectionListV_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__RolledSelectionListV_H__ - -#include "../GuiComponent.h" -class Minecraft; -class Tesselator; - - -class RolledSelectionListV : public GuiComponent -{ - static const int NO_DRAG = -1; - static const int DRAG_OUTSIDE = -2; - static const int DRAG_NORMAL = 0; -public: - RolledSelectionListV(Minecraft* minecraft, int width, int height, int x0, int x1, int y0, int y1, int itemHeight); - - virtual int getItemAtPosition(int x, int y); - - virtual bool capYPosition(); - - virtual void tick(); - virtual void render(int xm, int ym, float a); - virtual void renderHoleBackground(/*float x0, float x1,*/ float y0, float y1, int a0, int a1); - virtual void setRenderSelection(bool _renderSelection); - virtual void setComponentSelected(bool selected); -protected: - void setRenderHeader(bool _renderHeader, int _headerHeight); - - virtual int getNumberOfItems() = 0; - - virtual void selectStart(int item) {} - virtual void selectCancel() {} - virtual void selectItem(int item, bool doubleClick) = 0; - virtual bool isSelectedItem(int item) = 0; - - virtual int getMaxPosition(); - virtual float getPos(float alpha); - virtual void touched(); - - virtual void renderItem(int i, int x, int y, int h, Tesselator& t) = 0; - virtual void renderHeader(int x, int y, Tesselator& t) {} - virtual void renderBackground() = 0; - virtual void renderForeground() {} - virtual void renderDecorations(int mouseX, int mouseY) {} - - virtual void clickedHeader(int headerMouseX, int headerMouseY) {} - virtual int convertSelection(int item, int xm, int ym) { return item; } - - int getItemAtYPositionRaw(int y); - void evaluate(int xm, int ym); - virtual void onPreRender(); - virtual void onPostRender(); - void renderDirtBackground(); -protected: - Minecraft* minecraft; - - float x0; - float x1; - int itemHeight; - int width; - int height; -//private: - float y0; - float y1; - - int dragState; - float yDrag; - float yo; - float yoo; - float yInertia; - float _yinertia; - - int selectionY; - bool renderSelection; - bool _componentSelected; - - bool _renderDirtBackground; - bool _renderTopBorder; - bool _renderBottomBorder; - - int _lastxm; - int _lastym; -private: - int headerHeight; - bool doRenderHeader; - long lastSelectionTime; - int lastSelection; - - float _lastyoo; - - float _stickPixels; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__RolledSelectionListV_H__*/ +#pragma once + +#include "../GuiComponent.h" +class Minecraft; +class Tesselator; + + +class RolledSelectionListV : public GuiComponent +{ + static const int NO_DRAG = -1; + static const int DRAG_OUTSIDE = -2; + static const int DRAG_NORMAL = 0; +public: + RolledSelectionListV(Minecraft* minecraft, int width, int height, int x0, int x1, int y0, int y1, int itemHeight); + + virtual int getItemAtPosition(int x, int y); + + virtual bool capYPosition(); + + virtual void tick(); + virtual void render(int xm, int ym, float a); + virtual void renderHoleBackground(/*float x0, float x1,*/ float y0, float y1, int a0, int a1); + virtual void setRenderSelection(bool _renderSelection); + virtual void setComponentSelected(bool selected); +protected: + void setRenderHeader(bool _renderHeader, int _headerHeight); + + virtual int getNumberOfItems() = 0; + + virtual void selectStart(int item) {} + virtual void selectCancel() {} + virtual void selectItem(int item, bool doubleClick) = 0; + virtual bool isSelectedItem(int item) = 0; + + virtual int getMaxPosition(); + virtual float getPos(float alpha); + virtual void touched(); + + virtual void renderItem(int i, int x, int y, int h, Tesselator& t) = 0; + virtual void renderHeader(int x, int y, Tesselator& t) {} + virtual void renderBackground() = 0; + virtual void renderForeground() {} + virtual void renderDecorations(int mouseX, int mouseY) {} + + virtual void clickedHeader(int headerMouseX, int headerMouseY) {} + virtual int convertSelection(int item, int xm, int ym) { return item; } + + int getItemAtYPositionRaw(int y); + void evaluate(int xm, int ym); + virtual void onPreRender(); + virtual void onPostRender(); + void renderDirtBackground(); +protected: + Minecraft* minecraft; + + float x0; + float x1; + int itemHeight; + int width; + int height; +//private: + float y0; + float y1; + + int dragState; + float yDrag; + float yo; + float yoo; + float yInertia; + float _yinertia; + + int selectionY; + bool renderSelection; + bool _componentSelected; + + bool _renderDirtBackground; + bool _renderTopBorder; + bool _renderBottomBorder; + + int _lastxm; + int _lastym; +private: + int headerHeight; + bool doRenderHeader; + long lastSelectionTime; + int lastSelection; + + float _lastyoo; + + float _stickPixels; +}; + diff --git a/src/client/gui/components/ScrolledSelectionList.h b/src/client/gui/components/ScrolledSelectionList.h index bb6e9e2..199edd0 100755 --- a/src/client/gui/components/ScrolledSelectionList.h +++ b/src/client/gui/components/ScrolledSelectionList.h @@ -1,69 +1,67 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__ScrolledSelectionList_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__ScrolledSelectionList_H__ - -#include "../GuiComponent.h" -class Minecraft; -class Tesselator; - - -class ScrolledSelectionList : public GuiComponent -{ - static const int NO_DRAG = -1; - static const int DRAG_OUTSIDE = -2; - static const int DRAG_NORMAL = 0; - static const int DRAG_SKIP = 1; // special case to fix android jump bug -public: - ScrolledSelectionList(Minecraft* _minecraft, int _width, int _height, int _y0, int _y1, int _itemHeight); - - virtual void setRenderSelection(bool _renderSelection); -protected: - void setRenderHeader(bool _renderHeader, int _headerHeight); - - virtual int getNumberOfItems() = 0; - - virtual void selectItem(int item, bool doubleClick) = 0; - virtual bool isSelectedItem(int item) = 0; - - virtual int getMaxPosition(); - - virtual void renderItem(int i, int x, int y, int h, Tesselator& t) = 0; - virtual void renderHeader(int x, int y, Tesselator& t) {} - virtual void renderBackground() = 0; - virtual void renderDecorations(int mouseX, int mouseY) {} - - virtual void clickedHeader(int headerMouseX, int headerMouseY) {} -public: - virtual int getItemAtPosition(int x, int y); - - virtual void capYPosition(); - - virtual void render(int xm, int ym, float a); - virtual void renderHoleBackground(float y0, float y1, int a0, int a1); - void renderDirtBackground(); -protected: - Minecraft* minecraft; - - float y0; - float y1; - int itemHeight; -private: - int width; - int height; - float x1; - float x0; - - int ignoreY; // new attempt to fix android jump bug - int dragState; - float yDrag; - float yo; - float yInertia; - - int selectionY; - long lastSelectionTime; - - bool renderSelection; - bool doRenderHeader; - int headerHeight; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__ScrolledSelectionList_H__*/ +#pragma once + +#include "../GuiComponent.h" +class Minecraft; +class Tesselator; + + +class ScrolledSelectionList : public GuiComponent +{ + static const int NO_DRAG = -1; + static const int DRAG_OUTSIDE = -2; + static const int DRAG_NORMAL = 0; + static const int DRAG_SKIP = 1; // special case to fix android jump bug +public: + ScrolledSelectionList(Minecraft* _minecraft, int _width, int _height, int _y0, int _y1, int _itemHeight); + + virtual void setRenderSelection(bool _renderSelection); +protected: + void setRenderHeader(bool _renderHeader, int _headerHeight); + + virtual int getNumberOfItems() = 0; + + virtual void selectItem(int item, bool doubleClick) = 0; + virtual bool isSelectedItem(int item) = 0; + + virtual int getMaxPosition(); + + virtual void renderItem(int i, int x, int y, int h, Tesselator& t) = 0; + virtual void renderHeader(int x, int y, Tesselator& t) {} + virtual void renderBackground() = 0; + virtual void renderDecorations(int mouseX, int mouseY) {} + + virtual void clickedHeader(int headerMouseX, int headerMouseY) {} +public: + virtual int getItemAtPosition(int x, int y); + + virtual void capYPosition(); + + virtual void render(int xm, int ym, float a); + virtual void renderHoleBackground(float y0, float y1, int a0, int a1); + void renderDirtBackground(); +protected: + Minecraft* minecraft; + + float y0; + float y1; + int itemHeight; +private: + int width; + int height; + float x1; + float x0; + + int ignoreY; // new attempt to fix android jump bug + int dragState; + float yDrag; + float yo; + float yInertia; + + int selectionY; + long lastSelectionTime; + + bool renderSelection; + bool doRenderHeader; + int headerHeight; +}; + diff --git a/src/client/gui/components/ScrollingPane.h b/src/client/gui/components/ScrollingPane.h index 0a2c321..a27af1c 100755 --- a/src/client/gui/components/ScrollingPane.h +++ b/src/client/gui/components/ScrollingPane.h @@ -1,203 +1,201 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__ScrollingPane_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__ScrollingPane_H__ - -#include "../GuiComponent.h" -#include "ImageButton.h" -#include "../../player/input/touchscreen/TouchAreaModel.h" -#include "../../../world/phys/Vec3.h" -#include "../../Timer.h" - -enum ScrollingPaneFlags { - SF_LockX = 1 << 0, - SF_LockY = 1 << 1, - SF_WrapX = 1 << 2, - SF_WrapY = 1 << 3, - SF_HardLimits = 1 << 4, - SF_MultiSelect = 1 << 5, - //SF_Snap = 1 << 6, - //SF_CustomSnap = 1 << 7, - //SF_Scissor = 1 << 8, - SF_ShowScrollbar= 1 << 9, - SF_NoHoldSelect = 1 << 10 -}; - -typedef struct ScrollBar { - ScrollBar() - : alpha(0), - fading(-1) - {} - float x; - float y; - float w; - float h; - //bool visible; - float alpha; - int fading; -} ScrollBar; - -class ScrollingPane: public GuiComponent { -public: - typedef struct GridItem { - int id; - int x, y; - // The GUI coordinates comes in (xf, yf) - float xf, yf; - bool selected; - } GridItem; - - ScrollingPane(int flags, const IntRectangle& boundingBox, const IntRectangle& itemRect, int columns, int numItems, float screenScale = 1.0f, const IntRectangle& itemBoundingRect = IntRectangle(0,0,0,0)); - ~ScrollingPane(); - //void init(Minecraft*, int width, int height); - void tick(); - void render(int xm, int ym, float alpha); - - // scroll the content by the given amount (dx horizontal, dy vertical) - // positive values move content downward/rightward - void scrollBy(float dx, float dy); - - bool getGridItemFor_slow(int itemIndex, GridItem& out); - - void setSelected(int id, bool selected); - - // This function is called with all visible GridItems. The base - // implementation just dispatches each item to renderItem in y,x order - virtual void renderBatch(std::vector& items, float alpha); - virtual void renderItem(GridItem& item, float alpha); - - //void render(int xx, int yy); - bool queryHoldTime(int* gridId, int* heldMs); - -protected: - GridItem getItemForPos(float x, float y, bool isScreenPos); - void handleUserInput(); - void addDeltaPos(float x, float y, float dt, int z); - - void translate(float xo, float yo); - - int flags; - - int columns; - int rows; - int numItems; - - int px, py; - float fpx, fpy; - - float screenScale; - float invScreenScale; - //bool hasItemBounding; - - IntRectangle bbox; - IntRectangle itemRect; - IntRectangle itemBbox; - RectangleArea area; - RectangleArea bboxArea; - - // Dragging info - std::vector dragDeltas; - int dragState; - Vec3 dragBeginPos; - Vec3 dragBeginScreenPos; - int dragTicks; - float dragLastDeltaTimeStamp; - Vec3 dragLastPos; - - float dx, dy; - float friction; - - float dstx, dsty; - - // Rewrite - bool dragging; //! - bool decelerating; - bool tracking; //! - - bool pagingEnabled; //! - - Vec3 _contentOffset; //! - Vec3 _contentOffsetBeforeDeceleration; //* - - int lastEventTime; //< - - Vec3 decelerationVelocity; //* - Vec3 minDecelerationPoint; //* - Vec3 maxDecelerationPoint; //* - - float penetrationDeceleration; //< - float penetrationAcceleration; //< - - Vec3 minPoint; //* - Vec3 startPosition; //* - Vec3 startTouchPosition; //* - Vec3 startTimePosition; //* - - bool wasDeceleratingWhenTouchesBegan; //* - bool firstDrag; //< - - float startTime; //< - //float startTime - - IntRectangle size; - int lastFrame; - - bool _scrollEnabled; //! - bool touchesHaveMoved; //* - - virtual void didEndDragging() {} - virtual void didEndDecelerating() {} - virtual void willBeginDecelerating() {} - virtual void willBeginDragging() {} - - int te_moved, - te_ended, - te_highlight; - int highlightTimer; - int highlightStarted; - GridItem highlightItem; - - bool* selected; - int selectedId; - - ScrollBar vScroll, hScroll; - - IntRectangle adjustedContentSize; - void touchesBegan(float x, float y, int t); - void touchesMoved(float x, float y, int t); - void touchesEnded(float x, float y, int t); - void touchesCancelled(float x, float y, int t); - void beginTracking(float x, float y, int t); - void onHoldItem(); - - void _onSelect( int id ); - virtual bool onSelect(int gridId, bool selected); - - Vec3& contentOffset(); - - void startDecelerationAnimation(bool force); - void stopDecelerationAnimation(); - void stepThroughDecelerationAnimation(bool f); - - void setContentOffset(float x, float y); - void setContentOffset(Vec3 a); - void setContentOffsetWithAnimation(Vec3 b, bool doScroll); - void snapContentOffsetToBounds(bool snap); //* - void adjustContentSize(); - //TouchAreaModel _areaModel; - - bool isAllSet(int flag) { return (flags & flag) == flag; } - bool isSet(int flag) { return (flags & flag) != 0; } - bool isNotSet(int flag) { return !isSet(flag); } - - void updateHorizontalScrollIndicator(); - void updateVerticalScrollIndicator(); - void hideScrollIndicators(); //* - void updateScrollFade( ScrollBar& vScroll ); -private: - Timer _timer; - bool _doStepTimer; - bool _wasDown; - float _lx; - float _ly; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__ScrollingPane_H__*/ +#pragma once + +#include "../GuiComponent.h" +#include "ImageButton.h" +#include "../../player/input/touchscreen/TouchAreaModel.h" +#include "../../../world/phys/Vec3.h" +#include "../../Timer.h" + +enum ScrollingPaneFlags { + SF_LockX = 1 << 0, + SF_LockY = 1 << 1, + SF_WrapX = 1 << 2, + SF_WrapY = 1 << 3, + SF_HardLimits = 1 << 4, + SF_MultiSelect = 1 << 5, + //SF_Snap = 1 << 6, + //SF_CustomSnap = 1 << 7, + //SF_Scissor = 1 << 8, + SF_ShowScrollbar= 1 << 9, + SF_NoHoldSelect = 1 << 10 +}; + +typedef struct ScrollBar { + ScrollBar() + : alpha(0), + fading(-1) + {} + float x; + float y; + float w; + float h; + //bool visible; + float alpha; + int fading; +} ScrollBar; + +class ScrollingPane: public GuiComponent { +public: + typedef struct GridItem { + int id; + int x, y; + // The GUI coordinates comes in (xf, yf) + float xf, yf; + bool selected; + } GridItem; + + ScrollingPane(int flags, const IntRectangle& boundingBox, const IntRectangle& itemRect, int columns, int numItems, float screenScale = 1.0f, const IntRectangle& itemBoundingRect = IntRectangle(0,0,0,0)); + ~ScrollingPane(); + //void init(Minecraft*, int width, int height); + void tick(); + void render(int xm, int ym, float alpha); + + // scroll the content by the given amount (dx horizontal, dy vertical) + // positive values move content downward/rightward + void scrollBy(float dx, float dy); + + bool getGridItemFor_slow(int itemIndex, GridItem& out); + + void setSelected(int id, bool selected); + + // This function is called with all visible GridItems. The base + // implementation just dispatches each item to renderItem in y,x order + virtual void renderBatch(std::vector& items, float alpha); + virtual void renderItem(GridItem& item, float alpha); + + //void render(int xx, int yy); + bool queryHoldTime(int* gridId, int* heldMs); + +protected: + GridItem getItemForPos(float x, float y, bool isScreenPos); + void handleUserInput(); + void addDeltaPos(float x, float y, float dt, int z); + + void translate(float xo, float yo); + + int flags; + + int columns; + int rows; + int numItems; + + int px, py; + float fpx, fpy; + + float screenScale; + float invScreenScale; + //bool hasItemBounding; + + IntRectangle bbox; + IntRectangle itemRect; + IntRectangle itemBbox; + RectangleArea area; + RectangleArea bboxArea; + + // Dragging info + std::vector dragDeltas; + int dragState; + Vec3 dragBeginPos; + Vec3 dragBeginScreenPos; + int dragTicks; + float dragLastDeltaTimeStamp; + Vec3 dragLastPos; + + float dx, dy; + float friction; + + float dstx, dsty; + + // Rewrite + bool dragging; //! + bool decelerating; + bool tracking; //! + + bool pagingEnabled; //! + + Vec3 _contentOffset; //! + Vec3 _contentOffsetBeforeDeceleration; //* + + int lastEventTime; //< + + Vec3 decelerationVelocity; //* + Vec3 minDecelerationPoint; //* + Vec3 maxDecelerationPoint; //* + + float penetrationDeceleration; //< + float penetrationAcceleration; //< + + Vec3 minPoint; //* + Vec3 startPosition; //* + Vec3 startTouchPosition; //* + Vec3 startTimePosition; //* + + bool wasDeceleratingWhenTouchesBegan; //* + bool firstDrag; //< + + float startTime; //< + //float startTime + + IntRectangle size; + int lastFrame; + + bool _scrollEnabled; //! + bool touchesHaveMoved; //* + + virtual void didEndDragging() {} + virtual void didEndDecelerating() {} + virtual void willBeginDecelerating() {} + virtual void willBeginDragging() {} + + int te_moved, + te_ended, + te_highlight; + int highlightTimer; + int highlightStarted; + GridItem highlightItem; + + bool* selected; + int selectedId; + + ScrollBar vScroll, hScroll; + + IntRectangle adjustedContentSize; + void touchesBegan(float x, float y, int t); + void touchesMoved(float x, float y, int t); + void touchesEnded(float x, float y, int t); + void touchesCancelled(float x, float y, int t); + void beginTracking(float x, float y, int t); + void onHoldItem(); + + void _onSelect( int id ); + virtual bool onSelect(int gridId, bool selected); + + Vec3& contentOffset(); + + void startDecelerationAnimation(bool force); + void stopDecelerationAnimation(); + void stepThroughDecelerationAnimation(bool f); + + void setContentOffset(float x, float y); + void setContentOffset(Vec3 a); + void setContentOffsetWithAnimation(Vec3 b, bool doScroll); + void snapContentOffsetToBounds(bool snap); //* + void adjustContentSize(); + //TouchAreaModel _areaModel; + + bool isAllSet(int flag) { return (flags & flag) == flag; } + bool isSet(int flag) { return (flags & flag) != 0; } + bool isNotSet(int flag) { return !isSet(flag); } + + void updateHorizontalScrollIndicator(); + void updateVerticalScrollIndicator(); + void hideScrollIndicators(); //* + void updateScrollFade( ScrollBar& vScroll ); +private: + Timer _timer; + bool _doStepTimer; + bool _wasDown; + float _lx; + float _ly; +}; + diff --git a/src/client/gui/components/Slider.h b/src/client/gui/components/Slider.h index 73c009a..ccccb26 100755 --- a/src/client/gui/components/Slider.h +++ b/src/client/gui/components/Slider.h @@ -1,48 +1,46 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__Slider_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__Slider_H__ - -#include "GuiElement.h" -#include "../../../client/Options.h" -#include - -class Slider : public GuiElement { - typedef GuiElement super; -public: - virtual void render( Minecraft* minecraft, int xm, int ym ); - virtual void mouseClicked( Minecraft* minecraft, int x, int y, int buttonNum ); - virtual void mouseReleased( Minecraft* minecraft, int x, int y, int buttonNum ); - virtual void tick(Minecraft* minecraft); - -protected: - Slider(OptionId optId); - - OptionId m_optId; - - bool m_mouseDownOnElement; - float m_percentage; - int m_numSteps; -}; - -class SliderFloat : public Slider { -public: - SliderFloat(Minecraft* minecraft, OptionId option); - - virtual void mouseReleased( Minecraft* minecraft, int x, int y, int buttonNum ) override; - -protected: - OptionFloat* m_option; -}; - - -class SliderInt : public Slider { -public: - SliderInt(Minecraft* minecraft, OptionId option); - - virtual void render( Minecraft* minecraft, int xm, int ym ) override; - virtual void mouseReleased( Minecraft* minecraft, int x, int y, int buttonNum ) override; - -protected: - OptionInt* m_option; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__Slider_H__*/ +#pragma once + +#include "GuiElement.h" +#include "../../../client/Options.h" +#include + +class Slider : public GuiElement { + typedef GuiElement super; +public: + virtual void render( Minecraft* minecraft, int xm, int ym ); + virtual void mouseClicked( Minecraft* minecraft, int x, int y, int buttonNum ); + virtual void mouseReleased( Minecraft* minecraft, int x, int y, int buttonNum ); + virtual void tick(Minecraft* minecraft); + +protected: + Slider(OptionId optId); + + OptionId m_optId; + + bool m_mouseDownOnElement; + float m_percentage; + int m_numSteps; +}; + +class SliderFloat : public Slider { +public: + SliderFloat(Minecraft* minecraft, OptionId option); + + virtual void mouseReleased( Minecraft* minecraft, int x, int y, int buttonNum ) override; + +protected: + OptionFloat* m_option; +}; + + +class SliderInt : public Slider { +public: + SliderInt(Minecraft* minecraft, OptionId option); + + virtual void render( Minecraft* minecraft, int xm, int ym ) override; + virtual void mouseReleased( Minecraft* minecraft, int x, int y, int buttonNum ) override; + +protected: + OptionInt* m_option; +}; + diff --git a/src/client/gui/components/TextBox.h b/src/client/gui/components/TextBox.h index 34ea5a7..6f306a6 100755 --- a/src/client/gui/components/TextBox.h +++ b/src/client/gui/components/TextBox.h @@ -1,44 +1,42 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_COMPONENTS__TextBox_H__ -#define NET_MINECRAFT_CLIENT_GUI_COMPONENTS__TextBox_H__ - -//package net.minecraft.client.gui; - -#include -#include "GuiElement.h" -#include "../../Options.h" -#include "../../../platform/input/Mouse.h" -#include "../../../platform/input/Keyboard.h" - -class Font; -class Minecraft; - -class TextBox: public GuiElement -{ -public: - TextBox(int id, const std::string& msg); - TextBox(int id, int x, int y, const std::string& msg); - TextBox(int id, int x, int y, int w, int h, const std::string& msg); - - virtual void mouseClicked(Minecraft* minecraft, int x, int y, int buttonNum); - - virtual void setFocus(Minecraft* minecraft); - virtual bool loseFocus(Minecraft* minecraft); - - virtual void render(Minecraft* minecraft, int xm, int ym); - - virtual void keyPressed(Minecraft* minecraft, int key); - virtual void charPressed(Minecraft* minecraft, char c); - virtual void tick(Minecraft* minecraft); - -public: - std::string hint; - std::string text; - int id; - - int blinkTicks; - - bool focused; - bool blink; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_COMPONENTS__TextBox_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include +#include "GuiElement.h" +#include "../../Options.h" +#include "../../../platform/input/Mouse.h" +#include "../../../platform/input/Keyboard.h" + +class Font; +class Minecraft; + +class TextBox: public GuiElement +{ +public: + TextBox(int id, const std::string& msg); + TextBox(int id, int x, int y, const std::string& msg); + TextBox(int id, int x, int y, int w, int h, const std::string& msg); + + virtual void mouseClicked(Minecraft* minecraft, int x, int y, int buttonNum); + + virtual void setFocus(Minecraft* minecraft); + virtual bool loseFocus(Minecraft* minecraft); + + virtual void render(Minecraft* minecraft, int xm, int ym); + + virtual void keyPressed(Minecraft* minecraft, int key); + virtual void charPressed(Minecraft* minecraft, char c); + virtual void tick(Minecraft* minecraft); + +public: + std::string hint; + std::string text; + int id; + + int blinkTicks; + + bool focused; + bool blink; +}; + diff --git a/src/client/gui/screens/ArmorScreen.h b/src/client/gui/screens/ArmorScreen.h index 46c1d1f..578c1c0 100755 --- a/src/client/gui/screens/ArmorScreen.h +++ b/src/client/gui/screens/ArmorScreen.h @@ -1,79 +1,77 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__ArmorScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__ArmorScreen_H__ - -#include "BaseContainerScreen.h" - -#include "../components/InventoryPane.h" -#include "../components/Button.h" - -class Font; -class CItem; -class Textures; -class NinePatchLayer; -class Tesselator; - -class ArmorScreen: public Screen, - public Touch::IInventoryPaneCallback -{ - typedef Screen super; - typedef std::vector ItemList; - - static const int NUM_ARMORBUTTONS = 4; -public: - ArmorScreen(); - ~ArmorScreen(); - - void init(); - void setupPositions(); - - void tick(); - void render(int xm, int ym, float a); - bool renderGameBehind(); - void buttonClicked(Button* button); - - // IInventoryPaneCallback - bool addItem(const Touch::InventoryPane* pane, int itemId); - bool isAllowed( int slot ); - std::vector getItems( const Touch::InventoryPane* forPane ); -private: - void renderPlayer(float xo, float yo); - - void setupInventoryPane(); - void updateItems(); - - void drawSlotItemAt(Tesselator& t, int slot, const ItemInstance* item, int x, int y); - ItemInstance moveOver(const ItemInstance* item, int maxCount); - void takeAndClearSlot( int slot ); - void handleRenderPane(Touch::InventoryPane* pane, Tesselator& t, int xm, int ym, float a); - bool canMoveToSlot(int slot, const ItemInstance* item); - ItemList _items; - - std::string currentItemDesc; - ItemInstance burnResult; - float descWidth; - ImageButton btnClose; - - BlankButton btnArmor0; - BlankButton btnArmor1; - BlankButton btnArmor2; - BlankButton btnArmor3; - BlankButton* armorButtons[4]; - - Touch::THeader bHeader; - - Touch::InventoryPane* inventoryPane; - IntRectangle inventoryPaneRect; - IntRectangle guiPlayerBgRect; - - std::vector armorItems; - bool doRecreatePane; - - // GUI elements such as 9-Patches - NinePatchLayer* guiBackground; - NinePatchLayer* guiSlot; - NinePatchLayer* guiPaneFrame; - NinePatchLayer* guiPlayerBg; - Player* player; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__ArmorScreen_H__*/ +#pragma once + +#include "BaseContainerScreen.h" + +#include "../components/InventoryPane.h" +#include "../components/Button.h" + +class Font; +class CItem; +class Textures; +class NinePatchLayer; +class Tesselator; + +class ArmorScreen: public Screen, + public Touch::IInventoryPaneCallback +{ + typedef Screen super; + typedef std::vector ItemList; + + static const int NUM_ARMORBUTTONS = 4; +public: + ArmorScreen(); + ~ArmorScreen(); + + void init(); + void setupPositions(); + + void tick(); + void render(int xm, int ym, float a); + bool renderGameBehind(); + void buttonClicked(Button* button); + + // IInventoryPaneCallback + bool addItem(const Touch::InventoryPane* pane, int itemId); + bool isAllowed( int slot ); + std::vector getItems( const Touch::InventoryPane* forPane ); +private: + void renderPlayer(float xo, float yo); + + void setupInventoryPane(); + void updateItems(); + + void drawSlotItemAt(Tesselator& t, int slot, const ItemInstance* item, int x, int y); + ItemInstance moveOver(const ItemInstance* item, int maxCount); + void takeAndClearSlot( int slot ); + void handleRenderPane(Touch::InventoryPane* pane, Tesselator& t, int xm, int ym, float a); + bool canMoveToSlot(int slot, const ItemInstance* item); + ItemList _items; + + std::string currentItemDesc; + ItemInstance burnResult; + float descWidth; + ImageButton btnClose; + + BlankButton btnArmor0; + BlankButton btnArmor1; + BlankButton btnArmor2; + BlankButton btnArmor3; + BlankButton* armorButtons[4]; + + Touch::THeader bHeader; + + Touch::InventoryPane* inventoryPane; + IntRectangle inventoryPaneRect; + IntRectangle guiPlayerBgRect; + + std::vector armorItems; + bool doRecreatePane; + + // GUI elements such as 9-Patches + NinePatchLayer* guiBackground; + NinePatchLayer* guiSlot; + NinePatchLayer* guiPaneFrame; + NinePatchLayer* guiPlayerBg; + Player* player; +}; + diff --git a/src/client/gui/screens/BaseContainerScreen.h b/src/client/gui/screens/BaseContainerScreen.h index 55ce1e0..b06dbb1 100755 --- a/src/client/gui/screens/BaseContainerScreen.h +++ b/src/client/gui/screens/BaseContainerScreen.h @@ -1,50 +1,48 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__BaseContainerScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI__BaseContainerScreen_H__ - -//package net.minecraft.client.gui.screens; - -#include -#include "../Screen.h" -#include "../../Minecraft.h" -#include "../../player/LocalPlayer.h" - -class BaseContainerMenu; - -class BaseContainerScreen: public Screen -{ - typedef Screen super; -public: - BaseContainerScreen(BaseContainerMenu* menu) - : menu(menu) - { - } - - virtual void init() { - super::init(); - minecraft->player->containerMenu = menu; - } - - virtual void tick() { - super::tick(); - if (!minecraft->player->isAlive() || minecraft->player->removed) - minecraft->player->closeContainer(); - } - - virtual void keyPressed( int eventKey ) - { - if (eventKey == Keyboard::KEY_ESCAPE) { - minecraft->player->closeContainer(); - } else { - super::keyPressed(eventKey); - } - } - - virtual bool closeOnPlayerHurt() { - return true; - } - -protected: - BaseContainerMenu* menu; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI__BaseContainerScreen_H__*/ +#pragma once + +//package net.minecraft.client.gui.screens; + +#include +#include "../Screen.h" +#include "../../Minecraft.h" +#include "../../player/LocalPlayer.h" + +class BaseContainerMenu; + +class BaseContainerScreen: public Screen +{ + typedef Screen super; +public: + BaseContainerScreen(BaseContainerMenu* menu) + : menu(menu) + { + } + + virtual void init() { + super::init(); + minecraft->player->containerMenu = menu; + } + + virtual void tick() { + super::tick(); + if (!minecraft->player->isAlive() || minecraft->player->removed) + minecraft->player->closeContainer(); + } + + virtual void keyPressed( int eventKey ) + { + if (eventKey == Keyboard::KEY_ESCAPE) { + minecraft->player->closeContainer(); + } else { + super::keyPressed(eventKey); + } + } + + virtual bool closeOnPlayerHurt() { + return true; + } + +protected: + BaseContainerMenu* menu; +}; + diff --git a/src/client/gui/screens/ChatScreen.h b/src/client/gui/screens/ChatScreen.h index 0d6444b..809a3bb 100755 --- a/src/client/gui/screens/ChatScreen.h +++ b/src/client/gui/screens/ChatScreen.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__ChatScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__ChatScreen_H__ - -#include "../Screen.h" - -class ChatScreen: public Screen -{ -public: - ChatScreen() {} - virtual ~ChatScreen() {} - - void init(); - - void render(int xm, int ym, float a); - - void buttonClicked(Button* button) {}; - -private: -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__ChatScreen_H__*/ +#pragma once + +#include "../Screen.h" + +class ChatScreen: public Screen +{ +public: + ChatScreen() {} + virtual ~ChatScreen() {} + + void init(); + + void render(int xm, int ym, float a); + + void buttonClicked(Button* button) {}; + +private: +}; + diff --git a/src/client/gui/screens/ChestScreen.h b/src/client/gui/screens/ChestScreen.h index 7a072ef..216b459 100755 --- a/src/client/gui/screens/ChestScreen.h +++ b/src/client/gui/screens/ChestScreen.h @@ -1,72 +1,70 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__ChestScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__ChestScreen_H__ - -#include "BaseContainerScreen.h" - -#include "../components/InventoryPane.h" -#include "../components/Button.h" - -class Font; -class CItem; -class Textures; -class NinePatchLayer; -class FillingContainer; -class ChestTileEntity; -class Tesselator; - -class ChestScreen: public BaseContainerScreen, - public Touch::IInventoryPaneCallback -{ - typedef BaseContainerScreen super; - typedef std::vector ItemList; - friend class ItemPane; -public: - ChestScreen(Player* player, ChestTileEntity* chest); - ~ChestScreen(); - - void init(); - void setupPositions(); - - void tick(); - void render(int xm, int ym, float a); - bool renderGameBehind(); - void buttonClicked(Button* button); - - // IInventoryPaneCallback - bool addItem(const Touch::InventoryPane* pane, int itemId); - bool isAllowed( int slot ); - std::vector getItems( const Touch::InventoryPane* forPane ); - //const ItemList& getItems(const ItemPane* forPane); -private: - void setupPane(); - - void drawSlotItemAt(Tesselator& t, const ItemInstance* item, int x, int y, bool selected); - bool handleAddItem(FillingContainer* from, FillingContainer* to, int itemIndex); - void handleRenderPane(Touch::InventoryPane* pane, Tesselator& t, int xm, int ym, float a); - - std::string currentItemDesc; - ImageButton btnClose; - Touch::THeader bHeader; - Touch::THeader bHeaderChest; - - Touch::InventoryPane* inventoryPane; - Touch::InventoryPane* chestPane; - IntRectangle panesBbox; - - std::vector inventoryItems; - std::vector chestItems; - bool doRecreatePane; - - int selectedSlot; - - // GUI elements such as 9-Patches - NinePatchLayer* guiBackground; - NinePatchLayer* guiSlot; - NinePatchLayer* guiSlotMarked; - NinePatchLayer* guiSlotMarker; - NinePatchLayer* guiPaneFrame; - Player* player; - ChestTileEntity* chest; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__ChestScreen_H__*/ +#pragma once + +#include "BaseContainerScreen.h" + +#include "../components/InventoryPane.h" +#include "../components/Button.h" + +class Font; +class CItem; +class Textures; +class NinePatchLayer; +class FillingContainer; +class ChestTileEntity; +class Tesselator; + +class ChestScreen: public BaseContainerScreen, + public Touch::IInventoryPaneCallback +{ + typedef BaseContainerScreen super; + typedef std::vector ItemList; + friend class ItemPane; +public: + ChestScreen(Player* player, ChestTileEntity* chest); + ~ChestScreen(); + + void init(); + void setupPositions(); + + void tick(); + void render(int xm, int ym, float a); + bool renderGameBehind(); + void buttonClicked(Button* button); + + // IInventoryPaneCallback + bool addItem(const Touch::InventoryPane* pane, int itemId); + bool isAllowed( int slot ); + std::vector getItems( const Touch::InventoryPane* forPane ); + //const ItemList& getItems(const ItemPane* forPane); +private: + void setupPane(); + + void drawSlotItemAt(Tesselator& t, const ItemInstance* item, int x, int y, bool selected); + bool handleAddItem(FillingContainer* from, FillingContainer* to, int itemIndex); + void handleRenderPane(Touch::InventoryPane* pane, Tesselator& t, int xm, int ym, float a); + + std::string currentItemDesc; + ImageButton btnClose; + Touch::THeader bHeader; + Touch::THeader bHeaderChest; + + Touch::InventoryPane* inventoryPane; + Touch::InventoryPane* chestPane; + IntRectangle panesBbox; + + std::vector inventoryItems; + std::vector chestItems; + bool doRecreatePane; + + int selectedSlot; + + // GUI elements such as 9-Patches + NinePatchLayer* guiBackground; + NinePatchLayer* guiSlot; + NinePatchLayer* guiSlotMarked; + NinePatchLayer* guiSlotMarker; + NinePatchLayer* guiPaneFrame; + Player* player; + ChestTileEntity* chest; +}; + diff --git a/src/client/gui/screens/ChooseLevelScreen.h b/src/client/gui/screens/ChooseLevelScreen.h index 74d5341..069608a 100755 --- a/src/client/gui/screens/ChooseLevelScreen.h +++ b/src/client/gui/screens/ChooseLevelScreen.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__ChooseLevelScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__ChooseLevelScreen_H__ - -#include "../Screen.h" -#include "../../../world/level/storage/LevelStorageSource.h" - -class ChooseLevelScreen: public Screen -{ -public: - void init(); - -protected: - std::string getUniqueLevelName(const std::string& level); - -private: - void loadLevelSource(); - - LevelSummaryList levels; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__ChooseLevelScreen_H__*/ +#pragma once + +#include "../Screen.h" +#include "../../../world/level/storage/LevelStorageSource.h" + +class ChooseLevelScreen: public Screen +{ +public: + void init(); + +protected: + std::string getUniqueLevelName(const std::string& level); + +private: + void loadLevelSource(); + + LevelSummaryList levels; +}; + diff --git a/src/client/gui/screens/ConfirmScreen.h b/src/client/gui/screens/ConfirmScreen.h index 0fedbe9..db834ae 100755 --- a/src/client/gui/screens/ConfirmScreen.h +++ b/src/client/gui/screens/ConfirmScreen.h @@ -1,40 +1,38 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__ConfirmScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__ConfirmScreen_H__ - -//package net.minecraft.client.gui; - -#include "../Screen.h" -#include - -class ConfirmScreen: public Screen -{ - typedef Screen super; -public: - ConfirmScreen(Screen* parent_, const std::string& title1_, const std::string& title2_, int id_); - ConfirmScreen(Screen* parent_, const std::string& title1_, const std::string& title2_, const std::string& yesButton, const std::string& noButton, int id_); - ~ConfirmScreen(); - - void init(); - void setupPositions(); - - bool handleBackEvent(bool isDown); - void render(int xm, int ym, float a); -protected: - void buttonClicked(Button* button); - - virtual void postResult(bool isOk); - - Screen* parent; - int id; -private: - std::string title1; - std::string title2; - - std::string yesButtonText; - std::string noButtonText; - - Button* yesButton; // 0 - Button* noButton; // 1 -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__ConfirmScreen_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include "../Screen.h" +#include + +class ConfirmScreen: public Screen +{ + typedef Screen super; +public: + ConfirmScreen(Screen* parent_, const std::string& title1_, const std::string& title2_, int id_); + ConfirmScreen(Screen* parent_, const std::string& title1_, const std::string& title2_, const std::string& yesButton, const std::string& noButton, int id_); + ~ConfirmScreen(); + + void init(); + void setupPositions(); + + bool handleBackEvent(bool isDown); + void render(int xm, int ym, float a); +protected: + void buttonClicked(Button* button); + + virtual void postResult(bool isOk); + + Screen* parent; + int id; +private: + std::string title1; + std::string title2; + + std::string yesButtonText; + std::string noButtonText; + + Button* yesButton; // 0 + Button* noButton; // 1 +}; + diff --git a/src/client/gui/screens/ConsoleScreen.h b/src/client/gui/screens/ConsoleScreen.h index e0074b9..f366ff9 100644 --- a/src/client/gui/screens/ConsoleScreen.h +++ b/src/client/gui/screens/ConsoleScreen.h @@ -1,5 +1,4 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__ConsoleScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__ConsoleScreen_H__ +#pragma once #include "../Screen.h" #include @@ -31,4 +30,3 @@ private: int _cursorBlink; // tick counter for cursor blink }; -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__ConsoleScreen_H__*/ diff --git a/src/client/gui/screens/CreditsScreen.h b/src/client/gui/screens/CreditsScreen.h index 961b8d3..8739307 100644 --- a/src/client/gui/screens/CreditsScreen.h +++ b/src/client/gui/screens/CreditsScreen.h @@ -1,5 +1,4 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__CreditsScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__CreditsScreen_H__ +#pragma once #include "../Screen.h" #include "../components/Button.h" @@ -29,4 +28,3 @@ private: float _scrollSpeed; }; -#endif /* NET_MINECRAFT_CLIENT_GUI_SCREENS__CreditsScreen_H__ */ diff --git a/src/client/gui/screens/DeathScreen.h b/src/client/gui/screens/DeathScreen.h index 8a728ce..ba1e6ed 100755 --- a/src/client/gui/screens/DeathScreen.h +++ b/src/client/gui/screens/DeathScreen.h @@ -1,30 +1,28 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__DeathScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__DeathScreen_H__ - -#include "../Screen.h" -class Button; - -class DeathScreen: public Screen -{ -public: - DeathScreen(); - - virtual ~DeathScreen(); - - void init(); - - void setupPositions(); - - void tick(); - void render(int xm, int ym, float a); - - void buttonClicked(Button* button); - -private: - Button* bRespawn; - Button* bTitle; - bool _hasChosen; - int _tick; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__DeathScreen_H__*/ +#pragma once + +#include "../Screen.h" +class Button; + +class DeathScreen: public Screen +{ +public: + DeathScreen(); + + virtual ~DeathScreen(); + + void init(); + + void setupPositions(); + + void tick(); + void render(int xm, int ym, float a); + + void buttonClicked(Button* button); + +private: + Button* bRespawn; + Button* bTitle; + bool _hasChosen; + int _tick; +}; + diff --git a/src/client/gui/screens/DialogDefinitions.h b/src/client/gui/screens/DialogDefinitions.h index 886e6a2..a48a070 100755 --- a/src/client/gui/screens/DialogDefinitions.h +++ b/src/client/gui/screens/DialogDefinitions.h @@ -1,13 +1,11 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__DialogDefinitions_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__DialogDefinitions_H__ - -class DialogDefinitions { -public: - static const int DIALOG_CREATE_NEW_WORLD = 1; - static const int DIALOG_NEW_CHAT_MESSAGE = 2; - static const int DIALOG_MAINMENU_OPTIONS = 3; - static const int DIALOG_RENAME_MP_WORLD = 4; - static const int DIALOG_DEMO_FEATURE_DISABLED = 98; -}; - -#endif /*#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__DialogDefinitions_H__*/ +#pragma once + +class DialogDefinitions { +public: + static const int DIALOG_CREATE_NEW_WORLD = 1; + static const int DIALOG_NEW_CHAT_MESSAGE = 2; + static const int DIALOG_MAINMENU_OPTIONS = 3; + static const int DIALOG_RENAME_MP_WORLD = 4; + static const int DIALOG_DEMO_FEATURE_DISABLED = 98; +}; + diff --git a/src/client/gui/screens/DisconnectionScreen.h b/src/client/gui/screens/DisconnectionScreen.h index f32530f..fb2a331 100755 --- a/src/client/gui/screens/DisconnectionScreen.h +++ b/src/client/gui/screens/DisconnectionScreen.h @@ -1,57 +1,55 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__DisconnectionScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__DisconnectionScreen_H__ - -#include "../Screen.h" -#include "../Font.h" -#include "../components/Button.h" -#include "../../Minecraft.h" -#include - -class DisconnectionScreen: public Screen -{ - typedef Screen super; -public: - DisconnectionScreen(const std::string& msg) - : _msg(msg), - _back(NULL) - {} - - ~DisconnectionScreen() { - delete _back; - } - - void init() { - if (/* minecraft->useTouchscreen() */ true) - _back = new Touch::TButton(1, "Ok"); - else - _back = new Button(1, "Ok"); - - buttons.push_back(_back); - tabButtons.push_back(_back); - - _back->width = 128; - _back->x = (width - _back->width) / 2; - _back->y = height / 2; - } - - void render( int xm, int ym, float a ) { - renderBackground(); - super::render(xm, ym, a); - - int center = (width - minecraft->font->width(_msg)) / 2; - minecraft->font->drawShadow(_msg, (float)center, (float)(height / 2 - 32), 0xffffffff); - } - - void buttonClicked(Button* button) { - if (button->id == _back->id) { - minecraft->leaveGame(); - } - } - bool isInGameScreen() { return false; } - -private: - std::string _msg; - Button* _back; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__DisconnectionScreen_H__*/ +#pragma once + +#include "../Screen.h" +#include "../Font.h" +#include "../components/Button.h" +#include "../../Minecraft.h" +#include + +class DisconnectionScreen: public Screen +{ + typedef Screen super; +public: + DisconnectionScreen(const std::string& msg) + : _msg(msg), + _back(NULL) + {} + + ~DisconnectionScreen() { + delete _back; + } + + void init() { + if (/* minecraft->useTouchscreen() */ true) + _back = new Touch::TButton(1, "Ok"); + else + _back = new Button(1, "Ok"); + + buttons.push_back(_back); + tabButtons.push_back(_back); + + _back->width = 128; + _back->x = (width - _back->width) / 2; + _back->y = height / 2; + } + + void render( int xm, int ym, float a ) { + renderBackground(); + super::render(xm, ym, a); + + int center = (width - minecraft->font->width(_msg)) / 2; + minecraft->font->drawShadow(_msg, (float)center, (float)(height / 2 - 32), 0xffffffff); + } + + void buttonClicked(Button* button) { + if (button->id == _back->id) { + minecraft->leaveGame(); + } + } + bool isInGameScreen() { return false; } + +private: + std::string _msg; + Button* _back; +}; + diff --git a/src/client/gui/screens/FurnaceScreen.h b/src/client/gui/screens/FurnaceScreen.h index d359abd..61dc95f 100755 --- a/src/client/gui/screens/FurnaceScreen.h +++ b/src/client/gui/screens/FurnaceScreen.h @@ -1,84 +1,82 @@ -#ifndef _FURNACESCREEN_H__ -#define _FURNACESCREEN_H__ - -#include "BaseContainerScreen.h" - -#include "../components/InventoryPane.h" -#include "../components/Button.h" - -class Font; -class CItem; -class Textures; -class NinePatchLayer; -class Tesselator; - -class FurnaceScreen: public BaseContainerScreen, - public Touch::IInventoryPaneCallback -{ - typedef BaseContainerScreen super; - typedef std::vector ItemList; -public: - FurnaceScreen(Player* player, FurnaceTileEntity* furnace); - ~FurnaceScreen(); - - void init(); - void setupPositions(); - - void tick(); - void render(int xm, int ym, float a); - bool renderGameBehind(); - void buttonClicked(Button* button); - - // IInventoryPaneCallback - bool addItem(const Touch::InventoryPane* pane, int itemId); - bool isAllowed( int slot ); - std::vector getItems( const Touch::InventoryPane* forPane ); -private: - //void addItem(Recipe* recipe); - void recheckRecipes(); - - void clearItems(); - void updateResult(const ItemInstance* item); - void setupInventoryPane(); - void updateItems(); - - void drawSlotItemAt(Tesselator& t, const ItemInstance* item, int x, int y, bool selected); - ItemInstance moveOver(const ItemInstance* item, int maxCount); - void takeAndClearSlot( int slot ); - bool handleAddItem( int slot, const ItemInstance* item ); - void handleRenderPane(Touch::InventoryPane* pane, Tesselator& t, int xm, int ym, float a); - bool canMoveToFurnace(int inventorySlot, const ItemInstance* item); - ItemList _items; - - std::string currentItemDesc; - ItemInstance burnResult; - float descWidth; - ImageButton btnClose; - BlankButton btnIngredient; - BlankButton btnFuel; - BlankButton btnResult; - Touch::THeader bHeader; - - Touch::InventoryPane* inventoryPane; - IntRectangle inventoryPaneRect; - - ItemList listFuel; - ItemList listIngredient; - std::vector inventorySlots; - std::vector inventoryItems; - bool doRecreatePane; - - int selectedSlot; - int lastBurnTypeId; - - // GUI elements such as 9-Patches - NinePatchLayer* guiBackground; - NinePatchLayer* guiSlot; - NinePatchLayer* guiSlotMarked; - NinePatchLayer* guiSlotMarker; - NinePatchLayer* guiPaneFrame; - Player* player; - FurnaceTileEntity* furnace; -}; - -#endif /*_FURNACESCREEN_H__*/ +#pragma once + +#include "BaseContainerScreen.h" + +#include "../components/InventoryPane.h" +#include "../components/Button.h" + +class Font; +class CItem; +class Textures; +class NinePatchLayer; +class Tesselator; + +class FurnaceScreen: public BaseContainerScreen, + public Touch::IInventoryPaneCallback +{ + typedef BaseContainerScreen super; + typedef std::vector ItemList; +public: + FurnaceScreen(Player* player, FurnaceTileEntity* furnace); + ~FurnaceScreen(); + + void init(); + void setupPositions(); + + void tick(); + void render(int xm, int ym, float a); + bool renderGameBehind(); + void buttonClicked(Button* button); + + // IInventoryPaneCallback + bool addItem(const Touch::InventoryPane* pane, int itemId); + bool isAllowed( int slot ); + std::vector getItems( const Touch::InventoryPane* forPane ); +private: + //void addItem(Recipe* recipe); + void recheckRecipes(); + + void clearItems(); + void updateResult(const ItemInstance* item); + void setupInventoryPane(); + void updateItems(); + + void drawSlotItemAt(Tesselator& t, const ItemInstance* item, int x, int y, bool selected); + ItemInstance moveOver(const ItemInstance* item, int maxCount); + void takeAndClearSlot( int slot ); + bool handleAddItem( int slot, const ItemInstance* item ); + void handleRenderPane(Touch::InventoryPane* pane, Tesselator& t, int xm, int ym, float a); + bool canMoveToFurnace(int inventorySlot, const ItemInstance* item); + ItemList _items; + + std::string currentItemDesc; + ItemInstance burnResult; + float descWidth; + ImageButton btnClose; + BlankButton btnIngredient; + BlankButton btnFuel; + BlankButton btnResult; + Touch::THeader bHeader; + + Touch::InventoryPane* inventoryPane; + IntRectangle inventoryPaneRect; + + ItemList listFuel; + ItemList listIngredient; + std::vector inventorySlots; + std::vector inventoryItems; + bool doRecreatePane; + + int selectedSlot; + int lastBurnTypeId; + + // GUI elements such as 9-Patches + NinePatchLayer* guiBackground; + NinePatchLayer* guiSlot; + NinePatchLayer* guiSlotMarked; + NinePatchLayer* guiSlotMarker; + NinePatchLayer* guiPaneFrame; + Player* player; + FurnaceTileEntity* furnace; +}; + diff --git a/src/client/gui/screens/InBedScreen.h b/src/client/gui/screens/InBedScreen.h index 1004088..1fa8121 100755 --- a/src/client/gui/screens/InBedScreen.h +++ b/src/client/gui/screens/InBedScreen.h @@ -1,26 +1,24 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__InBedScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__InBedScreen_H__ - -#include "../Screen.h" -class Button; - -class InBedScreen: public Screen -{ -public: - InBedScreen(); - - virtual ~InBedScreen(); - - void init(); - - void setupPositions(); - - void render(int xm, int ym, float a); - - void buttonClicked(Button* button); - -private: - Button* bWakeUp; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__InBedScreen_H__*/ +#pragma once + +#include "../Screen.h" +class Button; + +class InBedScreen: public Screen +{ +public: + InBedScreen(); + + virtual ~InBedScreen(); + + void init(); + + void setupPositions(); + + void render(int xm, int ym, float a); + + void buttonClicked(Button* button); + +private: + Button* bWakeUp; +}; + diff --git a/src/client/gui/screens/IngameBlockSelectionScreen.h b/src/client/gui/screens/IngameBlockSelectionScreen.h index affd6af..cbe3b6e 100755 --- a/src/client/gui/screens/IngameBlockSelectionScreen.h +++ b/src/client/gui/screens/IngameBlockSelectionScreen.h @@ -1,59 +1,57 @@ -#ifndef _MINECRAFT_INGAMEBLOCKSELECTIONSCREEN_H_ -#define _MINECRAFT_INGAMEBLOCKSELECTIONSCREEN_H_ - -#include "../Screen.h" -#include "../../player/input/touchscreen/TouchAreaModel.h" -#include "../components/Button.h" - -class IngameBlockSelectionScreen : public Screen -{ - typedef Screen super; -public: - IngameBlockSelectionScreen(); - virtual ~IngameBlockSelectionScreen() {} - - virtual void init() override; - virtual void removed() override; - - void render(int xm, int ym, float a) override; - -protected: - virtual void mouseClicked(int x, int y, int buttonNum) override; - virtual void mouseReleased(int x, int y, int buttonNum) override; - - virtual void buttonClicked(Button* button) override; - - // wheel input for creative inventory scrolling - virtual void mouseWheel(int dx, int dy, int xm, int ym) override; - - virtual void keyPressed(int eventKey) override; -private: - void renderSlots(); - void renderSlot(int slot, int x, int y, float a); - void renderDemoOverlay(); - - int getSelectedSlot(int x, int y); - void selectSlotAndClose(); - - //int getLinearSlotId(int x, int y); - int getSlotPosX(int slotX); - int getSlotPosY(int slotY); - - int getSlotHeight(); - - bool isAllowed(int slot); - -private: - int InventoryCols; - int InventoryRows; - int InventorySize; - - int selectedItem; - bool _pendingQuit; - - Button bArmor; - - RectangleArea _area; -}; - -#endif +#pragma once + +#include "../Screen.h" +#include "../../player/input/touchscreen/TouchAreaModel.h" +#include "../components/Button.h" + +class IngameBlockSelectionScreen : public Screen +{ + typedef Screen super; +public: + IngameBlockSelectionScreen(); + virtual ~IngameBlockSelectionScreen() {} + + virtual void init() override; + virtual void removed() override; + + void render(int xm, int ym, float a) override; + +protected: + virtual void mouseClicked(int x, int y, int buttonNum) override; + virtual void mouseReleased(int x, int y, int buttonNum) override; + + virtual void buttonClicked(Button* button) override; + + // wheel input for creative inventory scrolling + virtual void mouseWheel(int dx, int dy, int xm, int ym) override; + + virtual void keyPressed(int eventKey) override; +private: + void renderSlots(); + void renderSlot(int slot, int x, int y, float a); + void renderDemoOverlay(); + + int getSelectedSlot(int x, int y); + void selectSlotAndClose(); + + //int getLinearSlotId(int x, int y); + int getSlotPosX(int slotX); + int getSlotPosY(int slotY); + + int getSlotHeight(); + + bool isAllowed(int slot); + +private: + int InventoryCols; + int InventoryRows; + int InventorySize; + + int selectedItem; + bool _pendingQuit; + + Button bArmor; + + RectangleArea _area; +}; + diff --git a/src/client/gui/screens/JoinGameScreen.h b/src/client/gui/screens/JoinGameScreen.h index 4c6fc20..c0cba87 100755 --- a/src/client/gui/screens/JoinGameScreen.h +++ b/src/client/gui/screens/JoinGameScreen.h @@ -1,70 +1,68 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__JoinGameScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__JoinGameScreen_H__ - -#include "../Screen.h" -#include "../components/Button.h" -#include "../components/ScrolledSelectionList.h" -#include "../../Minecraft.h" -#include "../../../network/RakNetInstance.h" - - -class JoinGameScreen; - -class AvailableGamesList : public ScrolledSelectionList -{ - int selectedItem; - ServerList copiedServerList; - - friend class JoinGameScreen; - -public: - - AvailableGamesList(Minecraft* _minecraft, int _width, int _height) - : ScrolledSelectionList(_minecraft, _width, _height, 24, _height - 30, 28) - { - } - -protected: - - virtual int getNumberOfItems() { return (int)copiedServerList.size(); } - - virtual void selectItem(int item, bool doubleClick) { selectedItem = item; } - virtual bool isSelectedItem(int item) { return item == selectedItem; } - - virtual void renderBackground() {} - virtual void renderItem(int i, int x, int y, int h, Tesselator& t) - { - const PingedCompatibleServer& s = copiedServerList[i]; - unsigned int color = s.isSpecial? 0xff00b0 : 0xffffa0; - drawString(minecraft->font, s.name.C_String(), x, y + 2, color); - drawString(minecraft->font, s.address.ToString(false), x, y + 16, 0xffffa0); - } -}; - -class JoinGameScreen: public Screen -{ -public: - JoinGameScreen(); - virtual ~JoinGameScreen(); - - void init(); - void setupPositions(); - - virtual bool handleBackEvent(bool isDown); - - virtual bool isIndexValid(int index); - - virtual void tick(); - - void render(int xm, int ym, float a); - - void buttonClicked(Button* button); - - bool isInGameScreen(); -private: - Button bJoin; - Button bBack; - AvailableGamesList* gamesList; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__JoinGameScreen_H__*/ +#pragma once + +#include "../Screen.h" +#include "../components/Button.h" +#include "../components/ScrolledSelectionList.h" +#include "../../Minecraft.h" +#include "../../../network/RakNetInstance.h" + + +class JoinGameScreen; + +class AvailableGamesList : public ScrolledSelectionList +{ + int selectedItem; + ServerList copiedServerList; + + friend class JoinGameScreen; + +public: + + AvailableGamesList(Minecraft* _minecraft, int _width, int _height) + : ScrolledSelectionList(_minecraft, _width, _height, 24, _height - 30, 28) + { + } + +protected: + + virtual int getNumberOfItems() { return (int)copiedServerList.size(); } + + virtual void selectItem(int item, bool doubleClick) { selectedItem = item; } + virtual bool isSelectedItem(int item) { return item == selectedItem; } + + virtual void renderBackground() {} + virtual void renderItem(int i, int x, int y, int h, Tesselator& t) + { + const PingedCompatibleServer& s = copiedServerList[i]; + unsigned int color = s.isSpecial? 0xff00b0 : 0xffffa0; + drawString(minecraft->font, s.name.C_String(), x, y + 2, color); + drawString(minecraft->font, s.address.ToString(false), x, y + 16, 0xffffa0); + } +}; + +class JoinGameScreen: public Screen +{ +public: + JoinGameScreen(); + virtual ~JoinGameScreen(); + + void init(); + void setupPositions(); + + virtual bool handleBackEvent(bool isDown); + + virtual bool isIndexValid(int index); + + virtual void tick(); + + void render(int xm, int ym, float a); + + void buttonClicked(Button* button); + + bool isInGameScreen(); +private: + Button bJoin; + Button bBack; + AvailableGamesList* gamesList; +}; + diff --git a/src/client/gui/screens/OptionsScreen.h b/src/client/gui/screens/OptionsScreen.h index b02c7b8..41589e7 100755 --- a/src/client/gui/screens/OptionsScreen.h +++ b/src/client/gui/screens/OptionsScreen.h @@ -1,49 +1,47 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__OptionsScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__OptionsScreen_H__ - -#include "../Screen.h" -#include "../components/Button.h" -#include "../components/OptionsGroup.h" - -class ImageButton; -class OptionsPane; - -class OptionsScreen: public Screen -{ - typedef Screen super; - - void init(); - void generateOptionScreens(); - -public: - OptionsScreen(); - ~OptionsScreen(); - - void setupPositions(); - void buttonClicked(Button* button); - void render(int xm, int ym, float a); - void removed(); - void selectCategory(int index); - - virtual void mouseClicked(int x, int y, int buttonNum); - virtual void mouseReleased(int x, int y, int buttonNum); - virtual void keyPressed(int eventKey); - virtual void charPressed(char inputChar); - - virtual void tick(); - -private: - Touch::THeader* bHeader; - ImageButton* btnClose; - - Button* btnCredits; // <-- ADD THIS - - std::vector categoryButtons; - std::vector optionPanes; - - OptionsGroup* currentOptionsGroup; - - int selectedCategory; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__OptionsScreen_H__*/ \ No newline at end of file +#pragma once + +#include "../Screen.h" +#include "../components/Button.h" +#include "../components/OptionsGroup.h" + +class ImageButton; +class OptionsPane; + +class OptionsScreen: public Screen +{ + typedef Screen super; + + void init(); + void generateOptionScreens(); + +public: + OptionsScreen(); + ~OptionsScreen(); + + void setupPositions(); + void buttonClicked(Button* button); + void render(int xm, int ym, float a); + void removed(); + void selectCategory(int index); + + virtual void mouseClicked(int x, int y, int buttonNum); + virtual void mouseReleased(int x, int y, int buttonNum); + virtual void keyPressed(int eventKey); + virtual void charPressed(char inputChar); + + virtual void tick(); + +private: + Touch::THeader* bHeader; + ImageButton* btnClose; + + Button* btnCredits; // <-- ADD THIS + + std::vector categoryButtons; + std::vector optionPanes; + + OptionsGroup* currentOptionsGroup; + + int selectedCategory; +}; + diff --git a/src/client/gui/screens/PauseScreen.h b/src/client/gui/screens/PauseScreen.h index 4098511..54ad654 100755 --- a/src/client/gui/screens/PauseScreen.h +++ b/src/client/gui/screens/PauseScreen.h @@ -1,45 +1,43 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI__PauseScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI__PauseScreen_H__ - -//package net.minecraft.client.gui; - -#include "../Screen.h" -#include "../components/ImageButton.h" - -class Button; - -class PauseScreen: public Screen -{ - typedef Screen super; -public: - PauseScreen(bool wasBackPaused); - ~PauseScreen(); - - void init(); - void setupPositions(); - - void tick(); - void render(int xm, int ym, float a); -protected: - void buttonClicked(Button* button); -private: - void updateServerVisibilityText(); - - int saveStep; - int visibleTime; - bool wasBackPaused; - - Button* bContinue; - Button* bQuit; - Button* bQuitAndSaveLocally; - Button* bServerVisibility; - Button* bOptions; - - // Button* bThirdPerson; - - // OptionButton bSound; - OptionButton bThirdPerson; - OptionButton bHideGui; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI__PauseScreen_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include "../Screen.h" +#include "../components/ImageButton.h" + +class Button; + +class PauseScreen: public Screen +{ + typedef Screen super; +public: + PauseScreen(bool wasBackPaused); + ~PauseScreen(); + + void init(); + void setupPositions(); + + void tick(); + void render(int xm, int ym, float a); +protected: + void buttonClicked(Button* button); +private: + void updateServerVisibilityText(); + + int saveStep; + int visibleTime; + bool wasBackPaused; + + Button* bContinue; + Button* bQuit; + Button* bQuitAndSaveLocally; + Button* bServerVisibility; + Button* bOptions; + + // Button* bThirdPerson; + + // OptionButton bSound; + OptionButton bThirdPerson; + OptionButton bHideGui; +}; + diff --git a/src/client/gui/screens/PrerenderTilesScreen.h b/src/client/gui/screens/PrerenderTilesScreen.h index faa405d..558e0bc 100755 --- a/src/client/gui/screens/PrerenderTilesScreen.h +++ b/src/client/gui/screens/PrerenderTilesScreen.h @@ -1,162 +1,160 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__PrerenderTilesScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__PrerenderTilesScreen_H__ - -#include "../Screen.h" - -#include "../../renderer/GameRenderer.h" -#include "../../renderer/entity/ItemRenderer.h" -#include "../../../world/item/ItemInstance.h" -#include "../../../world/level/tile/Tile.h" - -#include "../../../world/entity/player/Inventory.h" -#include "../../renderer/Tesselator.h" -#include "../../../world/item/crafting/Recipes.h" -#include "../../../world/item/crafting/FurnaceRecipes.h" -#include "../../../world/level/tile/LeafTile.h" -#include "../../renderer/TileRenderer.h" - -class PrerenderTilesScreen: public Screen -{ -public: - void init() { - Player p(minecraft->level, true); - Inventory _inventory(&p, true); - Inventory* inventory = &_inventory; - - // Copy over the inventory items - for (int i = Inventory::MAX_SELECTION_SIZE; i < inventory->getContainerSize(); ++i) - addItem(inventory->getItem(i)); - - // Fill the inventory with all the recipe items we don't already have: furnace - const FurnaceRecipes::Map& furnaceRecipes = FurnaceRecipes::getInstance()->getRecipes(); - for (FurnaceRecipes::Map::const_iterator cit = furnaceRecipes.begin(); cit != furnaceRecipes.end(); ++cit) { - ItemInstance ingredient(cit->first, 1, 0); - addItem(&ingredient); - ItemInstance result = cit->second; - addItem(&result); - } - - // Fill the inventory with all the recipe items we don't already have: crafting - const RecipeList& recipes = Recipes::getInstance()->getRecipes(); - for (unsigned int i = 0; i < recipes.size(); ++i) { - - std::vector items; - std::vector required = recipes[i]->getItemPack().getItemInstances(); - items.push_back(recipes[i]->getResultItem()); - items.insert(items.end(), required.begin(), required.end()); - - for (unsigned int i = 0; i < items.size(); ++i) { - ItemInstance& item = items[i]; - addItem(&item); - } - } - - // Manually added stuff - // Example: the one that's spawned from tiles when destroyed - int items[] = { - Tile::sapling->id, LeafTile::BIRCH_LEAF, - Tile::sapling->id, LeafTile::EVERGREEN_LEAF, - Tile::sapling->id, LeafTile::NORMAL_LEAF, - Tile::dirt->id, 0, - Tile::reeds->id, 0, - Tile::gravel->id, 0, - Item::apple->id, 0, - Tile::grass_carried->id, 0, - Tile::web->id, 0, - Item::sign->id, 0, - }; - for (int i = 0; i < sizeof(items)/sizeof(int); i += 2) { - ItemInstance item(items[i], 1, items[i+1]); - addItem(&item); - } - } - - void render( int xm, int ym, float a ) { - static Stopwatch w; - w.start(); - - glDisable2(GL_DEPTH_TEST); - fill(0, 0, width, height, 0xffff00ff); - //fill(0, 0, width, height, 0xff333333); - glColor4f2(1, 1, 1, 1); - glEnable2(GL_BLEND); - - LOGI("--------------------\n"); - /*int j = 0; - for (int i = Inventory::MAX_SELECTION_SIZE; i < inventory->getContainerSize(); ++i) { - - ItemInstance* item = inventory->getItem(i); - if (!item) continue; - - //LOGI("desc: %d - %s. %d\n", i, item->toString().c_str()); - - int x = j%16 * 16; - int y = j/16 * 16; - - //Tesselator::instance.color(0xffffffff); - //minecraft->textures->loadAndBindTexture("gui/gui2.png"); - //glColor4f2(0.2f, 0.5f, 0.2f, 1); - //blit(x, y, 4 + 20 * (i%9), 4, 16, 16, 15, 15); - //glColor4f2(1, 1, 1, 1); - - if (item->id < 256 && TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) { - LOGI("0, %d, %d, %d, 0\n", j, item->id, item->getAuxValue()); - ItemRenderer::renderGuiItemCorrect(minecraft->font, minecraft->textures, item, x, y); - } else if (item->getIcon() >= 0) { - LOGI("1, %d, %d, %d, %d\n", j, item->id, item->getAuxValue(), item->getIcon()); - } - ++j; - }*/ - int j = 0; - for(std::vector::iterator i = mItems.begin(); i != mItems.end(); ++i) { - ItemInstance* item = &(*i); - - //LOGI("desc: %d - %s. %d\n", i, item->toString().c_str()); - - int x = j%16 * 16; - int y = j/16 * 16; - if (item->id < 256 && TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) { - LOGI("0, %d, %d, %d, 0\n", j, item->id, item->getAuxValue()); - ItemRenderer::renderGuiItemCorrect(minecraft->font, minecraft->textures, item, x, y); - } else if (item->getIcon() >= 0) { - LOGI("1, %d, %d, %d, %d\n", j, item->id, item->getAuxValue(), item->getIcon()); - } - j++; - } - //@todo: blit out something famous here - - //glRotatef2(-180, 1, 0, 0); - glEnable2(GL_DEPTH_TEST); - glDisable2(GL_BLEND); - - w.stop(); - w.printEvery(100, "render-blocksel"); - } - void removed(){} - - void addItem(ItemInstance* item) { - if(item == NULL) - return; - if (item->getAuxValue() < 0) return; - - bool found = false; - for(std::vector::iterator i = mItems.begin(); i != mItems.end(); ++i) { - ItemInstance *jitem = &*i; - if(jitem->id != item->id) continue; - if(jitem->isStackedByData() && jitem->getAuxValue() != item->getAuxValue()) continue; - - found = true; - break; - } - - if (!found) { - LOGI("Adding item: %s\n", item->getDescriptionId().c_str()); - mItems.push_back(*item); - } - } - -private: - std::vector mItems; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__PrerenderTilesScreen_H__*/ +#pragma once + +#include "../Screen.h" + +#include "../../renderer/GameRenderer.h" +#include "../../renderer/entity/ItemRenderer.h" +#include "../../../world/item/ItemInstance.h" +#include "../../../world/level/tile/Tile.h" + +#include "../../../world/entity/player/Inventory.h" +#include "../../renderer/Tesselator.h" +#include "../../../world/item/crafting/Recipes.h" +#include "../../../world/item/crafting/FurnaceRecipes.h" +#include "../../../world/level/tile/LeafTile.h" +#include "../../renderer/TileRenderer.h" + +class PrerenderTilesScreen: public Screen +{ +public: + void init() { + Player p(minecraft->level, true); + Inventory _inventory(&p, true); + Inventory* inventory = &_inventory; + + // Copy over the inventory items + for (int i = Inventory::MAX_SELECTION_SIZE; i < inventory->getContainerSize(); ++i) + addItem(inventory->getItem(i)); + + // Fill the inventory with all the recipe items we don't already have: furnace + const FurnaceRecipes::Map& furnaceRecipes = FurnaceRecipes::getInstance()->getRecipes(); + for (FurnaceRecipes::Map::const_iterator cit = furnaceRecipes.begin(); cit != furnaceRecipes.end(); ++cit) { + ItemInstance ingredient(cit->first, 1, 0); + addItem(&ingredient); + ItemInstance result = cit->second; + addItem(&result); + } + + // Fill the inventory with all the recipe items we don't already have: crafting + const RecipeList& recipes = Recipes::getInstance()->getRecipes(); + for (unsigned int i = 0; i < recipes.size(); ++i) { + + std::vector items; + std::vector required = recipes[i]->getItemPack().getItemInstances(); + items.push_back(recipes[i]->getResultItem()); + items.insert(items.end(), required.begin(), required.end()); + + for (unsigned int i = 0; i < items.size(); ++i) { + ItemInstance& item = items[i]; + addItem(&item); + } + } + + // Manually added stuff + // Example: the one that's spawned from tiles when destroyed + int items[] = { + Tile::sapling->id, LeafTile::BIRCH_LEAF, + Tile::sapling->id, LeafTile::EVERGREEN_LEAF, + Tile::sapling->id, LeafTile::NORMAL_LEAF, + Tile::dirt->id, 0, + Tile::reeds->id, 0, + Tile::gravel->id, 0, + Item::apple->id, 0, + Tile::grass_carried->id, 0, + Tile::web->id, 0, + Item::sign->id, 0, + }; + for (int i = 0; i < sizeof(items)/sizeof(int); i += 2) { + ItemInstance item(items[i], 1, items[i+1]); + addItem(&item); + } + } + + void render( int xm, int ym, float a ) { + static Stopwatch w; + w.start(); + + glDisable2(GL_DEPTH_TEST); + fill(0, 0, width, height, 0xffff00ff); + //fill(0, 0, width, height, 0xff333333); + glColor4f2(1, 1, 1, 1); + glEnable2(GL_BLEND); + + LOGI("--------------------\n"); + /*int j = 0; + for (int i = Inventory::MAX_SELECTION_SIZE; i < inventory->getContainerSize(); ++i) { + + ItemInstance* item = inventory->getItem(i); + if (!item) continue; + + //LOGI("desc: %d - %s. %d\n", i, item->toString().c_str()); + + int x = j%16 * 16; + int y = j/16 * 16; + + //Tesselator::instance.color(0xffffffff); + //minecraft->textures->loadAndBindTexture("gui/gui2.png"); + //glColor4f2(0.2f, 0.5f, 0.2f, 1); + //blit(x, y, 4 + 20 * (i%9), 4, 16, 16, 15, 15); + //glColor4f2(1, 1, 1, 1); + + if (item->id < 256 && TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) { + LOGI("0, %d, %d, %d, 0\n", j, item->id, item->getAuxValue()); + ItemRenderer::renderGuiItemCorrect(minecraft->font, minecraft->textures, item, x, y); + } else if (item->getIcon() >= 0) { + LOGI("1, %d, %d, %d, %d\n", j, item->id, item->getAuxValue(), item->getIcon()); + } + ++j; + }*/ + int j = 0; + for(std::vector::iterator i = mItems.begin(); i != mItems.end(); ++i) { + ItemInstance* item = &(*i); + + //LOGI("desc: %d - %s. %d\n", i, item->toString().c_str()); + + int x = j%16 * 16; + int y = j/16 * 16; + if (item->id < 256 && TileRenderer::canRender(Tile::tiles[item->id]->getRenderShape())) { + LOGI("0, %d, %d, %d, 0\n", j, item->id, item->getAuxValue()); + ItemRenderer::renderGuiItemCorrect(minecraft->font, minecraft->textures, item, x, y); + } else if (item->getIcon() >= 0) { + LOGI("1, %d, %d, %d, %d\n", j, item->id, item->getAuxValue(), item->getIcon()); + } + j++; + } + //@todo: blit out something famous here + + //glRotatef2(-180, 1, 0, 0); + glEnable2(GL_DEPTH_TEST); + glDisable2(GL_BLEND); + + w.stop(); + w.printEvery(100, "render-blocksel"); + } + void removed(){} + + void addItem(ItemInstance* item) { + if(item == NULL) + return; + if (item->getAuxValue() < 0) return; + + bool found = false; + for(std::vector::iterator i = mItems.begin(); i != mItems.end(); ++i) { + ItemInstance *jitem = &*i; + if(jitem->id != item->id) continue; + if(jitem->isStackedByData() && jitem->getAuxValue() != item->getAuxValue()) continue; + + found = true; + break; + } + + if (!found) { + LOGI("Adding item: %s\n", item->getDescriptionId().c_str()); + mItems.push_back(*item); + } + } + +private: + std::vector mItems; +}; + diff --git a/src/client/gui/screens/ProgressScreen.h b/src/client/gui/screens/ProgressScreen.h index 762d4fa..8e4d9f4 100755 --- a/src/client/gui/screens/ProgressScreen.h +++ b/src/client/gui/screens/ProgressScreen.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__ProgressScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__ProgressScreen_H__ - -#include "../Screen.h" - -class ProgressScreen: public Screen -{ -public: - ProgressScreen(); - - void render(int xm, int ym, float a); - bool isInGameScreen(); - - virtual void keyPressed(int eventKey) {} - - void tick(); -private: - int ticks; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__ProgressScreen_H__*/ +#pragma once + +#include "../Screen.h" + +class ProgressScreen: public Screen +{ +public: + ProgressScreen(); + + void render(int xm, int ym, float a); + bool isInGameScreen(); + + virtual void keyPressed(int eventKey) {} + + void tick(); +private: + int ticks; +}; + diff --git a/src/client/gui/screens/ScreenChooser.h b/src/client/gui/screens/ScreenChooser.h index 0d20dd0..99e4862 100755 --- a/src/client/gui/screens/ScreenChooser.h +++ b/src/client/gui/screens/ScreenChooser.h @@ -1,30 +1,28 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__ScreenChooser_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__ScreenChooser_H__ - -enum ScreenId { - SCREEN_NONE, - SCREEN_STARTMENU, - SCREEN_JOINGAME, - SCREEN_PAUSE, - SCREEN_PAUSEPREV, - SCREEN_SELECTWORLD, - SCREEN_BLOCKSELECTION, - SCREEN_JOINBYIP, - SCREEN_CONSOLE -}; - -class Screen; -class MinecraftClient; - -class ScreenChooser -{ -public: - ScreenChooser(MinecraftClient& mc) : _mc(mc) {} - - Screen* createScreen(ScreenId id); - Screen* setScreen(ScreenId id); -private: - MinecraftClient& _mc; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__ScreenChooser_H__*/ +#pragma once + +enum ScreenId { + SCREEN_NONE, + SCREEN_STARTMENU, + SCREEN_JOINGAME, + SCREEN_PAUSE, + SCREEN_PAUSEPREV, + SCREEN_SELECTWORLD, + SCREEN_BLOCKSELECTION, + SCREEN_JOINBYIP, + SCREEN_CONSOLE +}; + +class Screen; +class MinecraftClient; + +class ScreenChooser +{ +public: + ScreenChooser(MinecraftClient& mc) : _mc(mc) {} + + Screen* createScreen(ScreenId id); + Screen* setScreen(ScreenId id); +private: + MinecraftClient& _mc; +}; + diff --git a/src/client/gui/screens/SelectWorldScreen.h b/src/client/gui/screens/SelectWorldScreen.h index b5e2f66..563514c 100755 --- a/src/client/gui/screens/SelectWorldScreen.h +++ b/src/client/gui/screens/SelectWorldScreen.h @@ -1,112 +1,110 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__SelectWorldScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__SelectWorldScreen_H__ - -#include "../Screen.h" -#include "../TweenData.h" -#include "../components/Button.h" -#include "../components/RolledSelectionListH.h" -#include "../../../world/level/storage/LevelStorageSource.h" - - -class SelectWorldScreen; -class MinecraftClient; - -// -// Scrolling World selection list -// -class WorldSelectionList : public RolledSelectionListH -{ -public: - WorldSelectionList(MinecraftClient& _minecraft, int _width, int _height); - virtual void tick(); - void stepLeft(); - void stepRight(); - - void commit(); -protected: - virtual int getNumberOfItems(); - virtual void selectItem(int item, bool doubleClick); - virtual bool isSelectedItem(int item); - - virtual void renderBackground() {} - virtual void renderItem(int i, int x, int y, int h, Tesselator& t); - virtual float getPos(float alpha); - virtual void touched() { mode = 0; } - virtual bool capXPosition(); -private: - TweenData td; - void tweenInited(); - - int selectedItem; - int _height; - LevelSummaryList levels; - std::vector _descriptions; - StringVector _imageNames; - - bool hasPickedLevel; - LevelSummary pickedLevel; - - int stoppedTick; - int currentTick; - float accRatio; - int mode; - - friend class SelectWorldScreen; -}; - -// -// Delete World screen -// -#include "ConfirmScreen.h" -class DeleteWorldScreen: public ConfirmScreen -{ -public: - DeleteWorldScreen(const LevelSummary& levelId); -protected: - virtual void postResult(bool isOk); -private: - LevelSummary _level; -}; - - -// -// Select world screen -// -class SelectWorldScreen: public Screen -{ -public: - SelectWorldScreen(); - virtual ~SelectWorldScreen(); - - virtual void init(); - virtual void setupPositions(); - virtual void tick(); - - virtual bool isIndexValid(int index); - virtual bool handleBackEvent(bool isDown); - virtual void buttonClicked(Button* button); - virtual void keyPressed(int eventKey); - - void render(int xm, int ym, float a); - - // mouse wheel scroll (new in desktop implementation) - virtual void mouseWheel(int dx, int dy, int xm, int ym); - - bool isInGameScreen(); -private: - void loadLevelSource(); - std::string getUniqueLevelName(const std::string& level); - - Button bDelete; - Button bCreate; - Button bBack; - Button bWorldView; - WorldSelectionList* worldsList; - LevelSummaryList levels; - - bool _mouseHasBeenUp; - bool _hasStartedLevel; - //LevelStorageSource* levels; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__SelectWorldScreen_H__*/ +#pragma once + +#include "../Screen.h" +#include "../TweenData.h" +#include "../components/Button.h" +#include "../components/RolledSelectionListH.h" +#include "../../../world/level/storage/LevelStorageSource.h" + + +class SelectWorldScreen; +class MinecraftClient; + +// +// Scrolling World selection list +// +class WorldSelectionList : public RolledSelectionListH +{ +public: + WorldSelectionList(MinecraftClient& _minecraft, int _width, int _height); + virtual void tick(); + void stepLeft(); + void stepRight(); + + void commit(); +protected: + virtual int getNumberOfItems(); + virtual void selectItem(int item, bool doubleClick); + virtual bool isSelectedItem(int item); + + virtual void renderBackground() {} + virtual void renderItem(int i, int x, int y, int h, Tesselator& t); + virtual float getPos(float alpha); + virtual void touched() { mode = 0; } + virtual bool capXPosition(); +private: + TweenData td; + void tweenInited(); + + int selectedItem; + int _height; + LevelSummaryList levels; + std::vector _descriptions; + StringVector _imageNames; + + bool hasPickedLevel; + LevelSummary pickedLevel; + + int stoppedTick; + int currentTick; + float accRatio; + int mode; + + friend class SelectWorldScreen; +}; + +// +// Delete World screen +// +#include "ConfirmScreen.h" +class DeleteWorldScreen: public ConfirmScreen +{ +public: + DeleteWorldScreen(const LevelSummary& levelId); +protected: + virtual void postResult(bool isOk); +private: + LevelSummary _level; +}; + + +// +// Select world screen +// +class SelectWorldScreen: public Screen +{ +public: + SelectWorldScreen(); + virtual ~SelectWorldScreen(); + + virtual void init(); + virtual void setupPositions(); + virtual void tick(); + + virtual bool isIndexValid(int index); + virtual bool handleBackEvent(bool isDown); + virtual void buttonClicked(Button* button); + virtual void keyPressed(int eventKey); + + void render(int xm, int ym, float a); + + // mouse wheel scroll (new in desktop implementation) + virtual void mouseWheel(int dx, int dy, int xm, int ym); + + bool isInGameScreen(); +private: + void loadLevelSource(); + std::string getUniqueLevelName(const std::string& level); + + Button bDelete; + Button bCreate; + Button bBack; + Button bWorldView; + WorldSelectionList* worldsList; + LevelSummaryList levels; + + bool _mouseHasBeenUp; + bool _hasStartedLevel; + //LevelStorageSource* levels; +}; + diff --git a/src/client/gui/screens/SimpleChooseLevelScreen.h b/src/client/gui/screens/SimpleChooseLevelScreen.h index 1c88d06..8200a20 100755 --- a/src/client/gui/screens/SimpleChooseLevelScreen.h +++ b/src/client/gui/screens/SimpleChooseLevelScreen.h @@ -1,44 +1,42 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__DemoChooseLevelScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__DemoChooseLevelScreen_H__ - -#include "ChooseLevelScreen.h" -#include "../components/TextBox.h" -#include "../components/Button.h" // for Touch::THeader -class Button; -class ImageButton; - -class SimpleChooseLevelScreen: public ChooseLevelScreen -{ -public: - SimpleChooseLevelScreen(const std::string& levelName); - - virtual ~SimpleChooseLevelScreen(); - - void init(); - void setupPositions(); - void tick(); - - void render(int xm, int ym, float a); - - void buttonClicked(Button* button); - bool handleBackEvent(bool isDown); - virtual void keyPressed(int eventKey); - virtual void mouseClicked(int x, int y, int buttonNum); - -private: - Touch::THeader* bHeader; - Button* bGamemode; - Button* bCheats; - ImageButton* bBack; - Button* bCreate; - bool hasChosen; - - std::string levelName; - int gamemode; - bool cheatsEnabled; - - TextBox tLevelName; - TextBox tSeed; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__DemoChooseLevelScreen_H__*/ +#pragma once + +#include "ChooseLevelScreen.h" +#include "../components/TextBox.h" +#include "../components/Button.h" // for Touch::THeader +class Button; +class ImageButton; + +class SimpleChooseLevelScreen: public ChooseLevelScreen +{ +public: + SimpleChooseLevelScreen(const std::string& levelName); + + virtual ~SimpleChooseLevelScreen(); + + void init(); + void setupPositions(); + void tick(); + + void render(int xm, int ym, float a); + + void buttonClicked(Button* button); + bool handleBackEvent(bool isDown); + virtual void keyPressed(int eventKey); + virtual void mouseClicked(int x, int y, int buttonNum); + +private: + Touch::THeader* bHeader; + Button* bGamemode; + Button* bCheats; + ImageButton* bBack; + Button* bCreate; + bool hasChosen; + + std::string levelName; + int gamemode; + bool cheatsEnabled; + + TextBox tLevelName; + TextBox tSeed; +}; + diff --git a/src/client/gui/screens/StartMenuScreen.h b/src/client/gui/screens/StartMenuScreen.h index e2801fe..1c794fe 100755 --- a/src/client/gui/screens/StartMenuScreen.h +++ b/src/client/gui/screens/StartMenuScreen.h @@ -1,40 +1,38 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__StartMenuScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__StartMenuScreen_H__ - -#include "../Screen.h" -#include "../components/Button.h" -#include "../components/ImageButton.h" - -class StartMenuScreen: public Screen -{ -public: - StartMenuScreen(); - virtual ~StartMenuScreen(); - - void init(); - void setupPositions(); - - void tick(); - void render(int xm, int ym, float a); - - void buttonClicked(Button* button); - virtual void mouseClicked(int x, int y, int buttonNum); - bool handleBackEvent(bool isDown); - bool isInGameScreen(); -private: - - Button bHost; - Button bJoin; - Button bOptions; - ImageButton bQuit; // X button in top-right corner - - std::string copyright; - int copyrightPosX; - - std::string version; - int versionPosX; - - std::string username; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__StartMenuScreen_H__*/ +#pragma once + +#include "../Screen.h" +#include "../components/Button.h" +#include "../components/ImageButton.h" + +class StartMenuScreen: public Screen +{ +public: + StartMenuScreen(); + virtual ~StartMenuScreen(); + + void init(); + void setupPositions(); + + void tick(); + void render(int xm, int ym, float a); + + void buttonClicked(Button* button); + virtual void mouseClicked(int x, int y, int buttonNum); + bool handleBackEvent(bool isDown); + bool isInGameScreen(); +private: + + Button bHost; + Button bJoin; + Button bOptions; + ImageButton bQuit; // X button in top-right corner + + std::string copyright; + int copyrightPosX; + + std::string version; + int versionPosX; + + std::string username; +}; + diff --git a/src/client/gui/screens/TextEditScreen.h b/src/client/gui/screens/TextEditScreen.h index 2fea9fc..7a97d1d 100755 --- a/src/client/gui/screens/TextEditScreen.h +++ b/src/client/gui/screens/TextEditScreen.h @@ -1,35 +1,33 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__TextEditScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__TextEditScreen_H__ - -//package net.minecraft.client.gui; - -#include "../Screen.h" -#include -#include "../components/ImageButton.h" -class SignTileEntity; -class Button; -class TextEditScreen: public Screen -{ - typedef Screen super; -public: - TextEditScreen(SignTileEntity* signEntity); - ~TextEditScreen(); - void init(); - void tick(); - bool handleBackEvent(bool isDown); - void render(int xm, int ym, float a); - virtual void lostFocus(); - virtual void keyPressed(int eventKey); - virtual void charPressed(char inputChar); - void setupPositions(); - void buttonClicked(Button* button); -protected: - bool isShowingKeyboard; - SignTileEntity* sign; - int frame; - int line; -private: - ImageButton btnClose; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__TextEditScreen_H__*/ +#pragma once + +//package net.minecraft.client.gui; + +#include "../Screen.h" +#include +#include "../components/ImageButton.h" +class SignTileEntity; +class Button; +class TextEditScreen: public Screen +{ + typedef Screen super; +public: + TextEditScreen(SignTileEntity* signEntity); + ~TextEditScreen(); + void init(); + void tick(); + bool handleBackEvent(bool isDown); + void render(int xm, int ym, float a); + virtual void lostFocus(); + virtual void keyPressed(int eventKey); + virtual void charPressed(char inputChar); + void setupPositions(); + void buttonClicked(Button* button); +protected: + bool isShowingKeyboard; + SignTileEntity* sign; + int frame; + int line; +private: + ImageButton btnClose; +}; + diff --git a/src/client/gui/screens/UploadPhotoScreen.h b/src/client/gui/screens/UploadPhotoScreen.h index 773f5bb..266f23c 100755 --- a/src/client/gui/screens/UploadPhotoScreen.h +++ b/src/client/gui/screens/UploadPhotoScreen.h @@ -1,36 +1,34 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__UploadPhotoScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__UploadPhotoScreen_H__ - -#include "Screen.h" - -class UploadPhotoScreen : public Screen -{ -public: - - UploadPhotoScreen(); - virtual ~UploadPhotoScreen() {} - - virtual void init(); - - void render(int xm, int ym, float a) { - Screen::render(xm, ym, a); - } - -protected: - - virtual void mouseClicked(int x, int y, int buttonNum); - virtual void mouseReleased(int x, int y, int buttonNum); - virtual void keyPressed(int eventKey); - -private: - - int selectedItem; - - void renderSlots(); - void renderSlot(int slot, int x, int y, float a); - - int getSelectedSlot(int x, int y); - void selectSlotAndClose(); -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__UploadPhotoScreen_H__*/ +#pragma once + +#include "Screen.h" + +class UploadPhotoScreen : public Screen +{ +public: + + UploadPhotoScreen(); + virtual ~UploadPhotoScreen() {} + + virtual void init(); + + void render(int xm, int ym, float a) { + Screen::render(xm, ym, a); + } + +protected: + + virtual void mouseClicked(int x, int y, int buttonNum); + virtual void mouseReleased(int x, int y, int buttonNum); + virtual void keyPressed(int eventKey); + +private: + + int selectedItem; + + void renderSlots(); + void renderSlot(int slot, int x, int y, float a); + + int getSelectedSlot(int x, int y); + void selectSlotAndClose(); +}; + diff --git a/src/client/gui/screens/UsernameScreen.h b/src/client/gui/screens/UsernameScreen.h index c1d750e..02f2830 100644 --- a/src/client/gui/screens/UsernameScreen.h +++ b/src/client/gui/screens/UsernameScreen.h @@ -1,5 +1,4 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS__UsernameScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS__UsernameScreen_H__ +#pragma once #include "../Screen.h" #include "../components/Button.h" @@ -34,4 +33,3 @@ private: int _cursorBlink; }; -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS__UsernameScreen_H__*/ diff --git a/src/client/gui/screens/crafting/CraftingFilters.h b/src/client/gui/screens/crafting/CraftingFilters.h index 8ad3bc3..699447c 100755 --- a/src/client/gui/screens/crafting/CraftingFilters.h +++ b/src/client/gui/screens/crafting/CraftingFilters.h @@ -1,10 +1,8 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_CraftingFilters_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_CraftingFilters_H__ - -class ItemInstance; - -namespace CraftingFilters { - bool isStonecutterItem(const ItemInstance& item); -} - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_CraftingFilters_H__*/ +#pragma once + +class ItemInstance; + +namespace CraftingFilters { + bool isStonecutterItem(const ItemInstance& item); +} + diff --git a/src/client/gui/screens/crafting/PaneCraftingScreen.h b/src/client/gui/screens/crafting/PaneCraftingScreen.h index d20303b..9639181 100755 --- a/src/client/gui/screens/crafting/PaneCraftingScreen.h +++ b/src/client/gui/screens/crafting/PaneCraftingScreen.h @@ -1,106 +1,104 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_PaneCraftingScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_PaneCraftingScreen_H__ - -#include "../../Screen.h" -#include "../../../../world/item/crafting/Recipes.h" -#include "../../../../world/item/ItemInstance.h" - -#include "../../components/ScrollingPane.h" -#include "../../components/ImageButton.h" -#include "../../components/ItemPane.h" - -class Font; -class CItem; -class Textures; -class NinePatchLayer; - -class CraftButton: public ImageButton -{ - typedef ImageButton super; -public: - CraftButton(int id); - ~CraftButton(); - - void init(Textures*); - void setSize(float w, float h); - - void setNumItems(int i) { numItems = i; } - IntRectangle getItemPos(int i); - void renderBg(Minecraft* minecraft, int xm, int ym); -private: - NinePatchLayer* bg; - NinePatchLayer* bgSelected; - int numItems; -}; - -class PaneCraftingScreen: public Screen, - public IItemPaneCallback -{ - typedef Screen super; - typedef std::vector ItemList; -public: - PaneCraftingScreen(int craftingSize); - ~PaneCraftingScreen(); - - void init(); - void setupPositions(); - - void tick(); - void render(int xm, int ym, float a); - bool renderGameBehind(); - bool closeOnPlayerHurt(); - void buttonClicked(Button* button); - void keyPressed( int eventKey ); - - // IItemPaneCallback - void onItemSelected(const ItemPane* forPane, int itemIndexInCurrentCategory); - const std::vector& getItems(const ItemPane* forPane); -protected: - void setSingleCategoryAndIcon(int categoryBitmask, int categoryIcon); -private: - /// Filter out non craftable recipes. - /// The default implementation calls bool filterRecipe(r) for every - /// Recipe r and keeps the ones that returned true. - /// A crafting size filter has already been applied. - virtual void filterRecipes(RecipeList& recipes); - virtual bool filterRecipe(const Recipe& recipe) = 0; - - void initCategories(); - - void addItem(Recipe* recipe); - void recheckRecipes(); - void onItemSelected(int buttonIndex, CItem* item); - void clearCategoryItems(); - - void craftSelectedItem(); - std::vector _categoryButtons; - - ItemList _items; - std::vector _categories; - - int currentCategory; - CItem* currentItem; - std::string currentItemDesc; - std::vector currentCategoryButtons; - ImageButton btnClose; - CraftButton btnCraft; - - int craftingSize; - - ItemPane* pane; - IntRectangle paneRect; - //int paneX; - //int paneW; - - int numCategories; - std::vector categoryBitmasks; - std::vector categoryIcons; - ImageButton* selectedCategoryButton; - - // GUI elements such as 9-Patches - NinePatchLayer* guiBackground; - NinePatchLayer* guiSlotCategory; - NinePatchLayer* guiSlotCategorySelected; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_PaneCraftingScreen_H__*/ +#pragma once + +#include "../../Screen.h" +#include "../../../../world/item/crafting/Recipes.h" +#include "../../../../world/item/ItemInstance.h" + +#include "../../components/ScrollingPane.h" +#include "../../components/ImageButton.h" +#include "../../components/ItemPane.h" + +class Font; +class CItem; +class Textures; +class NinePatchLayer; + +class CraftButton: public ImageButton +{ + typedef ImageButton super; +public: + CraftButton(int id); + ~CraftButton(); + + void init(Textures*); + void setSize(float w, float h); + + void setNumItems(int i) { numItems = i; } + IntRectangle getItemPos(int i); + void renderBg(Minecraft* minecraft, int xm, int ym); +private: + NinePatchLayer* bg; + NinePatchLayer* bgSelected; + int numItems; +}; + +class PaneCraftingScreen: public Screen, + public IItemPaneCallback +{ + typedef Screen super; + typedef std::vector ItemList; +public: + PaneCraftingScreen(int craftingSize); + ~PaneCraftingScreen(); + + void init(); + void setupPositions(); + + void tick(); + void render(int xm, int ym, float a); + bool renderGameBehind(); + bool closeOnPlayerHurt(); + void buttonClicked(Button* button); + void keyPressed( int eventKey ); + + // IItemPaneCallback + void onItemSelected(const ItemPane* forPane, int itemIndexInCurrentCategory); + const std::vector& getItems(const ItemPane* forPane); +protected: + void setSingleCategoryAndIcon(int categoryBitmask, int categoryIcon); +private: + /// Filter out non craftable recipes. + /// The default implementation calls bool filterRecipe(r) for every + /// Recipe r and keeps the ones that returned true. + /// A crafting size filter has already been applied. + virtual void filterRecipes(RecipeList& recipes); + virtual bool filterRecipe(const Recipe& recipe) = 0; + + void initCategories(); + + void addItem(Recipe* recipe); + void recheckRecipes(); + void onItemSelected(int buttonIndex, CItem* item); + void clearCategoryItems(); + + void craftSelectedItem(); + std::vector _categoryButtons; + + ItemList _items; + std::vector _categories; + + int currentCategory; + CItem* currentItem; + std::string currentItemDesc; + std::vector currentCategoryButtons; + ImageButton btnClose; + CraftButton btnCraft; + + int craftingSize; + + ItemPane* pane; + IntRectangle paneRect; + //int paneX; + //int paneW; + + int numCategories; + std::vector categoryBitmasks; + std::vector categoryIcons; + ImageButton* selectedCategoryButton; + + // GUI elements such as 9-Patches + NinePatchLayer* guiBackground; + NinePatchLayer* guiSlotCategory; + NinePatchLayer* guiSlotCategorySelected; +}; + diff --git a/src/client/gui/screens/crafting/StonecutterScreen.h b/src/client/gui/screens/crafting/StonecutterScreen.h index 4baf0df..978a2c6 100755 --- a/src/client/gui/screens/crafting/StonecutterScreen.h +++ b/src/client/gui/screens/crafting/StonecutterScreen.h @@ -1,17 +1,15 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_StonecutterScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_StonecutterScreen_H__ - -#include "PaneCraftingScreen.h" - -class StonecutterScreen: public PaneCraftingScreen -{ - typedef PaneCraftingScreen super; -public: - StonecutterScreen(); - ~StonecutterScreen(); - -private: - bool filterRecipe(const Recipe& r); -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_StonecutterScreen_H__*/ +#pragma once + +#include "PaneCraftingScreen.h" + +class StonecutterScreen: public PaneCraftingScreen +{ + typedef PaneCraftingScreen super; +public: + StonecutterScreen(); + ~StonecutterScreen(); + +private: + bool filterRecipe(const Recipe& r); +}; + diff --git a/src/client/gui/screens/crafting/WorkbenchScreen.h b/src/client/gui/screens/crafting/WorkbenchScreen.h index e4e5c24..260f960 100755 --- a/src/client/gui/screens/crafting/WorkbenchScreen.h +++ b/src/client/gui/screens/crafting/WorkbenchScreen.h @@ -1,17 +1,15 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_WorkbenchScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_WorkbenchScreen_H__ - -#include "PaneCraftingScreen.h" - -class WorkbenchScreen: public PaneCraftingScreen -{ - typedef PaneCraftingScreen super; -public: - WorkbenchScreen(int craftingSize); - ~WorkbenchScreen(); - -private: - bool filterRecipe(const Recipe& r); -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS_CRAFT_WorkbenchScreen_H__*/ +#pragma once + +#include "PaneCraftingScreen.h" + +class WorkbenchScreen: public PaneCraftingScreen +{ + typedef PaneCraftingScreen super; +public: + WorkbenchScreen(int craftingSize); + ~WorkbenchScreen(); + +private: + bool filterRecipe(const Recipe& r); +}; + diff --git a/src/client/gui/screens/touch/TouchIngameBlockSelectionScreen.h b/src/client/gui/screens/touch/TouchIngameBlockSelectionScreen.h index ee8cbb1..542ec93 100755 --- a/src/client/gui/screens/touch/TouchIngameBlockSelectionScreen.h +++ b/src/client/gui/screens/touch/TouchIngameBlockSelectionScreen.h @@ -1,73 +1,71 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchIngameBlockSelectionScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchIngameBlockSelectionScreen_H__ - -#include "../../Screen.h" -#include "../../components/InventoryPane.h" -#include "../../components/Button.h" -#include "../../components/ScrollingPane.h" -#include "../../components/ItemPane.h" -#include "../../TweenData.h" -#include "../../../player/input/touchscreen/TouchAreaModel.h" -#include "../../../../AppPlatform.h" - -namespace Touch { - -class IngameBlockSelectionScreen : public Screen, - public IInventoryPaneCallback -{ - typedef Screen super; - -public: - IngameBlockSelectionScreen(); - virtual ~IngameBlockSelectionScreen(); - - virtual void init() override; - virtual void setupPositions() override; - virtual void removed() override; - - void tick() override; - void render(int xm, int ym, float a) override; - - bool hasClippingArea(IntRectangle& out) override; - - // IInventoryPaneCallback - bool addItem(const InventoryPane* pane, int itemId) override; - bool isAllowed(int slot) override; - std::vector getItems(const InventoryPane* forPane) override; - - void buttonClicked(Button* button) override; -protected: - virtual void mouseClicked(int x, int y, int buttonNum) override; - virtual void mouseReleased(int x, int y, int buttonNum) override; - - // also support wheel scrolling - virtual void mouseWheel(int dx, int dy, int xm, int ym) override; -private: - void renderDemoOverlay(); - - //int getLinearSlotId(int x, int y); - int getSlotPosX(int slotX); - int getSlotPosY(int slotY); - int getSlotHeight(); - -private: - int selectedItem; - bool _pendingClose; - InventoryPane* _blockList; - - THeader bHeader; - ImageButton bDone; - TButton bCraft; - TButton bArmor; - TButton bMenu; - - IntRectangle clippingArea; - - int InventoryRows; - int InventorySize; - int InventoryColumns; -}; - -} - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchIngameBlockSelectionScreen_H__*/ +#pragma once + +#include "../../Screen.h" +#include "../../components/InventoryPane.h" +#include "../../components/Button.h" +#include "../../components/ScrollingPane.h" +#include "../../components/ItemPane.h" +#include "../../TweenData.h" +#include "../../../player/input/touchscreen/TouchAreaModel.h" +#include "../../../../AppPlatform.h" + +namespace Touch { + +class IngameBlockSelectionScreen : public Screen, + public IInventoryPaneCallback +{ + typedef Screen super; + +public: + IngameBlockSelectionScreen(); + virtual ~IngameBlockSelectionScreen(); + + virtual void init() override; + virtual void setupPositions() override; + virtual void removed() override; + + void tick() override; + void render(int xm, int ym, float a) override; + + bool hasClippingArea(IntRectangle& out) override; + + // IInventoryPaneCallback + bool addItem(const InventoryPane* pane, int itemId) override; + bool isAllowed(int slot) override; + std::vector getItems(const InventoryPane* forPane) override; + + void buttonClicked(Button* button) override; +protected: + virtual void mouseClicked(int x, int y, int buttonNum) override; + virtual void mouseReleased(int x, int y, int buttonNum) override; + + // also support wheel scrolling + virtual void mouseWheel(int dx, int dy, int xm, int ym) override; +private: + void renderDemoOverlay(); + + //int getLinearSlotId(int x, int y); + int getSlotPosX(int slotX); + int getSlotPosY(int slotY); + int getSlotHeight(); + +private: + int selectedItem; + bool _pendingClose; + InventoryPane* _blockList; + + THeader bHeader; + ImageButton bDone; + TButton bCraft; + TButton bArmor; + TButton bMenu; + + IntRectangle clippingArea; + + int InventoryRows; + int InventorySize; + int InventoryColumns; +}; + +} + diff --git a/src/client/gui/screens/touch/TouchJoinGameScreen.h b/src/client/gui/screens/touch/TouchJoinGameScreen.h index 2205bf6..6e45a2c 100755 --- a/src/client/gui/screens/touch/TouchJoinGameScreen.h +++ b/src/client/gui/screens/touch/TouchJoinGameScreen.h @@ -1,74 +1,72 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchJoinGameScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchJoinGameScreen_H__ - -#include "../../Screen.h" -#include "../../components/Button.h" -#include "../../components/RolledSelectionListV.h" -#include "../../../Minecraft.h" -#include "../../../../platform/input/Multitouch.h" -#include "../../../../network/RakNetInstance.h" - -namespace Touch { - -class JoinGameScreen; - -class AvailableGamesList : public RolledSelectionListV -{ - int startSelected; - int selectedItem; - ServerList copiedServerList; - - friend class JoinGameScreen; - -public: - AvailableGamesList(Minecraft* _minecraft, int _width, int _height) - : RolledSelectionListV(_minecraft, _width, _height, 0, _width, 24, _height, 34), - selectedItem(-1), - startSelected(-1) - { - } - -protected: - - virtual int getNumberOfItems() { return (int)copiedServerList.size(); } - - virtual void selectCancel(); - virtual void selectStart(int item); - virtual void selectItem(int item, bool doubleClick); - - virtual bool isSelectedItem(int item) { return item == selectedItem; } - - virtual void renderBackground() {} - virtual void renderItem(int i, int x, int y, int h, Tesselator& t); -}; - -class JoinGameScreen: public Screen -{ -public: - JoinGameScreen(); - virtual ~JoinGameScreen(); - - void init(); - void setupPositions(); - - virtual bool handleBackEvent(bool isDown); - - virtual bool isIndexValid(int index); - - virtual void tick(); - void render(int xm, int ym, float a); - - void buttonClicked(Button* button); - - bool isInGameScreen(); -private: - Button bJoin; - TButton bBack; - TButton bJoinByIp; - THeader bHeader; - AvailableGamesList* gamesList; -}; - -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchJoinGameScreen_H__*/ +#pragma once + +#include "../../Screen.h" +#include "../../components/Button.h" +#include "../../components/RolledSelectionListV.h" +#include "../../../Minecraft.h" +#include "../../../../platform/input/Multitouch.h" +#include "../../../../network/RakNetInstance.h" + +namespace Touch { + +class JoinGameScreen; + +class AvailableGamesList : public RolledSelectionListV +{ + int startSelected; + int selectedItem; + ServerList copiedServerList; + + friend class JoinGameScreen; + +public: + AvailableGamesList(Minecraft* _minecraft, int _width, int _height) + : RolledSelectionListV(_minecraft, _width, _height, 0, _width, 24, _height, 34), + selectedItem(-1), + startSelected(-1) + { + } + +protected: + + virtual int getNumberOfItems() { return (int)copiedServerList.size(); } + + virtual void selectCancel(); + virtual void selectStart(int item); + virtual void selectItem(int item, bool doubleClick); + + virtual bool isSelectedItem(int item) { return item == selectedItem; } + + virtual void renderBackground() {} + virtual void renderItem(int i, int x, int y, int h, Tesselator& t); +}; + +class JoinGameScreen: public Screen +{ +public: + JoinGameScreen(); + virtual ~JoinGameScreen(); + + void init(); + void setupPositions(); + + virtual bool handleBackEvent(bool isDown); + + virtual bool isIndexValid(int index); + + virtual void tick(); + void render(int xm, int ym, float a); + + void buttonClicked(Button* button); + + bool isInGameScreen(); +private: + Button bJoin; + TButton bBack; + TButton bJoinByIp; + THeader bHeader; + AvailableGamesList* gamesList; +}; + +}; + diff --git a/src/client/gui/screens/touch/TouchSelectWorldScreen.h b/src/client/gui/screens/touch/TouchSelectWorldScreen.h index 525116b..6d922d8 100755 --- a/src/client/gui/screens/touch/TouchSelectWorldScreen.h +++ b/src/client/gui/screens/touch/TouchSelectWorldScreen.h @@ -1,122 +1,120 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchSelectWorldScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchSelectWorldScreen_H__ - -#include "../ConfirmScreen.h" -#include "../../Screen.h" -#include "../../TweenData.h" -#include "../../components/ImageButton.h" -#include "../../components/Button.h" -#include "../../components/RolledSelectionListH.h" -#include "../../../Minecraft.h" -#include "../../../../world/level/storage/LevelStorageSource.h" - - -namespace Touch { - -class SelectWorldScreen; - -// -// Scrolling World selection list -// -class TouchWorldSelectionList : public RolledSelectionListH -{ -public: - TouchWorldSelectionList(Minecraft* _minecraft, int _width, int _height); - virtual void tick(); - void stepLeft(); - void stepRight(); - - void commit(); -protected: - virtual int getNumberOfItems(); - virtual void selectItem(int item, bool doubleClick); - virtual bool isSelectedItem(int item); - - virtual void renderBackground() {} - virtual void renderItem(int i, int x, int y, int h, Tesselator& t); - virtual float getPos(float alpha); - virtual void touched() { mode = 0; } - virtual bool capXPosition(); - - virtual void selectStart(int item, int localX, int localY); - virtual void selectCancel(); -private: - TweenData td; - void tweenInited(); - - int selectedItem; - bool _newWorldSelected; // Is the PLUS button pressed? - int _height; - LevelSummaryList levels; - std::vector _descriptions; - StringVector _imageNames; - - bool hasPickedLevel; - LevelSummary pickedLevel; - int pickedIndex; - - int stoppedTick; - int currentTick; - float accRatio; - int mode; - - friend class SelectWorldScreen; -}; - -// -// Delete World screen -// -class TouchDeleteWorldScreen: public ConfirmScreen -{ -public: - TouchDeleteWorldScreen(const LevelSummary& levelId); -protected: - virtual void postResult(bool isOk); -private: - LevelSummary _level; -}; - - -// -// Select world screen -// -class SelectWorldScreen: public Screen -{ -public: - SelectWorldScreen(); - virtual ~SelectWorldScreen(); - - virtual void init() override; - virtual void setupPositions() override; - - virtual void tick() override; - virtual void render(int xm, int ym, float a) override; - - virtual bool isIndexValid(int index); - virtual bool handleBackEvent(bool isDown) override; - virtual void buttonClicked(Button* button) override; - virtual void keyPressed(int eventKey) override; - - // support for mouse wheel when desktop code uses touch variant - virtual void mouseWheel(int dx, int dy, int xm, int ym) override; - - bool isInGameScreen() override; -private: - void loadLevelSource(); - std::string getUniqueLevelName(const std::string& level); - - ImageButton bDelete; - TButton bCreate; - THeader bHeader; - TButton bBack; - Button bWorldView; - TouchWorldSelectionList* worldsList; - LevelSummaryList levels; - - bool _mouseHasBeenUp; - bool _hasStartedLevel; - //LevelStorageSource* levels; -}; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchSelectWorldScreen_H__*/ +#pragma once + +#include "../ConfirmScreen.h" +#include "../../Screen.h" +#include "../../TweenData.h" +#include "../../components/ImageButton.h" +#include "../../components/Button.h" +#include "../../components/RolledSelectionListH.h" +#include "../../../Minecraft.h" +#include "../../../../world/level/storage/LevelStorageSource.h" + + +namespace Touch { + +class SelectWorldScreen; + +// +// Scrolling World selection list +// +class TouchWorldSelectionList : public RolledSelectionListH +{ +public: + TouchWorldSelectionList(Minecraft* _minecraft, int _width, int _height); + virtual void tick(); + void stepLeft(); + void stepRight(); + + void commit(); +protected: + virtual int getNumberOfItems(); + virtual void selectItem(int item, bool doubleClick); + virtual bool isSelectedItem(int item); + + virtual void renderBackground() {} + virtual void renderItem(int i, int x, int y, int h, Tesselator& t); + virtual float getPos(float alpha); + virtual void touched() { mode = 0; } + virtual bool capXPosition(); + + virtual void selectStart(int item, int localX, int localY); + virtual void selectCancel(); +private: + TweenData td; + void tweenInited(); + + int selectedItem; + bool _newWorldSelected; // Is the PLUS button pressed? + int _height; + LevelSummaryList levels; + std::vector _descriptions; + StringVector _imageNames; + + bool hasPickedLevel; + LevelSummary pickedLevel; + int pickedIndex; + + int stoppedTick; + int currentTick; + float accRatio; + int mode; + + friend class SelectWorldScreen; +}; + +// +// Delete World screen +// +class TouchDeleteWorldScreen: public ConfirmScreen +{ +public: + TouchDeleteWorldScreen(const LevelSummary& levelId); +protected: + virtual void postResult(bool isOk); +private: + LevelSummary _level; +}; + + +// +// Select world screen +// +class SelectWorldScreen: public Screen +{ +public: + SelectWorldScreen(); + virtual ~SelectWorldScreen(); + + virtual void init() override; + virtual void setupPositions() override; + + virtual void tick() override; + virtual void render(int xm, int ym, float a) override; + + virtual bool isIndexValid(int index); + virtual bool handleBackEvent(bool isDown) override; + virtual void buttonClicked(Button* button) override; + virtual void keyPressed(int eventKey) override; + + // support for mouse wheel when desktop code uses touch variant + virtual void mouseWheel(int dx, int dy, int xm, int ym) override; + + bool isInGameScreen() override; +private: + void loadLevelSource(); + std::string getUniqueLevelName(const std::string& level); + + ImageButton bDelete; + TButton bCreate; + THeader bHeader; + TButton bBack; + Button bWorldView; + TouchWorldSelectionList* worldsList; + LevelSummaryList levels; + + bool _mouseHasBeenUp; + bool _hasStartedLevel; + //LevelStorageSource* levels; +}; +}; + diff --git a/src/client/gui/screens/touch/TouchStartMenuScreen.h b/src/client/gui/screens/touch/TouchStartMenuScreen.h index b4c8755..954e06e 100755 --- a/src/client/gui/screens/touch/TouchStartMenuScreen.h +++ b/src/client/gui/screens/touch/TouchStartMenuScreen.h @@ -1,43 +1,41 @@ -#ifndef NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchStartMenuScreen_H__ -#define NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchStartMenuScreen_H__ - -#include "../../Screen.h" -#include "../../components/LargeImageButton.h" -#include "../../components/ImageButton.h" -#include "../../components/TextBox.h" - -namespace Touch { - -class StartMenuScreen: public Screen -{ -public: - StartMenuScreen(); - virtual ~StartMenuScreen(); - - void init(); - void setupPositions(); - - void render(int xm, int ym, float a); - - void buttonClicked(Button* button); - virtual void mouseClicked(int x, int y, int buttonNum); - bool handleBackEvent(bool isDown); - bool isInGameScreen(); -private: - - LargeImageButton bHost; - LargeImageButton bJoin; - LargeImageButton bOptions; - ImageButton bQuit; // X close icon - - std::string copyright; - int copyrightPosX; - - std::string version; - int versionPosX; - - std::string username; -}; -}; - -#endif /*NET_MINECRAFT_CLIENT_GUI_SCREENS_TOUCH__TouchStartMenuScreen_H__*/ +#pragma once + +#include "../../Screen.h" +#include "../../components/LargeImageButton.h" +#include "../../components/ImageButton.h" +#include "../../components/TextBox.h" + +namespace Touch { + +class StartMenuScreen: public Screen +{ +public: + StartMenuScreen(); + virtual ~StartMenuScreen(); + + void init(); + void setupPositions(); + + void render(int xm, int ym, float a); + + void buttonClicked(Button* button); + virtual void mouseClicked(int x, int y, int buttonNum); + bool handleBackEvent(bool isDown); + bool isInGameScreen(); +private: + + LargeImageButton bHost; + LargeImageButton bJoin; + LargeImageButton bOptions; + ImageButton bQuit; // X close icon + + std::string copyright; + int copyrightPosX; + + std::string version; + int versionPosX; + + std::string username; +}; +}; + diff --git a/src/client/model/ChestModel.h b/src/client/model/ChestModel.h index 4a91504..2f48a94 100755 --- a/src/client/model/ChestModel.h +++ b/src/client/model/ChestModel.h @@ -1,52 +1,50 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__ChestModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__ChestModel_H__ - -//package net.minecraft.client.model; - -#include "Model.h" -#include "geom/ModelPart.h" - -class ChestModel: public Model -{ -public: - ChestModel() - : lid(0, 0), - lock(0, 0), - bottom(0, 0) - { - lid.setModel(this); - lid.setTexSize(64, 64); - lid.addBox(0.0f, -5, -14, 14, 5, 14, 0); - lid.x = 1; - lid.y = 7; - lid.z = 15; - - lock.setModel(this); - lock.setTexSize(64, 64); - lock.addBox(-1, -2, -15, 2, 4, 1, 0); - lock.x = 8; - lock.y = 7; - lock.z = 15; - - bottom.setModel(this); - bottom.setTexSize(64, 64); - bottom.addBox(0.0f, 0, 0, 14, 10, 14, 0); - bottom.x = 1; - bottom.y = 6; - bottom.z = 1; - } - - void render() { - lock.xRot = lid.xRot; - - lid.render(1 / 16.0f); - lock.render(1 / 16.0f); - bottom.render(1 / 16.0f); - } - - ModelPart lid; - ModelPart bottom; - ModelPart lock; -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__ChestModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "Model.h" +#include "geom/ModelPart.h" + +class ChestModel: public Model +{ +public: + ChestModel() + : lid(0, 0), + lock(0, 0), + bottom(0, 0) + { + lid.setModel(this); + lid.setTexSize(64, 64); + lid.addBox(0.0f, -5, -14, 14, 5, 14, 0); + lid.x = 1; + lid.y = 7; + lid.z = 15; + + lock.setModel(this); + lock.setTexSize(64, 64); + lock.addBox(-1, -2, -15, 2, 4, 1, 0); + lock.x = 8; + lock.y = 7; + lock.z = 15; + + bottom.setModel(this); + bottom.setTexSize(64, 64); + bottom.addBox(0.0f, 0, 0, 14, 10, 14, 0); + bottom.x = 1; + bottom.y = 6; + bottom.z = 1; + } + + void render() { + lock.xRot = lid.xRot; + + lid.render(1 / 16.0f); + lock.render(1 / 16.0f); + bottom.render(1 / 16.0f); + } + + ModelPart lid; + ModelPart bottom; + ModelPart lock; +}; + diff --git a/src/client/model/ChickenModel.h b/src/client/model/ChickenModel.h index 7e9ff7c..ca0438b 100755 --- a/src/client/model/ChickenModel.h +++ b/src/client/model/ChickenModel.h @@ -1,23 +1,21 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__ChickenModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__ChickenModel_H__ - -#include "Model.h" -#include "geom/ModelPart.h" - -class Entity; - -class ChickenModel: public Model -{ - typedef Model super; -public: - ModelPart head, hair, body, leg0, leg1, wing0, wing1, beak, redThing; - - ChickenModel(); - - /*@Override*/ - void render(Entity* entity, float time, float r, float bob, float yRot, float xRot, float scale); - - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__ChickenModel_H__*/ +#pragma once + +#include "Model.h" +#include "geom/ModelPart.h" + +class Entity; + +class ChickenModel: public Model +{ + typedef Model super; +public: + ModelPart head, hair, body, leg0, leg1, wing0, wing1, beak, redThing; + + ChickenModel(); + + /*@Override*/ + void render(Entity* entity, float time, float r, float bob, float yRot, float xRot, float scale); + + void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); +}; + diff --git a/src/client/model/CowModel.h b/src/client/model/CowModel.h index 3840639..b3b260a 100755 --- a/src/client/model/CowModel.h +++ b/src/client/model/CowModel.h @@ -1,15 +1,13 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__CowModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__CowModel_H__ - -//package net.minecraft.client.model; - -#include "QuadrupedModel.h" - -class CowModel: public QuadrupedModel -{ - typedef QuadrupedModel super; -public: - CowModel(); -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__CowModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "QuadrupedModel.h" + +class CowModel: public QuadrupedModel +{ + typedef QuadrupedModel super; +public: + CowModel(); +}; + diff --git a/src/client/model/CreeperModel.h b/src/client/model/CreeperModel.h index 2909afe..35c3392 100755 --- a/src/client/model/CreeperModel.h +++ b/src/client/model/CreeperModel.h @@ -1,82 +1,80 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__CreeperModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__CreeperModel_H__ - -//package net.minecraft.client.model; - -#include "Model.h" - -#include "geom/ModelPart.h" -#include "../../world/entity/Entity.h" - -class CreeperModel: public Model -{ - typedef Model super; -public: - ModelPart head, /*hair,*/ body, leg0, leg1, leg2, leg3; - - CreeperModel(float g = 0) - : head(0, 0), - //hair(32, 0), - body(16, 16), - leg0(0, 16), - leg1(0, 16), - leg2(0, 16), - leg3(0, 16) - { - float yo = 4; - - head.setModel(this); - //hair.setModel(this); - body.setModel(this); - leg0.setModel(this); - leg1.setModel(this); - leg2.setModel(this); - leg3.setModel(this); - - head.addBox(-4, -8, -4, 8, 8, 8, g); // Head - head.setPos(0, yo, 0); - -// hair.addBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head -// hair.setPos(0, yo, 0); - - body.addBox(-4, 0, -2, 8, 12, 4, g); // Body - body.setPos(0, yo, 0); - - leg0.addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 - leg0.setPos(-2, 12 + yo, 4); - - leg1.addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 - leg1.setPos(2, 12 + yo, 4); - - leg2.addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 - leg2.setPos(-2, 12 + yo, -4); - - leg3.addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 - leg3.setPos(2, 12 + yo, -4); - } - - /*@Override*/ - void render(Entity* entity, float time, float r, float bob, float yRot, float xRot, float scale) { - setupAnim(time, r, bob, yRot, xRot, scale); - - head.render(scale); - body.render(scale); - leg0.render(scale); - leg1.render(scale); - leg2.render(scale); - leg3.render(scale); - } - - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) { - head.yRot = yRot / (float) (180 / Mth::PI); - head.xRot = xRot / (float) (180 / Mth::PI); - - const float pend = (Mth::cos(time * 0.6662f) * 1.4f) * r; - leg0.xRot = pend; - leg1.xRot = -pend; - leg2.xRot = -pend; - leg3.xRot = pend; - } -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__CreeperModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "Model.h" + +#include "geom/ModelPart.h" +#include "../../world/entity/Entity.h" + +class CreeperModel: public Model +{ + typedef Model super; +public: + ModelPart head, /*hair,*/ body, leg0, leg1, leg2, leg3; + + CreeperModel(float g = 0) + : head(0, 0), + //hair(32, 0), + body(16, 16), + leg0(0, 16), + leg1(0, 16), + leg2(0, 16), + leg3(0, 16) + { + float yo = 4; + + head.setModel(this); + //hair.setModel(this); + body.setModel(this); + leg0.setModel(this); + leg1.setModel(this); + leg2.setModel(this); + leg3.setModel(this); + + head.addBox(-4, -8, -4, 8, 8, 8, g); // Head + head.setPos(0, yo, 0); + +// hair.addBox(-4, -8, -4, 8, 8, 8, g + 0.5f); // Head +// hair.setPos(0, yo, 0); + + body.addBox(-4, 0, -2, 8, 12, 4, g); // Body + body.setPos(0, yo, 0); + + leg0.addBox(-2, 0, -2, 4, 6, 4, g); // Leg0 + leg0.setPos(-2, 12 + yo, 4); + + leg1.addBox(-2, 0, -2, 4, 6, 4, g); // Leg1 + leg1.setPos(2, 12 + yo, 4); + + leg2.addBox(-2, 0, -2, 4, 6, 4, g); // Leg2 + leg2.setPos(-2, 12 + yo, -4); + + leg3.addBox(-2, 0, -2, 4, 6, 4, g); // Leg3 + leg3.setPos(2, 12 + yo, -4); + } + + /*@Override*/ + void render(Entity* entity, float time, float r, float bob, float yRot, float xRot, float scale) { + setupAnim(time, r, bob, yRot, xRot, scale); + + head.render(scale); + body.render(scale); + leg0.render(scale); + leg1.render(scale); + leg2.render(scale); + leg3.render(scale); + } + + void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) { + head.yRot = yRot / (float) (180 / Mth::PI); + head.xRot = xRot / (float) (180 / Mth::PI); + + const float pend = (Mth::cos(time * 0.6662f) * 1.4f) * r; + leg0.xRot = pend; + leg1.xRot = -pend; + leg2.xRot = -pend; + leg3.xRot = pend; + } +}; + diff --git a/src/client/model/HumanoidModel.h b/src/client/model/HumanoidModel.h index d97a7be..f70a41c 100755 --- a/src/client/model/HumanoidModel.h +++ b/src/client/model/HumanoidModel.h @@ -1,28 +1,26 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__HumanoidModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__HumanoidModel_H__ - -//package net.minecraft.client.model; - -#include "Model.h" -#include "geom/ModelPart.h" -class ItemInstance; -class HumanoidModel: public Model -{ -public: -HumanoidModel(float g = 0, float yOffset = 0, int texW = 64, int texH = 32); - - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); - - void render(HumanoidModel* model, float scale); - void render(Entity* e, float time, float r, float bob, float yRot, float xRot, float scale); - void renderHorrible(float time, float r, float bob, float yRot, float xRot, float scale); - void onGraphicsReset(); - - ModelPart head, hair, body, arm0, arm1, leg0, leg1;//, ear; - bool holdingLeftHand; - bool holdingRightHand; - bool sneaking; - bool bowAndArrow; -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__HumanoidModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "Model.h" +#include "geom/ModelPart.h" +class ItemInstance; +class HumanoidModel: public Model +{ +public: +HumanoidModel(float g = 0, float yOffset = 0, int texW = 64, int texH = 32); + + void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); + + void render(HumanoidModel* model, float scale); + void render(Entity* e, float time, float r, float bob, float yRot, float xRot, float scale); + void renderHorrible(float time, float r, float bob, float yRot, float xRot, float scale); + void onGraphicsReset(); + + ModelPart head, hair, body, arm0, arm1, leg0, leg1;//, ear; + bool holdingLeftHand; + bool holdingRightHand; + bool sneaking; + bool bowAndArrow; +}; + diff --git a/src/client/model/Model.h b/src/client/model/Model.h index 176ca5e..e8e0455 100755 --- a/src/client/model/Model.h +++ b/src/client/model/Model.h @@ -1,48 +1,46 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__Model_H__ -#define NET_MINECRAFT_CLIENT_MODEL__Model_H__ - -//package net.minecraft.client.model; - -#include -#include "geom/ModelPart.h" - -class Mob; -class Entity; - -class Model -{ -protected: - Model() - : riding(false), - attackTime(0), - texWidth(64), - texHeight(32), - young(true) - {} - -public: - virtual ~Model() {} - - virtual void onGraphicsReset() { - for (unsigned int i = 0; i < cubes.size(); ++i) - cubes[i]->onGraphicsReset(); - } - - virtual void render(Entity* e, float time, float r, float bob, float yRot, float xRot, float scale) {} - virtual void renderHorrible(float time, float r, float bob, float yRot, float xRot, float scale) {} - virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) {} - virtual void prepareMobModel(Mob* mob, float time, float r, float a) {} - - float attackTime; - bool riding; - - int texWidth; - int texHeight; - - std::vector cubes; - bool young; -private: - //Map mappedTexOffs = new HashMap(); -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__Model_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include +#include "geom/ModelPart.h" + +class Mob; +class Entity; + +class Model +{ +protected: + Model() + : riding(false), + attackTime(0), + texWidth(64), + texHeight(32), + young(true) + {} + +public: + virtual ~Model() {} + + virtual void onGraphicsReset() { + for (unsigned int i = 0; i < cubes.size(); ++i) + cubes[i]->onGraphicsReset(); + } + + virtual void render(Entity* e, float time, float r, float bob, float yRot, float xRot, float scale) {} + virtual void renderHorrible(float time, float r, float bob, float yRot, float xRot, float scale) {} + virtual void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) {} + virtual void prepareMobModel(Mob* mob, float time, float r, float a) {} + + float attackTime; + bool riding; + + int texWidth; + int texHeight; + + std::vector cubes; + bool young; +private: + //Map mappedTexOffs = new HashMap(); +}; + diff --git a/src/client/model/ModelInclude.h b/src/client/model/ModelInclude.h index 0fb4a51..1f3a157 100755 --- a/src/client/model/ModelInclude.h +++ b/src/client/model/ModelInclude.h @@ -1,17 +1,15 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__ModelInclude_H__ -#define NET_MINECRAFT_CLIENT_MODEL__ModelInclude_H__ - -#include "HumanoidModel.h" - -#include "ChickenModel.h" -#include "CowModel.h" -#include "PigModel.h" -#include "SheepModel.h" -#include "SheepFurModel.h" - -#include "ZombieModel.h" -#include "SkeletonModel.h" - -#include "SignModel.h" - -#endif /*NET_MINECRAFT_CLIENT_MODEL__ModelInclude_H__*/ +#pragma once + +#include "HumanoidModel.h" + +#include "ChickenModel.h" +#include "CowModel.h" +#include "PigModel.h" +#include "SheepModel.h" +#include "SheepFurModel.h" + +#include "ZombieModel.h" +#include "SkeletonModel.h" + +#include "SignModel.h" + diff --git a/src/client/model/PigModel.h b/src/client/model/PigModel.h index c4bcc69..1afbe63 100755 --- a/src/client/model/PigModel.h +++ b/src/client/model/PigModel.h @@ -1,15 +1,13 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__PigModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__PigModel_H__ - -//package net.minecraft.client.model; - -#include "QuadrupedModel.h" - -class PigModel: public QuadrupedModel -{ - typedef QuadrupedModel super; -public: - PigModel(float g = 0); -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__PigModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "QuadrupedModel.h" + +class PigModel: public QuadrupedModel +{ + typedef QuadrupedModel super; +public: + PigModel(float g = 0); +}; + diff --git a/src/client/model/QuadrupedModel.h b/src/client/model/QuadrupedModel.h index 0cce639..0a32405 100755 --- a/src/client/model/QuadrupedModel.h +++ b/src/client/model/QuadrupedModel.h @@ -1,28 +1,26 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__QuadrupedModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__QuadrupedModel_H__ - -//package net.minecraft.client.model; - -#include "Model.h" -#include "geom/ModelPart.h" - -class Entity; - -class QuadrupedModel: public Model -{ -public: - QuadrupedModel(int legSize, float g); - - //@Override - void render(QuadrupedModel* model, float scale); - void render(Entity* entity, float time, float r, float bob, float yRot, float xRot, float scale); - - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); - - ModelPart head, hair, body, leg0, leg1, leg2, leg3; -protected: - float yHeadOffs; - float zHeadOffs; -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__QuadrupedModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "Model.h" +#include "geom/ModelPart.h" + +class Entity; + +class QuadrupedModel: public Model +{ +public: + QuadrupedModel(int legSize, float g); + + //@Override + void render(QuadrupedModel* model, float scale); + void render(Entity* entity, float time, float r, float bob, float yRot, float xRot, float scale); + + void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); + + ModelPart head, hair, body, leg0, leg1, leg2, leg3; +protected: + float yHeadOffs; + float zHeadOffs; +}; + diff --git a/src/client/model/SheepFurModel.h b/src/client/model/SheepFurModel.h index afc0b0f..960e7d9 100755 --- a/src/client/model/SheepFurModel.h +++ b/src/client/model/SheepFurModel.h @@ -1,24 +1,22 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__SheepFurModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__SheepFurModel_H__ - -//package net.minecraft.client.model; - -#include "QuadrupedModel.h" - -class SheepFurModel: public QuadrupedModel -{ - typedef QuadrupedModel super; - -public: - SheepFurModel(); - - /*@Override*/ - void prepareMobModel(Mob* mob, float time, float r, float a); - - /*@Override*/ - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); -private: - float headXRot; -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__SheepFurModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "QuadrupedModel.h" + +class SheepFurModel: public QuadrupedModel +{ + typedef QuadrupedModel super; + +public: + SheepFurModel(); + + /*@Override*/ + void prepareMobModel(Mob* mob, float time, float r, float a); + + /*@Override*/ + void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); +private: + float headXRot; +}; + diff --git a/src/client/model/SheepModel.h b/src/client/model/SheepModel.h index 7b2bc63..1e510f7 100755 --- a/src/client/model/SheepModel.h +++ b/src/client/model/SheepModel.h @@ -1,23 +1,21 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__SheepModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__SheepModel_H__ - -//package net.minecraft.client.model; - -#include "QuadrupedModel.h" - -class SheepModel: public QuadrupedModel -{ - typedef QuadrupedModel super; -public: - SheepModel(); - - /*@Override*/ - void prepareMobModel(Mob* mob, float time, float r, float a); - - /*@Override*/ - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); -private: - float headXRot; -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__SheepModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "QuadrupedModel.h" + +class SheepModel: public QuadrupedModel +{ + typedef QuadrupedModel super; +public: + SheepModel(); + + /*@Override*/ + void prepareMobModel(Mob* mob, float time, float r, float a); + + /*@Override*/ + void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale); +private: + float headXRot; +}; + diff --git a/src/client/model/SignModel.h b/src/client/model/SignModel.h index b2985c1..916ae18 100755 --- a/src/client/model/SignModel.h +++ b/src/client/model/SignModel.h @@ -1,32 +1,30 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__SignModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__SignModel_H__ - -//package net.minecraft.client.model; - -#include "Model.h" -#include "geom/ModelPart.h" - -class SignModel: public Model -{ -public: - SignModel() - : cube(0, 0), - cube2(0, 14) - { - cube.addBox(-12, -14, -1, 24, 12, 2, 0); - cube2.addBox(-1, -2, -1, 2, 14, 2, 0); - - cube.setModel(this); - cube2.setModel(this); - } - - void render() { - cube.render(1 / 16.0f); - cube2.render(1 / 16.0f); - } - - ModelPart cube; - ModelPart cube2; -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__SignModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "Model.h" +#include "geom/ModelPart.h" + +class SignModel: public Model +{ +public: + SignModel() + : cube(0, 0), + cube2(0, 14) + { + cube.addBox(-12, -14, -1, 24, 12, 2, 0); + cube2.addBox(-1, -2, -1, 2, 14, 2, 0); + + cube.setModel(this); + cube2.setModel(this); + } + + void render() { + cube.render(1 / 16.0f); + cube2.render(1 / 16.0f); + } + + ModelPart cube; + ModelPart cube2; +}; + diff --git a/src/client/model/SkeletonModel.h b/src/client/model/SkeletonModel.h index 86162c9..3ff814b 100755 --- a/src/client/model/SkeletonModel.h +++ b/src/client/model/SkeletonModel.h @@ -1,46 +1,44 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__SkeletonModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__SkeletonModel_H__ - -//package net.minecraft.client.model; - -#include "ZombieModel.h" -#include "geom/ModelPart.h" - -class SkeletonModel: public ZombieModel -{ - typedef ZombieModel super; -public: - SkeletonModel() - { - float g = 0; - - arm0 = ModelPart(24 + 16, 16); - arm0.setModel(this); - arm0.addBox(-1, -2, -1, 2, 12, 2, g); // Arm0 - arm0.setPos(-5, 2, 0); - - arm1 = ModelPart(24 + 16, 16); - arm1.setModel(this); - arm1.mirror = true; - arm1.addBox(-1, -2, -1, 2, 12, 2, g); // Arm1 - arm1.setPos(5, 2, 0); - - leg0 = ModelPart(0, 16); - leg0.setModel(this); - leg0.addBox(-1, 0, -1, 2, 12, 2, g); // Leg0 - leg0.setPos(-2, 12, 0); - - leg1 = ModelPart(0, 16); - leg1.setModel(this); - leg1.mirror = true; - leg1.addBox(-1, 0, -1, 2, 12, 2, g); // Leg1 - leg1.setPos(2, 12, 0); - } - - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) { - bowAndArrow = true; - super::setupAnim(time, r, bob, yRot, xRot, scale); - } -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__SkeletonModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "ZombieModel.h" +#include "geom/ModelPart.h" + +class SkeletonModel: public ZombieModel +{ + typedef ZombieModel super; +public: + SkeletonModel() + { + float g = 0; + + arm0 = ModelPart(24 + 16, 16); + arm0.setModel(this); + arm0.addBox(-1, -2, -1, 2, 12, 2, g); // Arm0 + arm0.setPos(-5, 2, 0); + + arm1 = ModelPart(24 + 16, 16); + arm1.setModel(this); + arm1.mirror = true; + arm1.addBox(-1, -2, -1, 2, 12, 2, g); // Arm1 + arm1.setPos(5, 2, 0); + + leg0 = ModelPart(0, 16); + leg0.setModel(this); + leg0.addBox(-1, 0, -1, 2, 12, 2, g); // Leg0 + leg0.setPos(-2, 12, 0); + + leg1 = ModelPart(0, 16); + leg1.setModel(this); + leg1.mirror = true; + leg1.addBox(-1, 0, -1, 2, 12, 2, g); // Leg1 + leg1.setPos(2, 12, 0); + } + + void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) { + bowAndArrow = true; + super::setupAnim(time, r, bob, yRot, xRot, scale); + } +}; + diff --git a/src/client/model/SpiderModel.h b/src/client/model/SpiderModel.h index f02c0ce..3dfc72b 100755 --- a/src/client/model/SpiderModel.h +++ b/src/client/model/SpiderModel.h @@ -1,168 +1,166 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__SpiderModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__SpiderModel_H__ - -//package net.minecraft.client.model; - -#include "Model.h" - -#include "geom/ModelPart.h" -#include "../../world/entity/Entity.h" -#include "../../util/Mth.h" - -class SpiderModel: public Model -{ - typedef Model super; -public: - ModelPart head, body0, body1, leg0, leg1, leg2, leg3, leg4, leg5, leg6, leg7; - - SpiderModel() - : head(32, 4), - body0(0, 0), - body1(0, 12), - leg0(18, 0), - leg1(18, 0), - leg2(18, 0), - leg3(18, 0), - leg4(18, 0), - leg5(18, 0), - leg6(18, 0), - leg7(18, 0) - { - float g = 0; - - head.setModel(this); - body0.setModel(this); - body0.setModel(this); - leg0.setModel(this); - leg1.setModel(this); - leg2.setModel(this); - leg3.setModel(this); - leg4.setModel(this); - leg5.setModel(this); - leg6.setModel(this); - leg7.setModel(this); - - float yo = 18 + 6 - 9; - - head.addBox(-4, -4, -8, 8, 8, 8, g); // Head - head.setPos(0, 0 + yo, -3); - - body0.addBox(-3, -3, -3, 6, 6, 6, g); // Body - body0.setPos(0, yo, 0); - - body1.addBox(-5, -4, -6, 10, 8, 12, g); // Body - body1.setPos(0, 0 + yo, 3 + 6); - - leg0.addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 - leg0.setPos(-4, 0 + yo, 2); - - leg1.addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 - leg1.setPos(4, 0 + yo, 2); - - leg2.addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 - leg2.setPos(-4, 0 + yo, 1); - - leg3.addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 - leg3.setPos(4, 0 + yo, 1); - - leg4.addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 - leg4.setPos(-4, 0 + yo, 0); - - leg5.addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 - leg5.setPos(4, 0 + yo, 0); - - leg6.addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 - leg6.setPos(-4, 0 + yo, -1); - - leg7.addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 - leg7.setPos(4, 0 + yo, -1); - } - - /*@Override*/ - void render(Entity* entity, float time, float r, float bob, float yRot, float xRot, float scale) { - setupAnim(time, r, bob, yRot, xRot, scale); - - head.render(scale); - body0.render(scale); - body1.render(scale); - leg0.render(scale); - leg1.render(scale); - leg2.render(scale); - leg3.render(scale); - leg4.render(scale); - leg5.render(scale); - leg6.render(scale); - leg7.render(scale); - } - - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) { - head.yRot = yRot / (float) (180 / Mth::PI); - head.xRot = xRot / (float) (180 / Mth::PI); - - const float sr = (float) Mth::PI / 4.0f; - leg0.zRot = -sr; - leg1.zRot = sr; - - leg2.zRot = -sr * 0.74f; - leg3.zRot = sr * 0.74f; - - leg4.zRot = -sr * 0.74f; - leg5.zRot = sr * 0.74f; - - leg6.zRot = -sr; - leg7.zRot = sr; - - //float ro = -(float) Mth::PI / 2.0f * 0; - const float ur = (float) Mth::PI / 8.0f; - const float ur2 = sr; - - leg0.yRot = ur2; - leg1.yRot = -ur2; - leg2.yRot = ur; - leg3.yRot = -ur; - leg4.yRot = -ur; - leg5.yRot = +ur; - leg6.yRot = -ur2; - leg7.yRot = +ur2; - - //static Stopwatch w; - //w.start(); - - float c0 = -((float) Mth::cos(time * 0.6662f * 2 + Mth::PI * 2 * 0 / 4.0f) * 0.4f) * r; - float c1 = -((float) Mth::cos(time * 0.6662f * 2 + Mth::PI * 2 * 2 / 4.0f) * 0.4f) * r; - float c2 = -((float) Mth::cos(time * 0.6662f * 2 + Mth::PI * 2 * 1 / 4.0f) * 0.4f) * r; - float c3 = -((float) Mth::cos(time * 0.6662f * 2 + Mth::PI * 2 * 3 / 4.0f) * 0.4f) * r; - - //LOGI("spider: %f, %f, %f, %f\n", c0, c1, c2, c3); - - float s0 = std::abs((float) Mth::sin(time * 0.6662f + Mth::PI * 2 * 0 / 4.0f) * 0.4f) * r; - float s1 = std::abs((float) Mth::sin(time * 0.6662f + Mth::PI * 2 * 2 / 4.0f) * 0.4f) * r; - float s2 = std::abs((float) Mth::sin(time * 0.6662f + Mth::PI * 2 * 1 / 4.0f) * 0.4f) * r; - float s3 = std::abs((float) Mth::sin(time * 0.6662f + Mth::PI * 2 * 3 / 4.0f) * 0.4f) * r; - - //w.stop(); - //w.printEvery(100); - - //LOGI("spiddy: %f, %f, %f, %f\n", s0, s1, s2, s3); - - leg0.yRot += c0; - leg1.yRot -= c0; - leg2.yRot += c1; - leg3.yRot -= c1; - leg4.yRot += c2; - leg5.yRot -= c2; - leg6.yRot += c3; - leg7.yRot -= c3; - - leg0.zRot += s0; - leg1.zRot -= s0; - leg2.zRot += s1; - leg3.zRot -= s1; - leg4.zRot += s2; - leg5.zRot -= s2; - leg6.zRot += s3; - leg7.zRot -= s3; - } -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__SpiderModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "Model.h" + +#include "geom/ModelPart.h" +#include "../../world/entity/Entity.h" +#include "../../util/Mth.h" + +class SpiderModel: public Model +{ + typedef Model super; +public: + ModelPart head, body0, body1, leg0, leg1, leg2, leg3, leg4, leg5, leg6, leg7; + + SpiderModel() + : head(32, 4), + body0(0, 0), + body1(0, 12), + leg0(18, 0), + leg1(18, 0), + leg2(18, 0), + leg3(18, 0), + leg4(18, 0), + leg5(18, 0), + leg6(18, 0), + leg7(18, 0) + { + float g = 0; + + head.setModel(this); + body0.setModel(this); + body0.setModel(this); + leg0.setModel(this); + leg1.setModel(this); + leg2.setModel(this); + leg3.setModel(this); + leg4.setModel(this); + leg5.setModel(this); + leg6.setModel(this); + leg7.setModel(this); + + float yo = 18 + 6 - 9; + + head.addBox(-4, -4, -8, 8, 8, 8, g); // Head + head.setPos(0, 0 + yo, -3); + + body0.addBox(-3, -3, -3, 6, 6, 6, g); // Body + body0.setPos(0, yo, 0); + + body1.addBox(-5, -4, -6, 10, 8, 12, g); // Body + body1.setPos(0, 0 + yo, 3 + 6); + + leg0.addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 + leg0.setPos(-4, 0 + yo, 2); + + leg1.addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 + leg1.setPos(4, 0 + yo, 2); + + leg2.addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 + leg2.setPos(-4, 0 + yo, 1); + + leg3.addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 + leg3.setPos(4, 0 + yo, 1); + + leg4.addBox(-15, -1, -1, 16, 2, 2, g); // Leg0 + leg4.setPos(-4, 0 + yo, 0); + + leg5.addBox(-1, -1, -1, 16, 2, 2, g); // Leg1 + leg5.setPos(4, 0 + yo, 0); + + leg6.addBox(-15, -1, -1, 16, 2, 2, g); // Leg2 + leg6.setPos(-4, 0 + yo, -1); + + leg7.addBox(-1, -1, -1, 16, 2, 2, g); // Leg3 + leg7.setPos(4, 0 + yo, -1); + } + + /*@Override*/ + void render(Entity* entity, float time, float r, float bob, float yRot, float xRot, float scale) { + setupAnim(time, r, bob, yRot, xRot, scale); + + head.render(scale); + body0.render(scale); + body1.render(scale); + leg0.render(scale); + leg1.render(scale); + leg2.render(scale); + leg3.render(scale); + leg4.render(scale); + leg5.render(scale); + leg6.render(scale); + leg7.render(scale); + } + + void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) { + head.yRot = yRot / (float) (180 / Mth::PI); + head.xRot = xRot / (float) (180 / Mth::PI); + + const float sr = (float) Mth::PI / 4.0f; + leg0.zRot = -sr; + leg1.zRot = sr; + + leg2.zRot = -sr * 0.74f; + leg3.zRot = sr * 0.74f; + + leg4.zRot = -sr * 0.74f; + leg5.zRot = sr * 0.74f; + + leg6.zRot = -sr; + leg7.zRot = sr; + + //float ro = -(float) Mth::PI / 2.0f * 0; + const float ur = (float) Mth::PI / 8.0f; + const float ur2 = sr; + + leg0.yRot = ur2; + leg1.yRot = -ur2; + leg2.yRot = ur; + leg3.yRot = -ur; + leg4.yRot = -ur; + leg5.yRot = +ur; + leg6.yRot = -ur2; + leg7.yRot = +ur2; + + //static Stopwatch w; + //w.start(); + + float c0 = -((float) Mth::cos(time * 0.6662f * 2 + Mth::PI * 2 * 0 / 4.0f) * 0.4f) * r; + float c1 = -((float) Mth::cos(time * 0.6662f * 2 + Mth::PI * 2 * 2 / 4.0f) * 0.4f) * r; + float c2 = -((float) Mth::cos(time * 0.6662f * 2 + Mth::PI * 2 * 1 / 4.0f) * 0.4f) * r; + float c3 = -((float) Mth::cos(time * 0.6662f * 2 + Mth::PI * 2 * 3 / 4.0f) * 0.4f) * r; + + //LOGI("spider: %f, %f, %f, %f\n", c0, c1, c2, c3); + + float s0 = std::abs((float) Mth::sin(time * 0.6662f + Mth::PI * 2 * 0 / 4.0f) * 0.4f) * r; + float s1 = std::abs((float) Mth::sin(time * 0.6662f + Mth::PI * 2 * 2 / 4.0f) * 0.4f) * r; + float s2 = std::abs((float) Mth::sin(time * 0.6662f + Mth::PI * 2 * 1 / 4.0f) * 0.4f) * r; + float s3 = std::abs((float) Mth::sin(time * 0.6662f + Mth::PI * 2 * 3 / 4.0f) * 0.4f) * r; + + //w.stop(); + //w.printEvery(100); + + //LOGI("spiddy: %f, %f, %f, %f\n", s0, s1, s2, s3); + + leg0.yRot += c0; + leg1.yRot -= c0; + leg2.yRot += c1; + leg3.yRot -= c1; + leg4.yRot += c2; + leg5.yRot -= c2; + leg6.yRot += c3; + leg7.yRot -= c3; + + leg0.zRot += s0; + leg1.zRot -= s0; + leg2.zRot += s1; + leg3.zRot -= s1; + leg4.zRot += s2; + leg5.zRot -= s2; + leg6.zRot += s3; + leg7.zRot -= s3; + } +}; + diff --git a/src/client/model/ZombieModel.h b/src/client/model/ZombieModel.h index e0f404b..b3d2053 100755 --- a/src/client/model/ZombieModel.h +++ b/src/client/model/ZombieModel.h @@ -1,37 +1,35 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__ZombieModel_H__ -#define NET_MINECRAFT_CLIENT_MODEL__ZombieModel_H__ - -//package net.minecraft.client.model; - -#include "HumanoidModel.h" - -class ZombieModel: public HumanoidModel -{ - typedef HumanoidModel super; -public: - void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) { - super::setupAnim(time, r, bob, yRot, xRot, scale); - if(!holdingLeftHand && !holdingRightHand) { - float attack2 = (float) Mth::sin(attackTime * Mth::PI); - float attack = (float) Mth::sin((1 - (1 - attackTime) * (1 - attackTime)) * Mth::PI); - arm0.zRot = 0;// -attack; - arm1.zRot = 0;// +attack; - arm0.yRot = -(0.1f - attack2 * 0.6f); - arm1.yRot = +(0.1f - attack2 * 0.6f); - arm0.xRot = -Mth::PI / 2.0f; - arm1.xRot = -Mth::PI / 2.0f; - arm0.xRot -= attack2 * 1.2f - attack * 0.4f; - arm1.xRot -= attack2 * 1.2f - attack * 0.4f; - - // body.yRot = attack; - const float zBob = Mth::cos(bob * 0.09f) * 0.05f + 0.05f; - const float xBob = Mth::sin(bob * 0.067f) * 0.05f; - arm0.zRot += zBob; - arm1.zRot -= zBob; - arm0.xRot += xBob; - arm1.xRot -= xBob; - } - } -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__ZombieModel_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "HumanoidModel.h" + +class ZombieModel: public HumanoidModel +{ + typedef HumanoidModel super; +public: + void setupAnim(float time, float r, float bob, float yRot, float xRot, float scale) { + super::setupAnim(time, r, bob, yRot, xRot, scale); + if(!holdingLeftHand && !holdingRightHand) { + float attack2 = (float) Mth::sin(attackTime * Mth::PI); + float attack = (float) Mth::sin((1 - (1 - attackTime) * (1 - attackTime)) * Mth::PI); + arm0.zRot = 0;// -attack; + arm1.zRot = 0;// +attack; + arm0.yRot = -(0.1f - attack2 * 0.6f); + arm1.yRot = +(0.1f - attack2 * 0.6f); + arm0.xRot = -Mth::PI / 2.0f; + arm1.xRot = -Mth::PI / 2.0f; + arm0.xRot -= attack2 * 1.2f - attack * 0.4f; + arm1.xRot -= attack2 * 1.2f - attack * 0.4f; + + // body.yRot = attack; + const float zBob = Mth::cos(bob * 0.09f) * 0.05f + 0.05f; + const float xBob = Mth::sin(bob * 0.067f) * 0.05f; + arm0.zRot += zBob; + arm1.zRot -= zBob; + arm0.xRot += xBob; + arm1.xRot -= xBob; + } + } +}; + diff --git a/src/client/model/geom/Cube.h b/src/client/model/geom/Cube.h index 8638006..544e06f 100755 --- a/src/client/model/geom/Cube.h +++ b/src/client/model/geom/Cube.h @@ -1,29 +1,27 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL_GEOM__Cube_H__ -#define NET_MINECRAFT_CLIENT_MODEL_GEOM__Cube_H__ - -//package net.minecraft.client.model; - -#include -#include "Polygon.h" - -class Tesselator; -class ModelPart; - -class Cube -{ -public: - Cube(ModelPart* modelPart, int xTexOffs, int yTexOffs, float x0, float y0, float z0, int w, int h, int d, float g); - - void compile(Tesselator& t, float scale); - Cube* setId(const std::string& id); -private: - - VertexPT vertices[8]; - PolygonQuad polygons[6]; - std::string id; - const float x0, y0, z0, x1, y1, z1; - - friend class ModelPart; -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL_GEOM__Cube_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include +#include "Polygon.h" + +class Tesselator; +class ModelPart; + +class Cube +{ +public: + Cube(ModelPart* modelPart, int xTexOffs, int yTexOffs, float x0, float y0, float z0, int w, int h, int d, float g); + + void compile(Tesselator& t, float scale); + Cube* setId(const std::string& id); +private: + + VertexPT vertices[8]; + PolygonQuad polygons[6]; + std::string id; + const float x0, y0, z0, x1, y1, z1; + + friend class ModelPart; +}; + diff --git a/src/client/model/geom/ModelPart.h b/src/client/model/geom/ModelPart.h index e666542..b532bb3 100755 --- a/src/client/model/geom/ModelPart.h +++ b/src/client/model/geom/ModelPart.h @@ -1,74 +1,72 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL_GEOM__ModelPart_H__ -#define NET_MINECRAFT_CLIENT_MODEL_GEOM__ModelPart_H__ - -#include "../../renderer/gles.h" - -class Model; -class Cube; - -class ModelPart -{ -public: - ModelPart(const std::string& id); - ModelPart(int xTexOffs = 0, int yTexOffs = 0); - ModelPart(Model* model, int xTexOffs = 0, int yTexOffs = 0); - ~ModelPart(); - - void _init(); - void clear();//const ModelPart& rhs); - ModelPart& operator=(const ModelPart& rhs); - - void setModel(Model* model); - - void setPos( float x, float y, float z ); - void translateTo( float scale ); - - ModelPart& setTexSize(int xs, int ys); - ModelPart& texOffs(int xTexOffs, int yTexOffs); - - void mimic(const ModelPart* o); - - // Render normally - void render( float scale ); - void renderRollable( float scale ); - void draw(); - // Bad, immediate version... //@fix @todo: remove this - void renderHorrible(float scale); - void drawSlow( float scale ); - - void onGraphicsReset() { compiled = false; } - void compile( float scale ); - - void addChild(ModelPart* child); - ModelPart& addBox(const std::string& id, float x0, float y0, float z0, int w, int h, int d); - ModelPart& addBox(float x0, float y0, float z0, int w, int h, int d); - void addBox(float x0, float y0, float z0, int w, int h, int d, float g); - void addTexBox(float x0, float y0, float z0, int w, int h, int d, int tex); - - float x, y, z; - float xRot, yRot, zRot; - - bool mirror; - bool visible; - - std::vector cubes; - std::vector children; - - std::string id; - - float xTexSize; - float yTexSize; - -private: - int xTexOffs, yTexOffs; - - bool neverRender; - - bool compiled; - int list; - GLuint vboId; - - Model* model; -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL_GEOM__ModelPart_H__*/ +#pragma once + +#include "../../renderer/gles.h" + +class Model; +class Cube; + +class ModelPart +{ +public: + ModelPart(const std::string& id); + ModelPart(int xTexOffs = 0, int yTexOffs = 0); + ModelPart(Model* model, int xTexOffs = 0, int yTexOffs = 0); + ~ModelPart(); + + void _init(); + void clear();//const ModelPart& rhs); + ModelPart& operator=(const ModelPart& rhs); + + void setModel(Model* model); + + void setPos( float x, float y, float z ); + void translateTo( float scale ); + + ModelPart& setTexSize(int xs, int ys); + ModelPart& texOffs(int xTexOffs, int yTexOffs); + + void mimic(const ModelPart* o); + + // Render normally + void render( float scale ); + void renderRollable( float scale ); + void draw(); + // Bad, immediate version... //@fix @todo: remove this + void renderHorrible(float scale); + void drawSlow( float scale ); + + void onGraphicsReset() { compiled = false; } + void compile( float scale ); + + void addChild(ModelPart* child); + ModelPart& addBox(const std::string& id, float x0, float y0, float z0, int w, int h, int d); + ModelPart& addBox(float x0, float y0, float z0, int w, int h, int d); + void addBox(float x0, float y0, float z0, int w, int h, int d, float g); + void addTexBox(float x0, float y0, float z0, int w, int h, int d, int tex); + + float x, y, z; + float xRot, yRot, zRot; + + bool mirror; + bool visible; + + std::vector cubes; + std::vector children; + + std::string id; + + float xTexSize; + float yTexSize; + +private: + int xTexOffs, yTexOffs; + + bool neverRender; + + bool compiled; + int list; + GLuint vboId; + + Model* model; +}; + diff --git a/src/client/model/geom/Polygon.h b/src/client/model/geom/Polygon.h index 7731f9c..3f05602 100755 --- a/src/client/model/geom/Polygon.h +++ b/src/client/model/geom/Polygon.h @@ -1,29 +1,27 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__Polygon_H__ -#define NET_MINECRAFT_CLIENT_MODEL__Polygon_H__ - -//package net.minecraft.client.model; -#include "Vertex.h" - -class Tesselator; - -class PolygonQuad -{ -public: - PolygonQuad() {} - PolygonQuad(VertexPT*,VertexPT*,VertexPT*,VertexPT*); - PolygonQuad(VertexPT*,VertexPT*,VertexPT*,VertexPT*, int u0, int v0, int u1, int v1, float texW = 64.0f, float texH = 32.0f); - PolygonQuad(VertexPT*,VertexPT*,VertexPT*,VertexPT*, float u0, float v0, float u1, float v1); - - void mirror(); - void render(Tesselator& t, float scale, int vboId = -1); - PolygonQuad* flipNormal(); - - VertexPT vertices[4]; - //int vertexCount; - -private: - static const int VERTEX_COUNT = 4; - bool _flipNormal; -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__Polygon_H__*/ +#pragma once + +//package net.minecraft.client.model; +#include "Vertex.h" + +class Tesselator; + +class PolygonQuad +{ +public: + PolygonQuad() {} + PolygonQuad(VertexPT*,VertexPT*,VertexPT*,VertexPT*); + PolygonQuad(VertexPT*,VertexPT*,VertexPT*,VertexPT*, int u0, int v0, int u1, int v1, float texW = 64.0f, float texH = 32.0f); + PolygonQuad(VertexPT*,VertexPT*,VertexPT*,VertexPT*, float u0, float v0, float u1, float v1); + + void mirror(); + void render(Tesselator& t, float scale, int vboId = -1); + PolygonQuad* flipNormal(); + + VertexPT vertices[4]; + //int vertexCount; + +private: + static const int VERTEX_COUNT = 4; + bool _flipNormal; +}; + diff --git a/src/client/model/geom/Vertex.h b/src/client/model/geom/Vertex.h index b7babbb..d1378cf 100755 --- a/src/client/model/geom/Vertex.h +++ b/src/client/model/geom/Vertex.h @@ -1,40 +1,38 @@ -#ifndef NET_MINECRAFT_CLIENT_MODEL__Vertex_H__ -#define NET_MINECRAFT_CLIENT_MODEL__Vertex_H__ - -//package net.minecraft.client.model; - -#include "../../../world/phys/Vec3.h" - -class VertexPT -{ -public: - Vec3 pos; - - float u, v; - - VertexPT() {} - - VertexPT(float x, float y, float z, float u_, float v_) - : pos(x, y, z), - u(u_), - v(v_) - {} - - VertexPT remap(float u, float v) { - return VertexPT(*this, u, v); - } - - VertexPT(const VertexPT& vertex, float u_, float v_) { - pos = vertex.pos; - u = u_; - v = v_; - } - - VertexPT(const Vec3& pos_, float u_, float v_) { - pos = pos_; - u = u_; - v = v_; - } -}; - -#endif /*NET_MINECRAFT_CLIENT_MODEL__Vertex_H__*/ +#pragma once + +//package net.minecraft.client.model; + +#include "../../../world/phys/Vec3.h" + +class VertexPT +{ +public: + Vec3 pos; + + float u, v; + + VertexPT() {} + + VertexPT(float x, float y, float z, float u_, float v_) + : pos(x, y, z), + u(u_), + v(v_) + {} + + VertexPT remap(float u, float v) { + return VertexPT(*this, u, v); + } + + VertexPT(const VertexPT& vertex, float u_, float v_) { + pos = vertex.pos; + u = u_; + v = v_; + } + + VertexPT(const Vec3& pos_, float u_, float v_) { + pos = pos_; + u = u_; + v = v_; + } +}; + diff --git a/src/client/multiplayer/MultiPlayerLevel.h b/src/client/multiplayer/MultiPlayerLevel.h index 3ed5737..2876b84 100755 --- a/src/client/multiplayer/MultiPlayerLevel.h +++ b/src/client/multiplayer/MultiPlayerLevel.h @@ -1,265 +1,263 @@ -#ifndef NET_MINECRAFT_CLIENT_MULTIPLAYER__MultiPlayerLevel_H__ -#define NET_MINECRAFT_CLIENT_MULTIPLAYER__MultiPlayerLevel_H__ - -#include "../../world/Pos.h" -#include "../../world/level/Level.h" -//#include "../../network/packet/DisconnectPacket.h" -#include "../../world/entity/Entity.h" -#include "../../world/level/chunk/ChunkSource.h" -#include "../../world/level/dimension/Dimension.h" -//#include "../../world/level/storage/MockedLevelStorage.h" - -#include -#include -#include - -class MultiPlayerLevel: public Level -{ - typedef Level super; - typedef std::map EntityIdMap; - typedef std::set EntitySet; - - static const int TICKS_BEFORE_RESET = SharedConstants::TicksPerSecond * 4; - - class ResetInfo { - public: - int x, y, z, ticks, tile, data; - - ResetInfo(int x, int y, int z, int tile, int data) - : x(x), - y(y), - z(z), - ticks(TICKS_BEFORE_RESET), - tile(tile), - data(data) - {} - }; - typedef std::list ResetInfoList; - -public: - MultiPlayerLevel(LevelStorage* levelStorage, const std::string& levelName, const LevelSettings& settings, int levelVersion) - : super(levelStorage, levelName, settings, levelVersion) - { - //super(new MockedLevelStorage(), "MpServer", Dimension.getNew(dimension), levelSettings); - //this->difficulty = difficulty; - //setSpawnPos(new Pos(8, 64, 8)); - //this.savedDataStorage = connection.savedDataStorage; - } - - //@todo: destructor (to Entities) - - void tick() { - if (adventureSettings.doTickTime) { - setTime(getTime() + 1); - } - updateSkyDarken(); - - for (int i = 0; i < 10 && !reEntries.empty(); i++) { - EntitySet::iterator it = reEntries.begin(); - Entity* e = *it;//reEntries.iterator().next(); - reEntries.erase(it); - - //if (!entities.contains(e)) addEntity(e); - EntityList::iterator jt = std::find(entities.begin(), entities.end(), e); - if (jt == entities.end()) - addEntity(e); - } - - for (ResetInfoList::iterator it = updatesToReset.begin(); it != updatesToReset.end();) { - ResetInfo& r = *it; - if (--r.ticks == 0) { - super::setTileAndDataNoUpdate(r.x, r.y, r.z, r.tile, r.data); - super::sendTileUpdated(r.x, r.y, r.z); - it = updatesToReset.erase(it); - } else - ++it; - } - } - - void clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1) { - for (ResetInfoList::iterator it = updatesToReset.begin(); it != updatesToReset.end();) { - ResetInfo& r = *it; - if (r.x >= x0 && r.y >= y0 && r.z >= z0 && r.x <= x1 && r.y <= y1 && r.z <= z1) { - it = updatesToReset.erase(it); - } else - ++it; - } - } - - void validateSpawn() { - setSpawnPos(Pos(8, 64, 8)); - } - - void addToTickNextTick(int x, int y, int z, int tileId, int tickDelay) { - } - - bool tickPendingTicks(bool force) { - return false; - } - - //@todo - //void setChunkVisible(int x, int z, bool visible) { - // if (visible) chunkCache.create(x, z); - // else chunkCache.drop(x, z); - // if (!visible) { - // this->setTilesDirty(x * 16, 0, z * 16, x * 16 + 15, depth, z * 16 + 15); - // } - //} - - bool addEntity(Entity* e) { - bool ok = super::addEntity(e); - forced.insert(e); - - if (!ok) { - reEntries.insert(e); - } - - return ok; - } - - void removeEntity(Entity* e) { - super::removeEntity(e); - forced.erase(e); - } - - void putEntity(int id, Entity* e) { - Entity* old = getEntity(id); - if (old != NULL) { - removeEntity(old); - } - - forced.insert(e); - e->entityId = id; - if (!addEntity(e)) { - reEntries.insert(e); - } - entitiesById.insert(std::make_pair(id, e)); - } - - Entity* getEntity(int id) { - EntityIdMap::const_iterator cit = entitiesById.find(id); - return cit != entitiesById.end()? cit->second : NULL; - } - - Entity* removeEntity(int id) { - EntityIdMap::iterator it = entitiesById.find(id); - if (it != entitiesById.end()) { - Entity* e = it->second; - entitiesById.erase(it); - removeEntity(e); - return it->second; - } - return NULL; - } - - bool setDataNoUpdate(int x, int y, int z, int data) { - int t = getTile(x, y, z); - int d = getData(x, y, z); - if (super::setDataNoUpdate(x, y, z, data)) { - updatesToReset.push_back(/*new*/ ResetInfo(x, y, z, t, d)); - return true; - } - return false; - } - - bool setTileAndDataNoUpdate(int x, int y, int z, int tile, int data) { - int t = getTile(x, y, z); - int d = getData(x, y, z); - if (super::setTileAndDataNoUpdate(x, y, z, tile, data)) { - updatesToReset.push_back(/*new*/ ResetInfo(x, y, z, t, d)); - return true; - } - return false; - } - - bool setTileNoUpdate(int x, int y, int z, int tile) { - int t = getTile(x, y, z); - int d = getData(x, y, z); - if (super::setTileNoUpdate(x, y, z, tile)) { - updatesToReset.push_back(/*new*/ ResetInfo(x, y, z, t, d)); - return true; - } - return false; - } - - bool doSetTileAndData(int x, int y, int z, int tile, int data) { - clearResetRegion(x, y, z, x, y, z); - if (super::setTileAndDataNoUpdate(x, y, z, tile, data)) { - // if (setTile(x, y, z, tile)) { - // setData(x, y, z, data); - tileUpdated(x, y, z, tile); - return true; - } - return false; - } - - void disconnect() { - //connection.sendAndDisconnect(/*new*/ DisconnectPacket("Quitting")); - } - -protected: - void tickTiles() { - } - /*@Override*/ - ChunkSource* createChunkSource() { - //chunkCache = /*new*/ MultiPlayerChunkCache(this); - //return chunkCache; - return NULL; - } - - void entityAdded(Entity* e) { - super::entityAdded(e); - EntitySet::iterator it = reEntries.find(e); - if (it != reEntries.end()) { - reEntries.erase(it); - } - } - - void entityRemoved(Entity* e) { - super::entityRemoved(e); - EntitySet::iterator it = forced.find(e); - if (it != forced.end()) { - if (e->isAlive()) { - reEntries.insert(e); - } else { - forced.erase(it); - } - } - } - -// void tickWeather() { -// if (dimension.hasCeiling) return; -// -// if (lightningTime > 0) { -// lightningTime--; -// } -// -// oRainLevel = rainLevel; -// if (levelData.isRaining()) { -// rainLevel += 0.01; -// } else { -// rainLevel -= 0.01; -// } -// if (rainLevel < 0) rainLevel = 0; -// if (rainLevel > 1) rainLevel = 1; -// -// oThunderLevel = thunderLevel; -// if (levelData.isThundering()) { -// thunderLevel += 0.01; -// } else { -// thunderLevel -= 0.01; -// } -// if (thunderLevel < 0) thunderLevel = 0; -// if (thunderLevel > 1) thunderLevel = 1; -// } -private: - ResetInfoList updatesToReset; - //ClientConnection connection; - //MultiPlayerChunkCache chunkCache; - - EntityIdMap entitiesById; - EntitySet forced; - EntitySet reEntries; -}; - -#endif /*NET_MINECRAFT_CLIENT_MULTIPLAYER__MultiPlayerLevel_H__*/ +#pragma once + +#include "../../world/Pos.h" +#include "../../world/level/Level.h" +//#include "../../network/packet/DisconnectPacket.h" +#include "../../world/entity/Entity.h" +#include "../../world/level/chunk/ChunkSource.h" +#include "../../world/level/dimension/Dimension.h" +//#include "../../world/level/storage/MockedLevelStorage.h" + +#include +#include +#include + +class MultiPlayerLevel: public Level +{ + typedef Level super; + typedef std::map EntityIdMap; + typedef std::set EntitySet; + + static const int TICKS_BEFORE_RESET = SharedConstants::TicksPerSecond * 4; + + class ResetInfo { + public: + int x, y, z, ticks, tile, data; + + ResetInfo(int x, int y, int z, int tile, int data) + : x(x), + y(y), + z(z), + ticks(TICKS_BEFORE_RESET), + tile(tile), + data(data) + {} + }; + typedef std::list ResetInfoList; + +public: + MultiPlayerLevel(LevelStorage* levelStorage, const std::string& levelName, const LevelSettings& settings, int levelVersion) + : super(levelStorage, levelName, settings, levelVersion) + { + //super(new MockedLevelStorage(), "MpServer", Dimension.getNew(dimension), levelSettings); + //this->difficulty = difficulty; + //setSpawnPos(new Pos(8, 64, 8)); + //this.savedDataStorage = connection.savedDataStorage; + } + + //@todo: destructor (to Entities) + + void tick() { + if (adventureSettings.doTickTime) { + setTime(getTime() + 1); + } + updateSkyDarken(); + + for (int i = 0; i < 10 && !reEntries.empty(); i++) { + EntitySet::iterator it = reEntries.begin(); + Entity* e = *it;//reEntries.iterator().next(); + reEntries.erase(it); + + //if (!entities.contains(e)) addEntity(e); + EntityList::iterator jt = std::find(entities.begin(), entities.end(), e); + if (jt == entities.end()) + addEntity(e); + } + + for (ResetInfoList::iterator it = updatesToReset.begin(); it != updatesToReset.end();) { + ResetInfo& r = *it; + if (--r.ticks == 0) { + super::setTileAndDataNoUpdate(r.x, r.y, r.z, r.tile, r.data); + super::sendTileUpdated(r.x, r.y, r.z); + it = updatesToReset.erase(it); + } else + ++it; + } + } + + void clearResetRegion(int x0, int y0, int z0, int x1, int y1, int z1) { + for (ResetInfoList::iterator it = updatesToReset.begin(); it != updatesToReset.end();) { + ResetInfo& r = *it; + if (r.x >= x0 && r.y >= y0 && r.z >= z0 && r.x <= x1 && r.y <= y1 && r.z <= z1) { + it = updatesToReset.erase(it); + } else + ++it; + } + } + + void validateSpawn() { + setSpawnPos(Pos(8, 64, 8)); + } + + void addToTickNextTick(int x, int y, int z, int tileId, int tickDelay) { + } + + bool tickPendingTicks(bool force) { + return false; + } + + //@todo + //void setChunkVisible(int x, int z, bool visible) { + // if (visible) chunkCache.create(x, z); + // else chunkCache.drop(x, z); + // if (!visible) { + // this->setTilesDirty(x * 16, 0, z * 16, x * 16 + 15, depth, z * 16 + 15); + // } + //} + + bool addEntity(Entity* e) { + bool ok = super::addEntity(e); + forced.insert(e); + + if (!ok) { + reEntries.insert(e); + } + + return ok; + } + + void removeEntity(Entity* e) { + super::removeEntity(e); + forced.erase(e); + } + + void putEntity(int id, Entity* e) { + Entity* old = getEntity(id); + if (old != NULL) { + removeEntity(old); + } + + forced.insert(e); + e->entityId = id; + if (!addEntity(e)) { + reEntries.insert(e); + } + entitiesById.insert(std::make_pair(id, e)); + } + + Entity* getEntity(int id) { + EntityIdMap::const_iterator cit = entitiesById.find(id); + return cit != entitiesById.end()? cit->second : NULL; + } + + Entity* removeEntity(int id) { + EntityIdMap::iterator it = entitiesById.find(id); + if (it != entitiesById.end()) { + Entity* e = it->second; + entitiesById.erase(it); + removeEntity(e); + return it->second; + } + return NULL; + } + + bool setDataNoUpdate(int x, int y, int z, int data) { + int t = getTile(x, y, z); + int d = getData(x, y, z); + if (super::setDataNoUpdate(x, y, z, data)) { + updatesToReset.push_back(/*new*/ ResetInfo(x, y, z, t, d)); + return true; + } + return false; + } + + bool setTileAndDataNoUpdate(int x, int y, int z, int tile, int data) { + int t = getTile(x, y, z); + int d = getData(x, y, z); + if (super::setTileAndDataNoUpdate(x, y, z, tile, data)) { + updatesToReset.push_back(/*new*/ ResetInfo(x, y, z, t, d)); + return true; + } + return false; + } + + bool setTileNoUpdate(int x, int y, int z, int tile) { + int t = getTile(x, y, z); + int d = getData(x, y, z); + if (super::setTileNoUpdate(x, y, z, tile)) { + updatesToReset.push_back(/*new*/ ResetInfo(x, y, z, t, d)); + return true; + } + return false; + } + + bool doSetTileAndData(int x, int y, int z, int tile, int data) { + clearResetRegion(x, y, z, x, y, z); + if (super::setTileAndDataNoUpdate(x, y, z, tile, data)) { + // if (setTile(x, y, z, tile)) { + // setData(x, y, z, data); + tileUpdated(x, y, z, tile); + return true; + } + return false; + } + + void disconnect() { + //connection.sendAndDisconnect(/*new*/ DisconnectPacket("Quitting")); + } + +protected: + void tickTiles() { + } + /*@Override*/ + ChunkSource* createChunkSource() { + //chunkCache = /*new*/ MultiPlayerChunkCache(this); + //return chunkCache; + return NULL; + } + + void entityAdded(Entity* e) { + super::entityAdded(e); + EntitySet::iterator it = reEntries.find(e); + if (it != reEntries.end()) { + reEntries.erase(it); + } + } + + void entityRemoved(Entity* e) { + super::entityRemoved(e); + EntitySet::iterator it = forced.find(e); + if (it != forced.end()) { + if (e->isAlive()) { + reEntries.insert(e); + } else { + forced.erase(it); + } + } + } + +// void tickWeather() { +// if (dimension.hasCeiling) return; +// +// if (lightningTime > 0) { +// lightningTime--; +// } +// +// oRainLevel = rainLevel; +// if (levelData.isRaining()) { +// rainLevel += 0.01; +// } else { +// rainLevel -= 0.01; +// } +// if (rainLevel < 0) rainLevel = 0; +// if (rainLevel > 1) rainLevel = 1; +// +// oThunderLevel = thunderLevel; +// if (levelData.isThundering()) { +// thunderLevel += 0.01; +// } else { +// thunderLevel -= 0.01; +// } +// if (thunderLevel < 0) thunderLevel = 0; +// if (thunderLevel > 1) thunderLevel = 1; +// } +private: + ResetInfoList updatesToReset; + //ClientConnection connection; + //MultiPlayerChunkCache chunkCache; + + EntityIdMap entitiesById; + EntitySet forced; + EntitySet reEntries; +}; + diff --git a/src/client/particle/BreakingItemParticle.h b/src/client/particle/BreakingItemParticle.h index b92e2dd..1951641 100755 --- a/src/client/particle/BreakingItemParticle.h +++ b/src/client/particle/BreakingItemParticle.h @@ -1,66 +1,64 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__BreakingItemParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__BreakingItemParticle_H__ - -//package net.minecraft.client.particle; - -#include "Particle.h" -#include "../renderer/Tesselator.h" -#include "../../world/item/Item.h" -#include "../../world/level/Level.h" -#include "../../world/level/tile/Tile.h" - -class BreakingItemParticle: public Particle -{ - typedef Particle super; -public: - BreakingItemParticle(Level* level, float x, float y, float z, Item* item) - : super(level, x, y, z, 0, 0, 0) - { - _init(item); - } - - BreakingItemParticle(Level* level, float x, float y, float z, float xa, float ya, float za, Item* item) - : super(level, x, y, z, 0, 0, 0) - { - _init(item); - - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - xd += xa; - yd += ya; - zd += za; - } - - void _init(Item* item) { - tex = item->getIcon(0); - rCol = gCol = bCol = 1.0f; - gravity = Tile::snow->gravity; - size /= 2; - } - - int getParticleTexture() { - return ParticleEngine::ITEM_TEXTURE; - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { - float u0 = (tex % 16 + uo / 4.0f) / 16.0f; - float u1 = u0 + 0.999f / 16.0f / 4; - float v0 = (tex / 16 + vo / 4.0f) / 16.0f; - float v1 = v0 + 0.999f / 16.0f / 4; - float r = 0.1f * size; - - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); - float br = getBrightness(a); - t.color(br * rCol, br * gCol, br * bCol); - - t.vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u0, v1); - t.vertexUV(x - xa * r + xa2 * r, y + ya * r, z - za * r + za2 * r, u0, v0); - t.vertexUV(x + xa * r + xa2 * r, y + ya * r, z + za * r + za2 * r, u1, v0); - t.vertexUV(x + xa * r - xa2 * r, y - ya * r, z + za * r - za2 * r, u1, v1); - } -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__BreakingItemParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "Particle.h" +#include "../renderer/Tesselator.h" +#include "../../world/item/Item.h" +#include "../../world/level/Level.h" +#include "../../world/level/tile/Tile.h" + +class BreakingItemParticle: public Particle +{ + typedef Particle super; +public: + BreakingItemParticle(Level* level, float x, float y, float z, Item* item) + : super(level, x, y, z, 0, 0, 0) + { + _init(item); + } + + BreakingItemParticle(Level* level, float x, float y, float z, float xa, float ya, float za, Item* item) + : super(level, x, y, z, 0, 0, 0) + { + _init(item); + + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + xd += xa; + yd += ya; + zd += za; + } + + void _init(Item* item) { + tex = item->getIcon(0); + rCol = gCol = bCol = 1.0f; + gravity = Tile::snow->gravity; + size /= 2; + } + + int getParticleTexture() { + return ParticleEngine::ITEM_TEXTURE; + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { + float u0 = (tex % 16 + uo / 4.0f) / 16.0f; + float u1 = u0 + 0.999f / 16.0f / 4; + float v0 = (tex / 16 + vo / 4.0f) / 16.0f; + float v1 = v0 + 0.999f / 16.0f / 4; + float r = 0.1f * size; + + float x = (float) (xo + (this->x - xo) * a - xOff); + float y = (float) (yo + (this->y - yo) * a - yOff); + float z = (float) (zo + (this->z - zo) * a - zOff); + float br = getBrightness(a); + t.color(br * rCol, br * gCol, br * bCol); + + t.vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u0, v1); + t.vertexUV(x - xa * r + xa2 * r, y + ya * r, z - za * r + za2 * r, u0, v0); + t.vertexUV(x + xa * r + xa2 * r, y + ya * r, z + za * r + za2 * r, u1, v0); + t.vertexUV(x + xa * r - xa2 * r, y - ya * r, z + za * r - za2 * r, u1, v1); + } +}; + diff --git a/src/client/particle/BubbleParticle.h b/src/client/particle/BubbleParticle.h index 4e2ee48..2508d22 100755 --- a/src/client/particle/BubbleParticle.h +++ b/src/client/particle/BubbleParticle.h @@ -1,51 +1,49 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__BubbleParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__BubbleParticle_H__ - -//package net.minecraft.client.particle; - -#include "../../util/Mth.h" -#include "../../world/level/Level.h" -#include "../../world/level/material/Material.h" -#include "Particle.h" - -class BubbleParticle: public Particle -{ - typedef Particle super; - -public: - BubbleParticle(Level* level, float x, float y, float z, float xa, float ya, float za) - : super(level, x, y, z, xa, ya, za) - { - rCol = 1.0f; - gCol = 1.0f; - bCol = 1.0f; - tex = 32; - this->setSize(0.02f, 0.02f); - - size = size*(sharedRandom.nextFloat()*0.6f+0.2f); - - xd = xa*0.2f+(float)(Mth::random()*2-1)*0.02f; - yd = ya*0.2f+(float)(Mth::random()*2-1)*0.02f; - zd = za*0.2f+(float)(Mth::random()*2-1)*0.02f; - - lifetime = (int) (8 / (Mth::random() * 0.8 + 0.2)); - } - - void tick() { - xo = x; - yo = y; - zo = z; - - yd += 0.002f; - move(xd, yd, zd); - xd *= 0.85f; - yd *= 0.85f; - zd *= 0.85f; - - if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != Material::water) remove(); - - if (lifetime-- <= 0) remove(); - } -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__BubbleParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "../../util/Mth.h" +#include "../../world/level/Level.h" +#include "../../world/level/material/Material.h" +#include "Particle.h" + +class BubbleParticle: public Particle +{ + typedef Particle super; + +public: + BubbleParticle(Level* level, float x, float y, float z, float xa, float ya, float za) + : super(level, x, y, z, xa, ya, za) + { + rCol = 1.0f; + gCol = 1.0f; + bCol = 1.0f; + tex = 32; + this->setSize(0.02f, 0.02f); + + size = size*(sharedRandom.nextFloat()*0.6f+0.2f); + + xd = xa*0.2f+(float)(Mth::random()*2-1)*0.02f; + yd = ya*0.2f+(float)(Mth::random()*2-1)*0.02f; + zd = za*0.2f+(float)(Mth::random()*2-1)*0.02f; + + lifetime = (int) (8 / (Mth::random() * 0.8 + 0.2)); + } + + void tick() { + xo = x; + yo = y; + zo = z; + + yd += 0.002f; + move(xd, yd, zd); + xd *= 0.85f; + yd *= 0.85f; + zd *= 0.85f; + + if (level->getMaterial(Mth::floor(x), Mth::floor(y), Mth::floor(z)) != Material::water) remove(); + + if (lifetime-- <= 0) remove(); + } +}; + diff --git a/src/client/particle/CritParticle2.h b/src/client/particle/CritParticle2.h index 229e386..4f1444a 100755 --- a/src/client/particle/CritParticle2.h +++ b/src/client/particle/CritParticle2.h @@ -1,74 +1,72 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__CritParticle2_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__CritParticle2_H__ - -//package net.minecraft.client.particle; - -#include "Particle.h" -#include "../../util/Mth.h" -#include "../../world/level/Level.h" -#include "../../world/level/material/Material.h" - -class CritParticle2: public Particle -{ - typedef Particle super; -public: - CritParticle2(Level* level, float x, float y, float z, float xa, float ya, float za, float scale = 1.0f) - : super(level, x, y, z, 0, 0, 0), - visible(true) - { - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - xd += xa * 0.4f; - yd += ya * 0.4f; - zd += za * 0.4f; - - rCol = gCol = bCol = (float) (Mth::random() * 0.3f + 0.6f); - size *= 0.75f; - size *= scale; - oSize = size; - - lifetime = (int)(6 / (Mth::random() * 0.8f + 0.6f) * scale); - noPhysics = false; - - tex = 16 * 4 + 1; - tick(); - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { - if (!visible) return; - float l = ((age + a) / lifetime) * 32; - if (l < 0) l = 0; - if (l > 1) l = 1; - - size = oSize * l; - super::render(t, a, xa, ya, za, xa2, za2); - } - - void tick() { - xo = x; - yo = y; - zo = z; - - if (age++ >= lifetime) remove(); - - move(xd, yd, zd); - gCol *= 0.96f; - bCol *= 0.9f; - - xd *= 0.70f; - yd *= 0.70f; - zd *= 0.70f; - yd -= 0.02f; - - if (onGround) { - xd *= 0.7f; - zd *= 0.7f; - } - } -protected: - bool visible; - float oSize; -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__CritParticle2_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "Particle.h" +#include "../../util/Mth.h" +#include "../../world/level/Level.h" +#include "../../world/level/material/Material.h" + +class CritParticle2: public Particle +{ + typedef Particle super; +public: + CritParticle2(Level* level, float x, float y, float z, float xa, float ya, float za, float scale = 1.0f) + : super(level, x, y, z, 0, 0, 0), + visible(true) + { + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + xd += xa * 0.4f; + yd += ya * 0.4f; + zd += za * 0.4f; + + rCol = gCol = bCol = (float) (Mth::random() * 0.3f + 0.6f); + size *= 0.75f; + size *= scale; + oSize = size; + + lifetime = (int)(6 / (Mth::random() * 0.8f + 0.6f) * scale); + noPhysics = false; + + tex = 16 * 4 + 1; + tick(); + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { + if (!visible) return; + float l = ((age + a) / lifetime) * 32; + if (l < 0) l = 0; + if (l > 1) l = 1; + + size = oSize * l; + super::render(t, a, xa, ya, za, xa2, za2); + } + + void tick() { + xo = x; + yo = y; + zo = z; + + if (age++ >= lifetime) remove(); + + move(xd, yd, zd); + gCol *= 0.96f; + bCol *= 0.9f; + + xd *= 0.70f; + yd *= 0.70f; + zd *= 0.70f; + yd -= 0.02f; + + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } + } +protected: + bool visible; + float oSize; +}; + diff --git a/src/client/particle/ExplodeParticle.h b/src/client/particle/ExplodeParticle.h index 0eeb305..dce0272 100755 --- a/src/client/particle/ExplodeParticle.h +++ b/src/client/particle/ExplodeParticle.h @@ -1,51 +1,49 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__ExplodeParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__ExplodeParticle_H__ - -//package net.minecraft.client.particle; - -#include "Particle.h" -#include "../renderer/Tesselator.h" -#include "../../world/level/Level.h" - -class ExplodeParticle: public Particle -{ - typedef Particle super; -public: - ExplodeParticle(Level* level, float x, float y, float z, float xa, float ya, float za) - : super(level, x, y, z, xa, ya, za) - { - xd = xa + (Mth::random()*2.0f-1.0f) * 0.05f; - yd = ya + (Mth::random()*2.0f-1.0f) * 0.05f; - zd = za + (Mth::random()*2.0f-1.0f) * 0.05f; - - rCol = gCol = bCol = sharedRandom.nextFloat() * 0.3f + 0.7f; - size = sharedRandom.nextFloat() * sharedRandom.nextFloat() * 6.0f + 1.0f; - - lifetime = (int)(16.0f/(sharedRandom.nextFloat() * 0.8f + 0.2f)) + 2; -// noPhysics = true; - } - - void tick() - { - xo = x; - yo = y; - zo = z; - - if (age++ >= lifetime) remove(); - - tex = 7 - age * 8 / lifetime; - - yd += 0.004f; - move(xd, yd, zd); - xd *= 0.90f; - yd *= 0.90f; - zd *= 0.90f; - - if (onGround) { - xd *= 0.7f; - zd *= 0.7f; - } - } -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__ExplodeParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "Particle.h" +#include "../renderer/Tesselator.h" +#include "../../world/level/Level.h" + +class ExplodeParticle: public Particle +{ + typedef Particle super; +public: + ExplodeParticle(Level* level, float x, float y, float z, float xa, float ya, float za) + : super(level, x, y, z, xa, ya, za) + { + xd = xa + (Mth::random()*2.0f-1.0f) * 0.05f; + yd = ya + (Mth::random()*2.0f-1.0f) * 0.05f; + zd = za + (Mth::random()*2.0f-1.0f) * 0.05f; + + rCol = gCol = bCol = sharedRandom.nextFloat() * 0.3f + 0.7f; + size = sharedRandom.nextFloat() * sharedRandom.nextFloat() * 6.0f + 1.0f; + + lifetime = (int)(16.0f/(sharedRandom.nextFloat() * 0.8f + 0.2f)) + 2; +// noPhysics = true; + } + + void tick() + { + xo = x; + yo = y; + zo = z; + + if (age++ >= lifetime) remove(); + + tex = 7 - age * 8 / lifetime; + + yd += 0.004f; + move(xd, yd, zd); + xd *= 0.90f; + yd *= 0.90f; + zd *= 0.90f; + + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } + } +}; + diff --git a/src/client/particle/FlameParticle.h b/src/client/particle/FlameParticle.h index 56fe208..aefd61c 100755 --- a/src/client/particle/FlameParticle.h +++ b/src/client/particle/FlameParticle.h @@ -1,73 +1,71 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__FlameParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__FlameParticle_H__ - -//package net.minecraft.client.particle; - -#include "Particle.h" -#include "../renderer/Tesselator.h" -#include "../../world/level/Level.h" - -class FlameParticle: public Particle -{ - typedef Particle super; - float oSize; -public: - FlameParticle(Level* level, float x, float y, float z, float xa, float ya, float za) - : super(level, x, y, z, xa, ya, za) - { - xd = xd * 0.01f + xa; - yd = yd * 0.01f + ya; - zd = zd * 0.01f + za; - x += (sharedRandom.nextFloat()-sharedRandom.nextFloat()) * 0.05f; - y += (sharedRandom.nextFloat()-sharedRandom.nextFloat()) * 0.05f; - z += (sharedRandom.nextFloat()-sharedRandom.nextFloat()) * 0.05f; - - //printf("xd, yd, zd: %f, %f, %f\n", xd, yd, zd); - - oSize = size; - rCol = gCol = bCol = 1.0f; - - lifetime = (int)(8.0f/(Mth::random()*0.8f+0.2f))+4; - noPhysics = true; - tex = 48; - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { - float s = (age + a) / (float) lifetime; - size = oSize * (1 - s*s*0.5f); - super::render(t, a, xa, ya, za, xa2, za2); - } - - float getBrightness(float a) { - return 1.0f; -/* - float l = (age+a)/lifetime; - if (l<0) l = 0; - if (l>1) l = 1; - float br = super::getBrightness(a); - - return br*l+(1-l); -*/ - } - - void tick() - { - xo = x; - yo = y; - zo = z; - - if (age++ >= lifetime) remove(); - - move(xd, yd, zd); - xd *= 0.96f; - yd *= 0.96f; - zd *= 0.96f; - - if (onGround) - { - xd *= 0.7f; - zd *= 0.7f; - } - } -}; -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__FlameParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "Particle.h" +#include "../renderer/Tesselator.h" +#include "../../world/level/Level.h" + +class FlameParticle: public Particle +{ + typedef Particle super; + float oSize; +public: + FlameParticle(Level* level, float x, float y, float z, float xa, float ya, float za) + : super(level, x, y, z, xa, ya, za) + { + xd = xd * 0.01f + xa; + yd = yd * 0.01f + ya; + zd = zd * 0.01f + za; + x += (sharedRandom.nextFloat()-sharedRandom.nextFloat()) * 0.05f; + y += (sharedRandom.nextFloat()-sharedRandom.nextFloat()) * 0.05f; + z += (sharedRandom.nextFloat()-sharedRandom.nextFloat()) * 0.05f; + + //printf("xd, yd, zd: %f, %f, %f\n", xd, yd, zd); + + oSize = size; + rCol = gCol = bCol = 1.0f; + + lifetime = (int)(8.0f/(Mth::random()*0.8f+0.2f))+4; + noPhysics = true; + tex = 48; + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { + float s = (age + a) / (float) lifetime; + size = oSize * (1 - s*s*0.5f); + super::render(t, a, xa, ya, za, xa2, za2); + } + + float getBrightness(float a) { + return 1.0f; +/* + float l = (age+a)/lifetime; + if (l<0) l = 0; + if (l>1) l = 1; + float br = super::getBrightness(a); + + return br*l+(1-l); +*/ + } + + void tick() + { + xo = x; + yo = y; + zo = z; + + if (age++ >= lifetime) remove(); + + move(xd, yd, zd); + xd *= 0.96f; + yd *= 0.96f; + zd *= 0.96f; + + if (onGround) + { + xd *= 0.7f; + zd *= 0.7f; + } + } +}; diff --git a/src/client/particle/HugeExplosionParticle.h b/src/client/particle/HugeExplosionParticle.h index 4bcd297..4225ee0 100755 --- a/src/client/particle/HugeExplosionParticle.h +++ b/src/client/particle/HugeExplosionParticle.h @@ -1,72 +1,70 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__HugeExplosionParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__HugeExplosionParticle_H__ - -//package net.minecraft.client.particle; - -#include "../renderer/Tesselator.h" -#include "../renderer/Textures.h" -#include "../../world/level/Level.h" - -class HugeExplosionParticle: public Particle -{ - typedef Particle super; -public: - HugeExplosionParticle(Textures* textures, Level* level, float x, float y, float z, float xa, float ya, float za) - : super(level, x, y, z, 0, 0, 0), - life(0), - lifeTime(6 + sharedRandom.nextInt(4)), - textures(textures), - size(1 - xa * 0.5f) - { - rCol = gCol = bCol = sharedRandom.nextFloat() * 0.6f + 0.4f; - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { - int tex = (int) ((life + a) * 15 / lifeTime); - if (tex > 15) return; - textures->loadAndBindTexture("misc/explosion.png"); - - float u0 = (tex % 4) / 4.0f; - float u1 = u0 + 0.999f / 4.0f; - float v0 = (tex / 4) / 4.0f; - float v1 = v0 + 0.999f / 4.0f; - -// xa2 = 0; -// za2 = 1; - - float r = size + size; - - float x = xo + (this->x - xo) * a - xOff; - float y = yo + (this->y - yo) * a - yOff; - float z = zo + (this->z - zo) * a - zOff; - const float xar = xa * r, yar = ya * r, zar = za * r; - const float xa2r = xa2 * r, za2r = za2 * r; - t.begin(); - t.color(rCol, gCol, bCol, 1.0f); - t.vertexUV(x - xar - xa2r, y - yar, z - zar - za2r, u1, v1); - t.vertexUV(x - xar + xa2r, y + yar, z - zar + za2r, u1, v0); - t.vertexUV(x + xar + xa2r, y + yar, z + zar + za2r, u0, v0); - t.vertexUV(x + xar - xa2r, y - yar, z + zar - za2r, u0, v1); - t.draw(); - //glPolygonOffset(0, 0.0f); - } - - void tick() { - xo = x; - yo = y; - zo = z; - life++; - if (life == lifeTime) remove(); - } - - int getParticleTexture() { - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; - } -private: - int life; - int lifeTime; - float size; - Textures* textures; -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__HugeExplosionParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "../renderer/Tesselator.h" +#include "../renderer/Textures.h" +#include "../../world/level/Level.h" + +class HugeExplosionParticle: public Particle +{ + typedef Particle super; +public: + HugeExplosionParticle(Textures* textures, Level* level, float x, float y, float z, float xa, float ya, float za) + : super(level, x, y, z, 0, 0, 0), + life(0), + lifeTime(6 + sharedRandom.nextInt(4)), + textures(textures), + size(1 - xa * 0.5f) + { + rCol = gCol = bCol = sharedRandom.nextFloat() * 0.6f + 0.4f; + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { + int tex = (int) ((life + a) * 15 / lifeTime); + if (tex > 15) return; + textures->loadAndBindTexture("misc/explosion.png"); + + float u0 = (tex % 4) / 4.0f; + float u1 = u0 + 0.999f / 4.0f; + float v0 = (tex / 4) / 4.0f; + float v1 = v0 + 0.999f / 4.0f; + +// xa2 = 0; +// za2 = 1; + + float r = size + size; + + float x = xo + (this->x - xo) * a - xOff; + float y = yo + (this->y - yo) * a - yOff; + float z = zo + (this->z - zo) * a - zOff; + const float xar = xa * r, yar = ya * r, zar = za * r; + const float xa2r = xa2 * r, za2r = za2 * r; + t.begin(); + t.color(rCol, gCol, bCol, 1.0f); + t.vertexUV(x - xar - xa2r, y - yar, z - zar - za2r, u1, v1); + t.vertexUV(x - xar + xa2r, y + yar, z - zar + za2r, u1, v0); + t.vertexUV(x + xar + xa2r, y + yar, z + zar + za2r, u0, v0); + t.vertexUV(x + xar - xa2r, y - yar, z + zar - za2r, u0, v1); + t.draw(); + //glPolygonOffset(0, 0.0f); + } + + void tick() { + xo = x; + yo = y; + zo = z; + life++; + if (life == lifeTime) remove(); + } + + int getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; + } +private: + int life; + int lifeTime; + float size; + Textures* textures; +}; + diff --git a/src/client/particle/HugeExplosionSeedParticle.h b/src/client/particle/HugeExplosionSeedParticle.h index 6b06e8c..15f30c3 100755 --- a/src/client/particle/HugeExplosionSeedParticle.h +++ b/src/client/particle/HugeExplosionSeedParticle.h @@ -1,40 +1,38 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__HugeExplosionSeedParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__HugeExplosionSeedParticle_H__ - -//package net.minecraft.client.particle; - -#include "Particle.h" - -class HugeExplosionSeedParticle: public Particle -{ - typedef Particle super; -public: - HugeExplosionSeedParticle(Level* level, float x, float y, float z, float xa, float ya, float za) - : super(level, x, y, z, 0, 0, 0), - life(0), - lifeTime(8) - { - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) {} - - void tick() { - for (int i = 0; i < 6; i++) { - float xx = x + (sharedRandom.nextFloat() - sharedRandom.nextFloat()) * 4; - float yy = y + (sharedRandom.nextFloat() - sharedRandom.nextFloat()) * 4; - float zz = z + (sharedRandom.nextFloat() - sharedRandom.nextFloat()) * 4; - level->addParticle(PARTICLETYPE(largeexplode), xx, yy, zz, life / (float) lifeTime, 0, 0); - } - life++; - if (life == lifeTime) remove(); - } - - int getParticleTexture() { - return ParticleEngine::TERRAIN_TEXTURE; - } -private: - int life; - int lifeTime; -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__HugeExplosionSeedParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "Particle.h" + +class HugeExplosionSeedParticle: public Particle +{ + typedef Particle super; +public: + HugeExplosionSeedParticle(Level* level, float x, float y, float z, float xa, float ya, float za) + : super(level, x, y, z, 0, 0, 0), + life(0), + lifeTime(8) + { + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) {} + + void tick() { + for (int i = 0; i < 6; i++) { + float xx = x + (sharedRandom.nextFloat() - sharedRandom.nextFloat()) * 4; + float yy = y + (sharedRandom.nextFloat() - sharedRandom.nextFloat()) * 4; + float zz = z + (sharedRandom.nextFloat() - sharedRandom.nextFloat()) * 4; + level->addParticle(PARTICLETYPE(largeexplode), xx, yy, zz, life / (float) lifeTime, 0, 0); + } + life++; + if (life == lifeTime) remove(); + } + + int getParticleTexture() { + return ParticleEngine::TERRAIN_TEXTURE; + } +private: + int life; + int lifeTime; +}; + diff --git a/src/client/particle/LavaParticle.h b/src/client/particle/LavaParticle.h index 86b6fe0..6ed2ee1 100755 --- a/src/client/particle/LavaParticle.h +++ b/src/client/particle/LavaParticle.h @@ -1,63 +1,61 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__LavaParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__LavaParticle_H__ - -//package net.minecraft.client.particle; - -#include "../renderer/Tesselator.h" -#include "../../world/level/Level.h" - -class LavaParticle: public Particle -{ - typedef Particle super; - float oSize; -public: - LavaParticle(Level* level, float x, float y, float z) - : super(level, x, y, z, 0, 0, 0) - { - xd *= 0.8f; - yd *= 0.8f; - zd *= 0.8f; - yd = sharedRandom.nextFloat() * 0.4f + 0.05f; - - rCol = gCol = bCol = 1; - size *= (sharedRandom.nextFloat() * 2 + 0.2f); - oSize = size; - - lifetime = (int) (16 / (Mth::random() * 0.8 + 0.2)); - noPhysics = false; - tex = 49; - } - - float getBrightness(float a) { - return 1; - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { - float s = (age + a) / (float) lifetime; - size = oSize * (1 - s*s); - super::render(t, a, xa, ya, za, xa2, za2); - } - - void tick() { - xo = x; - yo = y; - zo = z; - - if (age++ >= lifetime) remove(); - float odds = age / (float) lifetime; - if (sharedRandom.nextFloat() > odds) level->addParticle(PARTICLETYPE(smoke), x, y, z, xd, yd, zd); - - yd -= 0.03f; - move(xd, yd, zd); - xd *= 0.999f; - yd *= 0.999f; - zd *= 0.999f; - - if (onGround) { - xd *= 0.7f; - zd *= 0.7f; - } - } -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__LavaParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "../renderer/Tesselator.h" +#include "../../world/level/Level.h" + +class LavaParticle: public Particle +{ + typedef Particle super; + float oSize; +public: + LavaParticle(Level* level, float x, float y, float z) + : super(level, x, y, z, 0, 0, 0) + { + xd *= 0.8f; + yd *= 0.8f; + zd *= 0.8f; + yd = sharedRandom.nextFloat() * 0.4f + 0.05f; + + rCol = gCol = bCol = 1; + size *= (sharedRandom.nextFloat() * 2 + 0.2f); + oSize = size; + + lifetime = (int) (16 / (Mth::random() * 0.8 + 0.2)); + noPhysics = false; + tex = 49; + } + + float getBrightness(float a) { + return 1; + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { + float s = (age + a) / (float) lifetime; + size = oSize * (1 - s*s); + super::render(t, a, xa, ya, za, xa2, za2); + } + + void tick() { + xo = x; + yo = y; + zo = z; + + if (age++ >= lifetime) remove(); + float odds = age / (float) lifetime; + if (sharedRandom.nextFloat() > odds) level->addParticle(PARTICLETYPE(smoke), x, y, z, xd, yd, zd); + + yd -= 0.03f; + move(xd, yd, zd); + xd *= 0.999f; + yd *= 0.999f; + zd *= 0.999f; + + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } + } +}; + diff --git a/src/client/particle/Particle.h b/src/client/particle/Particle.h index dd96bb4..1c71339 100755 --- a/src/client/particle/Particle.h +++ b/src/client/particle/Particle.h @@ -1,46 +1,44 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__Particle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__Particle_H__ - -//package net.minecraft.client.particle; - -#include "../renderer/Tesselator.h" -#include "../../world/entity/Entity.h" -#include "../../world/level/Level.h" -#include "ParticleEngine.h" - -class CompoundTag; - -class Particle: public Entity { - typedef Entity super; - -public: - static float xOff, yOff, zOff; - - Particle(Level* level, float x, float y, float z, float xa, float ya, float za); - - virtual ~Particle() {} - - Particle* setPower(float power); - Particle* scale(float scale); - - virtual void tick(); - virtual void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2); - - virtual int getParticleTexture(); - - virtual void addAdditonalSaveData(CompoundTag* entityTag) {} - virtual void readAdditionalSaveData(CompoundTag* tag) {} - - virtual int getEntityTypeId() const { return 0; } - -protected: - int tex; - float uo, vo; - int age; - int lifetime; - float size; - float gravity; - float rCol, gCol, bCol; -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__Particle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "../renderer/Tesselator.h" +#include "../../world/entity/Entity.h" +#include "../../world/level/Level.h" +#include "ParticleEngine.h" + +class CompoundTag; + +class Particle: public Entity { + typedef Entity super; + +public: + static float xOff, yOff, zOff; + + Particle(Level* level, float x, float y, float z, float xa, float ya, float za); + + virtual ~Particle() {} + + Particle* setPower(float power); + Particle* scale(float scale); + + virtual void tick(); + virtual void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2); + + virtual int getParticleTexture(); + + virtual void addAdditonalSaveData(CompoundTag* entityTag) {} + virtual void readAdditionalSaveData(CompoundTag* tag) {} + + virtual int getEntityTypeId() const { return 0; } + +protected: + int tex; + float uo, vo; + int age; + int lifetime; + float size; + float gravity; + float rCol, gCol, bCol; +}; + diff --git a/src/client/particle/ParticleEngine.h b/src/client/particle/ParticleEngine.h index b75c248..afb5c03 100755 --- a/src/client/particle/ParticleEngine.h +++ b/src/client/particle/ParticleEngine.h @@ -1,54 +1,52 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__ParticleEngine_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__ParticleEngine_H__ - -//package net.minecraft.client.particle; - -#include -#include "../../world/entity/Entity.h" -#include "../../world/level/tile/Tile.h" -#include "../renderer/gles.h" - -class Textures; -class Level; -class Particle; -typedef std::vector ParticleList; - -class ParticleEngine -{ -public: - static const int MISC_TEXTURE = 0; - static const int TERRAIN_TEXTURE = 1; - static const int ITEM_TEXTURE = 2; - static const int ENTITY_PARTICLE_TEXTURE = 3; - - static const int TEXTURE_COUNT = 4; - - ParticleEngine(Level* level, Textures* textures); - ~ParticleEngine(); - - void add(Particle* p); - void destroy(int x, int y, int z); - - void tick(); - void render(Entity* player, float a); - void renderLit(Entity* player, float a); - - void setLevel(Level* level); - - void crack(int x, int y, int z, int face); - - std::string countParticles(); - -protected: - void clear(); - - Level* level; - GLuint textureIds[4]; - -private: - ParticleList particles[4]; - Textures* textures; - Random random; -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__ParticleEngine_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include +#include "../../world/entity/Entity.h" +#include "../../world/level/tile/Tile.h" +#include "../renderer/gles.h" + +class Textures; +class Level; +class Particle; +typedef std::vector ParticleList; + +class ParticleEngine +{ +public: + static const int MISC_TEXTURE = 0; + static const int TERRAIN_TEXTURE = 1; + static const int ITEM_TEXTURE = 2; + static const int ENTITY_PARTICLE_TEXTURE = 3; + + static const int TEXTURE_COUNT = 4; + + ParticleEngine(Level* level, Textures* textures); + ~ParticleEngine(); + + void add(Particle* p); + void destroy(int x, int y, int z); + + void tick(); + void render(Entity* player, float a); + void renderLit(Entity* player, float a); + + void setLevel(Level* level); + + void crack(int x, int y, int z, int face); + + std::string countParticles(); + +protected: + void clear(); + + Level* level; + GLuint textureIds[4]; + +private: + ParticleList particles[4]; + Textures* textures; + Random random; +}; + diff --git a/src/client/particle/ParticleInclude.h b/src/client/particle/ParticleInclude.h index dadcd4b..61702be 100755 --- a/src/client/particle/ParticleInclude.h +++ b/src/client/particle/ParticleInclude.h @@ -1,17 +1,15 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__ParticleInclude_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__ParticleInclude_H__ - -#include "Particle.h" - -#include "BubbleParticle.h" -#include "CritParticle2.h" -#include "ExplodeParticle.h" -#include "FlameParticle.h" -#include "LavaParticle.h" -#include "RedDustParticle.h" -#include "SmokeParticle.h" -#include "TerrainParticle.h" -#include "HugeExplosionSeedParticle.h" -#include "HugeExplosionParticle.h" - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__ParticleInclude_H__*/ +#pragma once + +#include "Particle.h" + +#include "BubbleParticle.h" +#include "CritParticle2.h" +#include "ExplodeParticle.h" +#include "FlameParticle.h" +#include "LavaParticle.h" +#include "RedDustParticle.h" +#include "SmokeParticle.h" +#include "TerrainParticle.h" +#include "HugeExplosionSeedParticle.h" +#include "HugeExplosionParticle.h" + diff --git a/src/client/particle/RedDustParticle.h b/src/client/particle/RedDustParticle.h index 67a6faf..9c4278c 100755 --- a/src/client/particle/RedDustParticle.h +++ b/src/client/particle/RedDustParticle.h @@ -1,73 +1,71 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__RedDustParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__RedDustParticle_H__ - -//package net.minecraft.client.particle; - -#include "../renderer/Tesselator.h" -#include "../../world/level/Level.h" - - -class RedDustParticle: public Particle -{ - typedef Particle super; -public: - float oSize; - - RedDustParticle(Level* level, float x, float y, float z, float rCol, float gCol, float bCol, float scale = 1.0f) - : super(level, x, y, z, 0, 0, 0) - { - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - - if (rCol == 0) { - rCol = 1; - } - float brr = (float) Mth::random() * 0.4f + 0.6f; - this->rCol = ((float) (Mth::random() * 0.2f) + 0.8f) * rCol * brr; - this->gCol = ((float) (Mth::random() * 0.2f) + 0.8f) * gCol * brr; - this->bCol = ((float) (Mth::random() * 0.2f) + 0.8f) * bCol * brr; - size *= 0.75f; - size *= scale; - oSize = size; - - lifetime = (int) (8 / (Mth::random() * 0.8 + 0.2)); - lifetime = (int)(lifetime * scale); - noPhysics = false; - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { - float l = ((age + a) / lifetime) * 32; - if (l < 0) l = 0; - if (l > 1) l = 1; - - size = oSize * l; - super::render(t, a, xa, ya, za, xa2, za2); - } - - void tick() { - xo = x; - yo = y; - zo = z; - - if (age++ >= lifetime) remove(); - - tex = 7 - age * 8 / lifetime; - - move(xd, yd, zd); - if (y == yo) { - xd *= 1.1f; - zd *= 1.1f; - } - xd *= 0.96f; - yd *= 0.96f; - zd *= 0.96f; - - if (onGround) { - xd *= 0.7f; - zd *= 0.7f; - } - } -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__RedDustParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "../renderer/Tesselator.h" +#include "../../world/level/Level.h" + + +class RedDustParticle: public Particle +{ + typedef Particle super; +public: + float oSize; + + RedDustParticle(Level* level, float x, float y, float z, float rCol, float gCol, float bCol, float scale = 1.0f) + : super(level, x, y, z, 0, 0, 0) + { + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + + if (rCol == 0) { + rCol = 1; + } + float brr = (float) Mth::random() * 0.4f + 0.6f; + this->rCol = ((float) (Mth::random() * 0.2f) + 0.8f) * rCol * brr; + this->gCol = ((float) (Mth::random() * 0.2f) + 0.8f) * gCol * brr; + this->bCol = ((float) (Mth::random() * 0.2f) + 0.8f) * bCol * brr; + size *= 0.75f; + size *= scale; + oSize = size; + + lifetime = (int) (8 / (Mth::random() * 0.8 + 0.2)); + lifetime = (int)(lifetime * scale); + noPhysics = false; + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { + float l = ((age + a) / lifetime) * 32; + if (l < 0) l = 0; + if (l > 1) l = 1; + + size = oSize * l; + super::render(t, a, xa, ya, za, xa2, za2); + } + + void tick() { + xo = x; + yo = y; + zo = z; + + if (age++ >= lifetime) remove(); + + tex = 7 - age * 8 / lifetime; + + move(xd, yd, zd); + if (y == yo) { + xd *= 1.1f; + zd *= 1.1f; + } + xd *= 0.96f; + yd *= 0.96f; + zd *= 0.96f; + + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } + } +}; + diff --git a/src/client/particle/SmokeParticle.h b/src/client/particle/SmokeParticle.h index 7e92f18..5f1ccc6 100755 --- a/src/client/particle/SmokeParticle.h +++ b/src/client/particle/SmokeParticle.h @@ -1,69 +1,67 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__SmokeParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__SmokeParticle_H__ - -//package net.minecraft.client.particle; - -#include "Particle.h" - -class SmokeParticle: public Particle -{ - typedef Particle super; - -public: - float oSize; - - SmokeParticle(Level* level, float x, float y, float z, float xa, float ya, float za, float scale = 1.0f) - : super(level, x, y, z, 0, 0, 0) - { - xd *= 0.1f; - yd *= 0.1f; - zd *= 0.1f; - xd += xa; - yd += ya; - zd += za; - - rCol = gCol = bCol = (float) (Mth::random() * 0.5f); - size *= 0.75f; - size *= scale; - oSize = size; - - lifetime = (int) (scale * 8.0f / (Mth::random() * 0.8f + 0.2f)); - noPhysics = false; - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { - float l = ((age + a) / lifetime) * 32; - if (l < 0) l = 0; - if (l > 1) l = 1; - - size = oSize * l; - super::render(t, a, xa, ya, za, xa2, za2); - } - - void tick() { - xo = x; - yo = y; - zo = z; - - if (age++ >= lifetime) remove(); - - tex = 7 - age * 8 / lifetime; - - yd += 0.004f; - move(xd, yd, zd); - if (y == yo) { - xd *= 1.1f; - zd *= 1.1f; - } - xd *= 0.96f; - yd *= 0.96f; - zd *= 0.96f; - - if (onGround) { - xd *= 0.7f; - zd *= 0.7f; - } - } -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__SmokeParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "Particle.h" + +class SmokeParticle: public Particle +{ + typedef Particle super; + +public: + float oSize; + + SmokeParticle(Level* level, float x, float y, float z, float xa, float ya, float za, float scale = 1.0f) + : super(level, x, y, z, 0, 0, 0) + { + xd *= 0.1f; + yd *= 0.1f; + zd *= 0.1f; + xd += xa; + yd += ya; + zd += za; + + rCol = gCol = bCol = (float) (Mth::random() * 0.5f); + size *= 0.75f; + size *= scale; + oSize = size; + + lifetime = (int) (scale * 8.0f / (Mth::random() * 0.8f + 0.2f)); + noPhysics = false; + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { + float l = ((age + a) / lifetime) * 32; + if (l < 0) l = 0; + if (l > 1) l = 1; + + size = oSize * l; + super::render(t, a, xa, ya, za, xa2, za2); + } + + void tick() { + xo = x; + yo = y; + zo = z; + + if (age++ >= lifetime) remove(); + + tex = 7 - age * 8 / lifetime; + + yd += 0.004f; + move(xd, yd, zd); + if (y == yo) { + xd *= 1.1f; + zd *= 1.1f; + } + xd *= 0.96f; + yd *= 0.96f; + zd *= 0.96f; + + if (onGround) { + xd *= 0.7f; + zd *= 0.7f; + } + } +}; + diff --git a/src/client/particle/SplashParticle.h b/src/client/particle/SplashParticle.h index b895de1..2a9444c 100755 --- a/src/client/particle/SplashParticle.h +++ b/src/client/particle/SplashParticle.h @@ -1,26 +1,24 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__SplashParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__SplashParticle_H__ - -//package net.minecraft.client.particle; - -#include "WaterDropParticle.h" -#include "../../world/level/Level.h" - -class SplashParticle: public WaterDropParticle -{ - typedef WaterDropParticle super; -public: - SplashParticle(Level* level, float x, float y, float z, float xa, float ya, float za) - : super(level, x, y, z) - { - gravity = 0.04f; - tex += 1; - if (ya == 0 && (xa != 0 || za != 0)) { - xd = xa; - yd = ya + 0.1; - zd = za; - } - } -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__SplashParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "WaterDropParticle.h" +#include "../../world/level/Level.h" + +class SplashParticle: public WaterDropParticle +{ + typedef WaterDropParticle super; +public: + SplashParticle(Level* level, float x, float y, float z, float xa, float ya, float za) + : super(level, x, y, z) + { + gravity = 0.04f; + tex += 1; + if (ya == 0 && (xa != 0 || za != 0)) { + xd = xa; + yd = ya + 0.1; + zd = za; + } + } +}; + diff --git a/src/client/particle/TakeAnimationParticle.h b/src/client/particle/TakeAnimationParticle.h index 78bad7f..62fa70e 100755 --- a/src/client/particle/TakeAnimationParticle.h +++ b/src/client/particle/TakeAnimationParticle.h @@ -1,82 +1,80 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__TakeAnimationParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__TakeAnimationParticle_H__ - -//package net.minecraft.client.particle; - -#include "Particle.h" - -#include "../renderer/entity/EntityRenderDispatcher.h" -#include "../renderer/Tesselator.h" -#include "../../world/entity/Entity.h" -#include "../../world/level/Level.h" -#include "../../util/Mth.h" -#include "../../world/entity/item/ItemEntity.h" - -class TakeAnimationParticle: public Particle -{ - typedef Particle super; - -public: - //@todo:itementity - TakeAnimationParticle(Level* level, ItemEntity* item, Entity* target, float yOffs) - : super(level, item->x, item->y, item->z, item->xd, item->yd, item->zd), - e(level, item->x, item->y, item->z, item->item), - //bx(item->x), by(item->y), bz(item->z), - target(target), - yOffs(yOffs), - life(0), - lifeTime(3) - { - e.item.count = 1; - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { - float time = (life + a) / lifeTime; - time = time*time; - - float xo = e.x; - float yo = e.y; - float zo = e.z; - - float xt = target->xOld + (target->x - target->xOld) * a; - float yt = target->yOld + (target->y - target->yOld) * a+yOffs; - float zt = target->zOld + (target->z - target->zOld) * a; - - float xx = xo + (xt - xo) * time; - float yy = yo + (yt - yo) * time; - float zz = zo + (zt - zo) * time; - - int xTile = Mth::floor(xx); - int yTile = Mth::floor(yy + heightOffset * 0.5f); - int zTile = Mth::floor(zz); - - float br = level->getBrightness(xTile, yTile, zTile); - glColor4f2(br, br, br, 1); - - xx -= xOff; - yy -= yOff; - zz -= zOff; - - EntityRenderDispatcher::getInstance()->render(&e, xx, yy, zz, e.yRot, a); - } - - void tick() { - life++; - if (life == lifeTime) remove(); - } - - int getParticleTexture() { - return ParticleEngine::ENTITY_PARTICLE_TEXTURE; - } - -private: - //Entity* item; - ItemEntity e; - Entity* target; - //float bx, by, bz; - int life; - int lifeTime; - float yOffs; -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__TakeAnimationParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "Particle.h" + +#include "../renderer/entity/EntityRenderDispatcher.h" +#include "../renderer/Tesselator.h" +#include "../../world/entity/Entity.h" +#include "../../world/level/Level.h" +#include "../../util/Mth.h" +#include "../../world/entity/item/ItemEntity.h" + +class TakeAnimationParticle: public Particle +{ + typedef Particle super; + +public: + //@todo:itementity + TakeAnimationParticle(Level* level, ItemEntity* item, Entity* target, float yOffs) + : super(level, item->x, item->y, item->z, item->xd, item->yd, item->zd), + e(level, item->x, item->y, item->z, item->item), + //bx(item->x), by(item->y), bz(item->z), + target(target), + yOffs(yOffs), + life(0), + lifeTime(3) + { + e.item.count = 1; + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { + float time = (life + a) / lifeTime; + time = time*time; + + float xo = e.x; + float yo = e.y; + float zo = e.z; + + float xt = target->xOld + (target->x - target->xOld) * a; + float yt = target->yOld + (target->y - target->yOld) * a+yOffs; + float zt = target->zOld + (target->z - target->zOld) * a; + + float xx = xo + (xt - xo) * time; + float yy = yo + (yt - yo) * time; + float zz = zo + (zt - zo) * time; + + int xTile = Mth::floor(xx); + int yTile = Mth::floor(yy + heightOffset * 0.5f); + int zTile = Mth::floor(zz); + + float br = level->getBrightness(xTile, yTile, zTile); + glColor4f2(br, br, br, 1); + + xx -= xOff; + yy -= yOff; + zz -= zOff; + + EntityRenderDispatcher::getInstance()->render(&e, xx, yy, zz, e.yRot, a); + } + + void tick() { + life++; + if (life == lifeTime) remove(); + } + + int getParticleTexture() { + return ParticleEngine::ENTITY_PARTICLE_TEXTURE; + } + +private: + //Entity* item; + ItemEntity e; + Entity* target; + //float bx, by, bz; + int life; + int lifeTime; + float yOffs; +}; + diff --git a/src/client/particle/TerrainParticle.h b/src/client/particle/TerrainParticle.h index 663d87b..98da959 100755 --- a/src/client/particle/TerrainParticle.h +++ b/src/client/particle/TerrainParticle.h @@ -1,63 +1,61 @@ -#ifndef NET_MINECRAFT_CLIENT_PARTICLE__TerrainParticle_H__ -#define NET_MINECRAFT_CLIENT_PARTICLE__TerrainParticle_H__ - -//package net.minecraft.client.particle; - -#include "../renderer/Tesselator.h" -#include "../../world/level/Level.h" -#include "../../world/level/tile/Tile.h" -#include "../../world/level/tile/GrassTile.h" - -class TerrainParticle: public Particle -{ - typedef Particle super; - -public: - TerrainParticle(Level* level, float x, float y, float z, float xa, float ya, float za, Tile* tile, int data) - : super(level, x, y, z, xa, ya, za), - tile(tile) - { - tex = tile->getTexture(2, data); - gravity = tile->gravity; - rCol = gCol = bCol = 0.6f; - size /= 2; - //noPhysics = true; - } - - TerrainParticle* init(int x, int y, int z) { - if (tile == Tile::grass) return this; - int col = tile->getColor(level, x, y, z); - rCol *= ((col >> 16) & 0xff) / 255.0f; - gCol *= ((col >> 8) & 0xff) / 255.0f; - bCol *= ((col) & 0xff) / 255.0f; - return this; - } - - int getParticleTexture() { - return ParticleEngine::TERRAIN_TEXTURE; - } - - void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { - float u0 = ((tex & 15) + uo / 4.0f) / 16.0f; - float u1 = u0 + 0.999f / 16.0f / 4; - float v0 = ((tex >> 4) + vo / 4.0f) / 16.0f; - float v1 = v0 + 0.999f / 16.0f / 4; - float r = 0.1f * size; - - float x = (float) (xo + (this->x - xo) * a - xOff); - float y = (float) (yo + (this->y - yo) * a - yOff); - float z = (float) (zo + (this->z - zo) * a - zOff); - float br = getBrightness(a); - t.color(br * rCol, br * gCol, br * bCol); - - t.vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u0, v1); - t.vertexUV(x - xa * r + xa2 * r, y + ya * r, z - za * r + za2 * r, u0, v0); - t.vertexUV(x + xa * r + xa2 * r, y + ya * r, z + za * r + za2 * r, u1, v0); - t.vertexUV(x + xa * r - xa2 * r, y - ya * r, z + za * r - za2 * r, u1, v1); - } - -private: - Tile* tile; -}; - -#endif /*NET_MINECRAFT_CLIENT_PARTICLE__TerrainParticle_H__*/ +#pragma once + +//package net.minecraft.client.particle; + +#include "../renderer/Tesselator.h" +#include "../../world/level/Level.h" +#include "../../world/level/tile/Tile.h" +#include "../../world/level/tile/GrassTile.h" + +class TerrainParticle: public Particle +{ + typedef Particle super; + +public: + TerrainParticle(Level* level, float x, float y, float z, float xa, float ya, float za, Tile* tile, int data) + : super(level, x, y, z, xa, ya, za), + tile(tile) + { + tex = tile->getTexture(2, data); + gravity = tile->gravity; + rCol = gCol = bCol = 0.6f; + size /= 2; + //noPhysics = true; + } + + TerrainParticle* init(int x, int y, int z) { + if (tile == Tile::grass) return this; + int col = tile->getColor(level, x, y, z); + rCol *= ((col >> 16) & 0xff) / 255.0f; + gCol *= ((col >> 8) & 0xff) / 255.0f; + bCol *= ((col) & 0xff) / 255.0f; + return this; + } + + int getParticleTexture() { + return ParticleEngine::TERRAIN_TEXTURE; + } + + void render(Tesselator& t, float a, float xa, float ya, float za, float xa2, float za2) { + float u0 = ((tex & 15) + uo / 4.0f) / 16.0f; + float u1 = u0 + 0.999f / 16.0f / 4; + float v0 = ((tex >> 4) + vo / 4.0f) / 16.0f; + float v1 = v0 + 0.999f / 16.0f / 4; + float r = 0.1f * size; + + float x = (float) (xo + (this->x - xo) * a - xOff); + float y = (float) (yo + (this->y - yo) * a - yOff); + float z = (float) (zo + (this->z - zo) * a - zOff); + float br = getBrightness(a); + t.color(br * rCol, br * gCol, br * bCol); + + t.vertexUV(x - xa * r - xa2 * r, y - ya * r, z - za * r - za2 * r, u0, v1); + t.vertexUV(x - xa * r + xa2 * r, y + ya * r, z - za * r + za2 * r, u0, v0); + t.vertexUV(x + xa * r + xa2 * r, y + ya * r, z + za * r + za2 * r, u1, v0); + t.vertexUV(x + xa * r - xa2 * r, y - ya * r, z + za * r - za2 * r, u1, v1); + } + +private: + Tile* tile; +}; + diff --git a/src/client/player/LocalPlayer.h b/src/client/player/LocalPlayer.h index f0de0d0..aba7053 100755 --- a/src/client/player/LocalPlayer.h +++ b/src/client/player/LocalPlayer.h @@ -1,110 +1,108 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER__LocalPlayer_H__ -#define NET_MINECRAFT_CLIENT_PLAYER__LocalPlayer_H__ - -//package net.minecraft.client.player; - -#include "input/IMoveInput.h" -#include "../../util/SmoothFloat.h" -#include "../../world/entity/player/Player.h" - -class MinecraftClient; -class Stat; -class CompoundTag; - -class LocalPlayer: public Player -{ - typedef Player super; -public: - LocalPlayer(MinecraftClient& minecraft, Level* level, const std::string& username, int dimension, bool isCreative); - ~LocalPlayer(); - - void _init(); - virtual void reset(); - - void tick(); - void move(float xa, float ya, float za); - - void aiStep(); - void updateAi(); - - void setKey(int eventKey, bool eventKeyState); - void releaseAllKeys(); - - void addAdditonalSaveData(CompoundTag* entityTag); - void readAdditionalSaveData(CompoundTag* entityTag); - - void closeContainer(); - - void drop(ItemInstance* item, bool randomly); - void take(Entity* e, int orgCount); - - void startCrafting(int x, int y, int z, int tableSize); - void startStonecutting(int x, int y, int z); - - void openContainer(ChestTileEntity* container); - void openFurnace(FurnaceTileEntity* e); - - bool isSneaking(); - - void actuallyHurt(int dmg); - void hurtTo(int newHealth); - void die(Entity* source); - - void respawn(); - - void animateRespawn() {} - float getFieldOfViewModifier(); - void chat(const std::string& message) {} - void displayClientMessage(const std::string& messageId); - - void awardStat(Stat* stat, int count) { - //minecraft->stats.award(stat, count); - //minecraft->achievementPopup.popup("Achievement get!", stat.name); - } - void causeFallDamage( float distance ); - - virtual int startSleepInBed(int x, int y, int z); - virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint); - - void swing(); - virtual void openTextEdit( TileEntity* tileEntity ); - virtual float getWalkingSpeedModifier(); -private: - void calculateFlight(float xa, float ya, float za); - bool isSolidTile(int x, int y, int z); - void updateArmorTypeHash(); -public: - IMoveInput* input = nullptr; - bool autoJumpEnabled = true; -protected: - MinecraftClient& minecraft; - int jumpTriggerTime; - int ascendTriggerTime; - int descendTriggerTime; - bool ascending, descending; -private: - // local player fly - // ----------------------- - float flyX, flyY, flyZ; - - // smooth camera settings - SmoothFloat smoothFlyX; - SmoothFloat smoothFlyY; - SmoothFloat smoothFlyZ; - - int autoJumpTime; - - int sentInventoryItemId = -1; - int sentInventoryItemData = -1; - - int armorTypeHash = 0; - - // sprinting - bool sprinting = false; - int sprintDoubleTapTimer = 0; - bool prevForwardHeld = false; -public: - void setSprinting(bool sprint) { sprinting = sprint; } -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER__LocalPlayer_H__*/ +#pragma once + +//package net.minecraft.client.player; + +#include "input/IMoveInput.h" +#include "../../util/SmoothFloat.h" +#include "../../world/entity/player/Player.h" + +class MinecraftClient; +class Stat; +class CompoundTag; + +class LocalPlayer: public Player +{ + typedef Player super; +public: + LocalPlayer(MinecraftClient& minecraft, Level* level, const std::string& username, int dimension, bool isCreative); + ~LocalPlayer(); + + void _init(); + virtual void reset(); + + void tick(); + void move(float xa, float ya, float za); + + void aiStep(); + void updateAi(); + + void setKey(int eventKey, bool eventKeyState); + void releaseAllKeys(); + + void addAdditonalSaveData(CompoundTag* entityTag); + void readAdditionalSaveData(CompoundTag* entityTag); + + void closeContainer(); + + void drop(ItemInstance* item, bool randomly); + void take(Entity* e, int orgCount); + + void startCrafting(int x, int y, int z, int tableSize); + void startStonecutting(int x, int y, int z); + + void openContainer(ChestTileEntity* container); + void openFurnace(FurnaceTileEntity* e); + + bool isSneaking(); + + void actuallyHurt(int dmg); + void hurtTo(int newHealth); + void die(Entity* source); + + void respawn(); + + void animateRespawn() {} + float getFieldOfViewModifier(); + void chat(const std::string& message) {} + void displayClientMessage(const std::string& messageId); + + void awardStat(Stat* stat, int count) { + //minecraft->stats.award(stat, count); + //minecraft->achievementPopup.popup("Achievement get!", stat.name); + } + void causeFallDamage( float distance ); + + virtual int startSleepInBed(int x, int y, int z); + virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint); + + void swing(); + virtual void openTextEdit( TileEntity* tileEntity ); + virtual float getWalkingSpeedModifier(); +private: + void calculateFlight(float xa, float ya, float za); + bool isSolidTile(int x, int y, int z); + void updateArmorTypeHash(); +public: + IMoveInput* input = nullptr; + bool autoJumpEnabled = true; +protected: + MinecraftClient& minecraft; + int jumpTriggerTime; + int ascendTriggerTime; + int descendTriggerTime; + bool ascending, descending; +private: + // local player fly + // ----------------------- + float flyX, flyY, flyZ; + + // smooth camera settings + SmoothFloat smoothFlyX; + SmoothFloat smoothFlyY; + SmoothFloat smoothFlyZ; + + int autoJumpTime; + + int sentInventoryItemId = -1; + int sentInventoryItemData = -1; + + int armorTypeHash = 0; + + // sprinting + bool sprinting = false; + int sprintDoubleTapTimer = 0; + bool prevForwardHeld = false; +public: + void setSprinting(bool sprint) { sprinting = sprint; } +}; + diff --git a/src/client/player/RemotePlayer.h b/src/client/player/RemotePlayer.h index 6cdba9a..37bf407 100755 --- a/src/client/player/RemotePlayer.h +++ b/src/client/player/RemotePlayer.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER__RemotePlayer_H__ -#define NET_MINECRAFT_CLIENT_PLAYER__RemotePlayer_H__ - -//package net.minecraft.client.player; - -#include "../../world/entity/player/Player.h" - -class Level; - -class RemotePlayer: public Player -{ - typedef Player super; -public: - RemotePlayer(Level* level, bool isCreative); - void aiStep(); - void tick(); -private: - bool hasStartedUsingItem; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER__RemotePlayer_H__*/ +#pragma once + +//package net.minecraft.client.player; + +#include "../../world/entity/player/Player.h" + +class Level; + +class RemotePlayer: public Player +{ + typedef Player super; +public: + RemotePlayer(Level* level, bool isCreative); + void aiStep(); + void tick(); +private: + bool hasStartedUsingItem; +}; + diff --git a/src/client/player/input/ControllerTurnInput.h b/src/client/player/input/ControllerTurnInput.h index d34a42f..fc6694c 100755 --- a/src/client/player/input/ControllerTurnInput.h +++ b/src/client/player/input/ControllerTurnInput.h @@ -1,69 +1,67 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER_INPUT_ControllerTurnInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER_INPUT_ControllerTurnInput_H__ - -#include "ITurnInput.h" -#include "../../../platform/input/Controller.h" - -/** A Controller Turn input */ -class ControllerTurnInput : public ITurnInput { -public: - static const int MODE_OFFSET = 1; - static const int MODE_DELTA = 2; - - ControllerTurnInput(int controllerId, int mode_) - : cid(controllerId), - mode(mode_), - cxO(0), cyO(0), - wasActive(false) - {} - - bool isTouched() { return Controller::isTouched(cid); } - - TurnDelta getTurnDelta() { - float dx = 0, dy = 0; - bool isActive = Controller::isTouched(cid); - - if (MODE_OFFSET == mode) { - float dt = getDeltaTime(); - const float MaxTurnX = 250.0f; - const float MaxTurnY = 200.0f; - float cx = isActive? Controller::getX(cid) : cxO * 0.7f; - float cy = isActive? Controller::getY(cid) : cyO * 0.7f; - dx = linearTransform( cx, 0.1f, MaxTurnX ) * dt; - dy = linearTransform( cy, 0.1f, MaxTurnY ) * dt; - cxO = cx; - cyO = cy; - } else - if (MODE_DELTA == mode && (wasActive || isActive)) { - float cx = Controller::getX(cid); - float cy = Controller::getY(cid); - -// const float dt = getDeltaTime(); - const float MaxTurnX = 100.0f; - const float MaxTurnY = 100.0f; - const float DeadZone = 0;//0.25f * dt;//0.02f; - - if (!wasActive) { - cxO = cx; - cyO = cy; - } - if (isActive) { - dx = linearTransform(cx - cxO, DeadZone) * MaxTurnX; - dy = linearTransform(cy - cyO, DeadZone) * MaxTurnY; - cxO = cx; - cyO = cy; - } - } - - wasActive = isActive; - return TurnDelta(dx, -dy); - } - - int mode; -private: - int cid; - float cxO, cyO; - bool wasActive; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER_INPUT_ControllerTurnInput_H__*/ +#pragma once + +#include "ITurnInput.h" +#include "../../../platform/input/Controller.h" + +/** A Controller Turn input */ +class ControllerTurnInput : public ITurnInput { +public: + static const int MODE_OFFSET = 1; + static const int MODE_DELTA = 2; + + ControllerTurnInput(int controllerId, int mode_) + : cid(controllerId), + mode(mode_), + cxO(0), cyO(0), + wasActive(false) + {} + + bool isTouched() { return Controller::isTouched(cid); } + + TurnDelta getTurnDelta() { + float dx = 0, dy = 0; + bool isActive = Controller::isTouched(cid); + + if (MODE_OFFSET == mode) { + float dt = getDeltaTime(); + const float MaxTurnX = 250.0f; + const float MaxTurnY = 200.0f; + float cx = isActive? Controller::getX(cid) : cxO * 0.7f; + float cy = isActive? Controller::getY(cid) : cyO * 0.7f; + dx = linearTransform( cx, 0.1f, MaxTurnX ) * dt; + dy = linearTransform( cy, 0.1f, MaxTurnY ) * dt; + cxO = cx; + cyO = cy; + } else + if (MODE_DELTA == mode && (wasActive || isActive)) { + float cx = Controller::getX(cid); + float cy = Controller::getY(cid); + +// const float dt = getDeltaTime(); + const float MaxTurnX = 100.0f; + const float MaxTurnY = 100.0f; + const float DeadZone = 0;//0.25f * dt;//0.02f; + + if (!wasActive) { + cxO = cx; + cyO = cy; + } + if (isActive) { + dx = linearTransform(cx - cxO, DeadZone) * MaxTurnX; + dy = linearTransform(cy - cyO, DeadZone) * MaxTurnY; + cxO = cx; + cyO = cy; + } + } + + wasActive = isActive; + return TurnDelta(dx, -dy); + } + + int mode; +private: + int cid; + float cxO, cyO; + bool wasActive; +}; + diff --git a/src/client/player/input/IBuildInput.h b/src/client/player/input/IBuildInput.h index 488e172..c228c71 100755 --- a/src/client/player/input/IBuildInput.h +++ b/src/client/player/input/IBuildInput.h @@ -1,45 +1,43 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER_INPUT__IBuildInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER_INPUT__IBuildInput_H__ - -#include "../../IConfigListener.h" -class Player; - -class BuildActionIntention { -public: - BuildActionIntention() - : action(0) - {} - BuildActionIntention(int action) - : action(action) - {} - - bool isFirstRemove() { return (action & BAI_FIRSTREMOVE) != 0; } - bool isRemoveContinue() { return (action & BAI_REMOVE) != 0; } - - bool isBuild() { return (action & BAI_BUILD) != 0; } - bool isRemove() { return isFirstRemove() || isRemoveContinue(); } - - bool isAttack() { return (action & BAI_ATTACK) != 0; } - bool isInteract() { return (action & BAI_INTERACT) != 0; } - - int action; - - static const int BAI_BUILD = 1; - static const int BAI_REMOVE = 2; - static const int BAI_FIRSTREMOVE = 4; - - static const int BAI_ATTACK = 8; - static const int BAI_INTERACT = 16; -}; - - -class IBuildInput: public IConfigListener { -public: - virtual ~IBuildInput(){} - - virtual void onConfigChanged(const Config& c) {} - // @return true if user wants to do an action, false if not - virtual bool tickBuild(Player*, BuildActionIntention* bai) { return false; } -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER_INPUT__IBuildInput_H__*/ +#pragma once + +#include "../../IConfigListener.h" +class Player; + +class BuildActionIntention { +public: + BuildActionIntention() + : action(0) + {} + BuildActionIntention(int action) + : action(action) + {} + + bool isFirstRemove() { return (action & BAI_FIRSTREMOVE) != 0; } + bool isRemoveContinue() { return (action & BAI_REMOVE) != 0; } + + bool isBuild() { return (action & BAI_BUILD) != 0; } + bool isRemove() { return isFirstRemove() || isRemoveContinue(); } + + bool isAttack() { return (action & BAI_ATTACK) != 0; } + bool isInteract() { return (action & BAI_INTERACT) != 0; } + + int action; + + static const int BAI_BUILD = 1; + static const int BAI_REMOVE = 2; + static const int BAI_FIRSTREMOVE = 4; + + static const int BAI_ATTACK = 8; + static const int BAI_INTERACT = 16; +}; + + +class IBuildInput: public IConfigListener { +public: + virtual ~IBuildInput(){} + + virtual void onConfigChanged(const Config& c) {} + // @return true if user wants to do an action, false if not + virtual bool tickBuild(Player*, BuildActionIntention* bai) { return false; } +}; + diff --git a/src/client/player/input/IInputHolder.h b/src/client/player/input/IInputHolder.h index 4f531c6..9ae7d4c 100755 --- a/src/client/player/input/IInputHolder.h +++ b/src/client/player/input/IInputHolder.h @@ -1,75 +1,73 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER__IInputHolder_H__ -#define NET_MINECRAFT_CLIENT_PLAYER__IInputHolder_H__ - -#include "IMoveInput.h" -#include "ITurnInput.h" -#include "IBuildInput.h" - -#include "../../../platform/input/Mouse.h" - -class Player; - -class IInputHolder: public IConfigListener -{ -public: - IInputHolder() - : mousex(0), - mousey(0), - alpha(0) - {} - - virtual ~IInputHolder() {} - - virtual void render(float alpha) {} - - virtual bool allowPicking() { - mousex = Mouse::getX(); - mousey = Mouse::getY(); - return Mouse::getButtonState(MouseAction::ACTION_LEFT) == MouseAction::DATA_DOWN; - } - - void onConfigChanged(const Config& c) { - getMoveInput()->onConfigChanged(c); - getTurnInput()->onConfigChanged(c); - getBuildInput()->onConfigChanged(c); - } - - virtual IMoveInput* getMoveInput() = 0; - virtual ITurnInput* getTurnInput() = 0; - virtual IBuildInput* getBuildInput() = 0; - - float mousex, mousey; - float alpha; -}; - - -class CustomInputHolder: public IInputHolder -{ -public: - CustomInputHolder(IMoveInput* move, ITurnInput* turn, IBuildInput* build) - { - setInputs(move, turn, build); - } - - ~CustomInputHolder() { - delete _move; - delete _turn; - delete _build; - } - void setInputs(IMoveInput* move, ITurnInput* turn, IBuildInput* build) { - _move = move; - _turn = turn; - _build = build; - } - - virtual IMoveInput* getMoveInput() { return _move; } - virtual ITurnInput* getTurnInput() { return _turn; } - virtual IBuildInput* getBuildInput() { return _build; } - -private: - IMoveInput* _move; - ITurnInput* _turn; - IBuildInput* _build; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER__IInputHolder_H__*/ +#pragma once + +#include "IMoveInput.h" +#include "ITurnInput.h" +#include "IBuildInput.h" + +#include "../../../platform/input/Mouse.h" + +class Player; + +class IInputHolder: public IConfigListener +{ +public: + IInputHolder() + : mousex(0), + mousey(0), + alpha(0) + {} + + virtual ~IInputHolder() {} + + virtual void render(float alpha) {} + + virtual bool allowPicking() { + mousex = Mouse::getX(); + mousey = Mouse::getY(); + return Mouse::getButtonState(MouseAction::ACTION_LEFT) == MouseAction::DATA_DOWN; + } + + void onConfigChanged(const Config& c) { + getMoveInput()->onConfigChanged(c); + getTurnInput()->onConfigChanged(c); + getBuildInput()->onConfigChanged(c); + } + + virtual IMoveInput* getMoveInput() = 0; + virtual ITurnInput* getTurnInput() = 0; + virtual IBuildInput* getBuildInput() = 0; + + float mousex, mousey; + float alpha; +}; + + +class CustomInputHolder: public IInputHolder +{ +public: + CustomInputHolder(IMoveInput* move, ITurnInput* turn, IBuildInput* build) + { + setInputs(move, turn, build); + } + + ~CustomInputHolder() { + delete _move; + delete _turn; + delete _build; + } + void setInputs(IMoveInput* move, ITurnInput* turn, IBuildInput* build) { + _move = move; + _turn = turn; + _build = build; + } + + virtual IMoveInput* getMoveInput() { return _move; } + virtual ITurnInput* getTurnInput() { return _turn; } + virtual IBuildInput* getBuildInput() { return _build; } + +private: + IMoveInput* _move; + ITurnInput* _turn; + IBuildInput* _build; +}; + diff --git a/src/client/player/input/IMoveInput.h b/src/client/player/input/IMoveInput.h index e61bac1..359a65b 100755 --- a/src/client/player/input/IMoveInput.h +++ b/src/client/player/input/IMoveInput.h @@ -1,47 +1,45 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER__IMoveInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER__IMoveInput_H__ - -//package net.minecraft.client.player; - -#include "../../IConfigListener.h" -class Player; -class Minecraft; - -class IMoveInput -{ -protected: - IMoveInput() - : xa(0), - ya(0), - wasJumping(false), - jumping(false), - sneaking(false), - wantUp(false), - wantDown(false), - isChangingFlightHeight(false) - {} -public: - virtual ~IMoveInput() {} - - virtual void tick(Player* player) {} - virtual void render(float a) {} - - virtual void setKey(int eventKey, bool eventKeyState) {} - virtual void releaseAllKeys() {} - - virtual void onConfigChanged(const Config& c) {} - -public: - float xa; - float ya; - - bool wasJumping; - bool jumping; - bool sneaking; - - bool wantUp; - bool wantDown; - bool isChangingFlightHeight; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER__IMoveInput_H__*/ +#pragma once + +//package net.minecraft.client.player; + +#include "../../IConfigListener.h" +class Player; +class Minecraft; + +class IMoveInput +{ +protected: + IMoveInput() + : xa(0), + ya(0), + wasJumping(false), + jumping(false), + sneaking(false), + wantUp(false), + wantDown(false), + isChangingFlightHeight(false) + {} +public: + virtual ~IMoveInput() {} + + virtual void tick(Player* player) {} + virtual void render(float a) {} + + virtual void setKey(int eventKey, bool eventKeyState) {} + virtual void releaseAllKeys() {} + + virtual void onConfigChanged(const Config& c) {} + +public: + float xa; + float ya; + + bool wasJumping; + bool jumping; + bool sneaking; + + bool wantUp; + bool wantDown; + bool isChangingFlightHeight; +}; + diff --git a/src/client/player/input/ITurnInput.h b/src/client/player/input/ITurnInput.h index 151e807..0db08d0 100755 --- a/src/client/player/input/ITurnInput.h +++ b/src/client/player/input/ITurnInput.h @@ -1,52 +1,50 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER__ITurnInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER__ITurnInput_H__ - -#include "../../../platform/time.h" -#include "../../IConfigListener.h" -#include - -/** Representing a Turn delta value */ -class TurnDelta { -public: - TurnDelta(float dx, float dy) - : x(dx), - y(dy) - {} - - float x, y; -}; - -/** Base class for classes providing TurnDeltas */ -class ITurnInput: public IConfigListener { -public: - virtual ~ITurnInput() {} - virtual void onConfigChanged(const Config& c) {} - - virtual TurnDelta getTurnDelta() = 0; -protected: - ITurnInput() - : _lastTime(-1.0f) - {} - - float getDeltaTime(){ - if (_lastTime == -1.0f) { - _lastTime = getTimeS(); - } - float now = getTimeS(); - float dt = now - _lastTime; - _lastTime = now; - return dt; - } - - static float linearTransform(float value, float deadZone, float scale=1.0f, bool limit1=false) { - float deadSigned = value >= 0? deadZone : -deadZone; - if (std::abs(deadSigned) >= std::abs(value)) return 0; - float ret = (value - deadSigned) * scale; - if (limit1 && std::abs(ret) > 1) ret /= std::abs(ret); - return ret; - } -private: - float _lastTime; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER__ITurnInput_H__*/ +#pragma once + +#include "../../../platform/time.h" +#include "../../IConfigListener.h" +#include + +/** Representing a Turn delta value */ +class TurnDelta { +public: + TurnDelta(float dx, float dy) + : x(dx), + y(dy) + {} + + float x, y; +}; + +/** Base class for classes providing TurnDeltas */ +class ITurnInput: public IConfigListener { +public: + virtual ~ITurnInput() {} + virtual void onConfigChanged(const Config& c) {} + + virtual TurnDelta getTurnDelta() = 0; +protected: + ITurnInput() + : _lastTime(-1.0f) + {} + + float getDeltaTime(){ + if (_lastTime == -1.0f) { + _lastTime = getTimeS(); + } + float now = getTimeS(); + float dt = now - _lastTime; + _lastTime = now; + return dt; + } + + static float linearTransform(float value, float deadZone, float scale=1.0f, bool limit1=false) { + float deadSigned = value >= 0? deadZone : -deadZone; + if (std::abs(deadSigned) >= std::abs(value)) return 0; + float ret = (value - deadSigned) * scale; + if (limit1 && std::abs(ret) > 1) ret /= std::abs(ret); + return ret; + } +private: + float _lastTime; +}; + diff --git a/src/client/player/input/KeyboardInput.h b/src/client/player/input/KeyboardInput.h index eb33c31..7342451 100755 --- a/src/client/player/input/KeyboardInput.h +++ b/src/client/player/input/KeyboardInput.h @@ -1,36 +1,34 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER__KeyboardInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER__KeyboardInput_H__ - -//package net.minecraft.client.player; - -#include "IMoveInput.h" - -class Options; -class Player; - -// @todo: extract a separate MoveInput (-> merge XperiaPlayInput) -class KeyboardInput: public IMoveInput -{ - static const int NumKeys = 10; -public: - static const int KEY_UP = 0; - static const int KEY_DOWN = 1; - static const int KEY_LEFT = 2; - static const int KEY_RIGHT = 3; - static const int KEY_JUMP = 4; - static const int KEY_SNEAK = 5; - static const int KEY_CRAFT = 6; - - KeyboardInput(Options* options); - - void tick(Player* player); - - void setKey(int key, bool state); - void releaseAllKeys(); - -protected: - bool keys[NumKeys]; - Options* options; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER__KeyboardInput_H__*/ +#pragma once + +//package net.minecraft.client.player; + +#include "IMoveInput.h" + +class Options; +class Player; + +// @todo: extract a separate MoveInput (-> merge XperiaPlayInput) +class KeyboardInput: public IMoveInput +{ + static const int NumKeys = 10; +public: + static const int KEY_UP = 0; + static const int KEY_DOWN = 1; + static const int KEY_LEFT = 2; + static const int KEY_RIGHT = 3; + static const int KEY_JUMP = 4; + static const int KEY_SNEAK = 5; + static const int KEY_CRAFT = 6; + + KeyboardInput(Options* options); + + void tick(Player* player); + + void setKey(int key, bool state); + void releaseAllKeys(); + +protected: + bool keys[NumKeys]; + Options* options; +}; + diff --git a/src/client/player/input/MouseBuildInput.h b/src/client/player/input/MouseBuildInput.h index c50b0c4..91938e8 100755 --- a/src/client/player/input/MouseBuildInput.h +++ b/src/client/player/input/MouseBuildInput.h @@ -1,36 +1,34 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER_INPUT_MouseBuildInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER_INPUT_MouseBuildInput_H__ - -#include "IBuildInput.h" -#include "../../../platform/input/Mouse.h" - -/** A Mouse Build input */ -class MouseBuildInput : public IBuildInput { -public: - MouseBuildInput() - : buildDelayTicks(10), - buildHoldTicks(0) - {} - - virtual bool tickBuild(Player* p, BuildActionIntention* bai) { - if (Mouse::getButtonState(MouseAction::ACTION_LEFT) != 0) { - *bai = BuildActionIntention(BuildActionIntention::BAI_REMOVE | BuildActionIntention::BAI_ATTACK); - return true; - } - if (Mouse::getButtonState(MouseAction::ACTION_RIGHT) != 0) { - if (buildHoldTicks >= buildDelayTicks) buildHoldTicks = 0; - if (++buildHoldTicks == 1) { - *bai = BuildActionIntention(BuildActionIntention::BAI_BUILD | BuildActionIntention::BAI_INTERACT); - return true; - } - } else { - buildHoldTicks = 0; - } - return false; - } -private: - int buildHoldTicks; - int buildDelayTicks; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER_INPUT_MouseBuildInput_H__*/ +#pragma once + +#include "IBuildInput.h" +#include "../../../platform/input/Mouse.h" + +/** A Mouse Build input */ +class MouseBuildInput : public IBuildInput { +public: + MouseBuildInput() + : buildDelayTicks(10), + buildHoldTicks(0) + {} + + virtual bool tickBuild(Player* p, BuildActionIntention* bai) { + if (Mouse::getButtonState(MouseAction::ACTION_LEFT) != 0) { + *bai = BuildActionIntention(BuildActionIntention::BAI_REMOVE | BuildActionIntention::BAI_ATTACK); + return true; + } + if (Mouse::getButtonState(MouseAction::ACTION_RIGHT) != 0) { + if (buildHoldTicks >= buildDelayTicks) buildHoldTicks = 0; + if (++buildHoldTicks == 1) { + *bai = BuildActionIntention(BuildActionIntention::BAI_BUILD | BuildActionIntention::BAI_INTERACT); + return true; + } + } else { + buildHoldTicks = 0; + } + return false; + } +private: + int buildHoldTicks; + int buildDelayTicks; +}; + diff --git a/src/client/player/input/MouseTurnInput.h b/src/client/player/input/MouseTurnInput.h index a1cf6b4..5fc25cd 100755 --- a/src/client/player/input/MouseTurnInput.h +++ b/src/client/player/input/MouseTurnInput.h @@ -1,43 +1,41 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER_INPUT_MouseTurnInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER_INPUT_MouseTurnInput_H__ - -#include "ITurnInput.h" -#include "../../../platform/input/Mouse.h" - -/** A Mouse Turn input */ -class MouseTurnInput : public ITurnInput { -public: - static const int MODE_OFFSET = 1; - static const int MODE_DELTA = 2; - - MouseTurnInput(int mode_, int centerX, int centerY) - : mode(mode_), - _centerX((float)centerX), - _centerY((float)centerY) - {} - - void onConfigChanged(const Config& config) { - _centerX = ((float) config.width ) * 0.5f; - _centerY = ((float) config.height) * 0.5f; - } - - TurnDelta getTurnDelta() { - float dx = 0, dy = 0; - if ( MODE_DELTA == mode ) { - dx = (float)Mouse::getDX(); - dy = (float)Mouse::getDY(); - } else if (MODE_OFFSET == mode) { - float dt = getDeltaTime(); - dx = linearTransform( (float)Mouse::getX() - _centerX, 40, 0.4f ) * dt; - dy = linearTransform( (float)Mouse::getY() - _centerY, 30, 0.6f ) * dt; - } - return TurnDelta(dx, dy); - } - - int mode; -private: - float _centerX; - float _centerY; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER_INPUT_MouseTurnInput_H__*/ +#pragma once + +#include "ITurnInput.h" +#include "../../../platform/input/Mouse.h" + +/** A Mouse Turn input */ +class MouseTurnInput : public ITurnInput { +public: + static const int MODE_OFFSET = 1; + static const int MODE_DELTA = 2; + + MouseTurnInput(int mode_, int centerX, int centerY) + : mode(mode_), + _centerX((float)centerX), + _centerY((float)centerY) + {} + + void onConfigChanged(const Config& config) { + _centerX = ((float) config.width ) * 0.5f; + _centerY = ((float) config.height) * 0.5f; + } + + TurnDelta getTurnDelta() { + float dx = 0, dy = 0; + if ( MODE_DELTA == mode ) { + dx = (float)Mouse::getDX(); + dy = (float)Mouse::getDY(); + } else if (MODE_OFFSET == mode) { + float dt = getDeltaTime(); + dx = linearTransform( (float)Mouse::getX() - _centerX, 40, 0.4f ) * dt; + dy = linearTransform( (float)Mouse::getY() - _centerY, 30, 0.6f ) * dt; + } + return TurnDelta(dx, dy); + } + + int mode; +private: + float _centerX; + float _centerY; +}; + diff --git a/src/client/player/input/XperiaPlayInput.h b/src/client/player/input/XperiaPlayInput.h index 0b3afc5..bfba51f 100755 --- a/src/client/player/input/XperiaPlayInput.h +++ b/src/client/player/input/XperiaPlayInput.h @@ -1,51 +1,49 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER__XperiaPlayInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER__XperiaPlayInput_H__ - -//package net.minecraft.client.player; - -#include "KeyboardInput.h" -#include "platform/input/Controller.h" -#include "world/entity/player/Player.h" - -// @note: This is just copy-pasted from KeyboardInput right now. -class XperiaPlayInput: public KeyboardInput -{ - typedef KeyboardInput super; -public: - XperiaPlayInput(Options* options) - : super(options), - wasSneakTouched(false) - {} - - void tick(Player* player) { - bool _sneaking = sneaking; - super::tick(player); - sneaking = _sneaking; - - wantUp = (jumping && keys[KEY_UP]); - wantDown = (jumping && keys[KEY_DOWN]); - if ((wantUp | wantDown) && (player && player->abilities.flying)) ya = 0; - - bool isSneakTouched = Controller::isTouched(1); - if (isSneakTouched && !wasSneakTouched) { - sneaking = !sneaking; - } - wasSneakTouched = isSneakTouched; - - if (sneaking) { - xa *= 0.3f; - ya *= 0.3f; - } - } - - /* - if (Controller::isTouched(moveStick)) { - xa = -Controller::getTransformedX(moveStick, 0.1f, 1.25f, true); - ya = +Controller::getTransformedY(moveStick, 0.1f, 1.25f, true); - } - */ -private: - bool wasSneakTouched; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER__XperiaPlayInput_H__*/ +#pragma once + +//package net.minecraft.client.player; + +#include "KeyboardInput.h" +#include "platform/input/Controller.h" +#include "world/entity/player/Player.h" + +// @note: This is just copy-pasted from KeyboardInput right now. +class XperiaPlayInput: public KeyboardInput +{ + typedef KeyboardInput super; +public: + XperiaPlayInput(Options* options) + : super(options), + wasSneakTouched(false) + {} + + void tick(Player* player) { + bool _sneaking = sneaking; + super::tick(player); + sneaking = _sneaking; + + wantUp = (jumping && keys[KEY_UP]); + wantDown = (jumping && keys[KEY_DOWN]); + if ((wantUp | wantDown) && (player && player->abilities.flying)) ya = 0; + + bool isSneakTouched = Controller::isTouched(1); + if (isSneakTouched && !wasSneakTouched) { + sneaking = !sneaking; + } + wasSneakTouched = isSneakTouched; + + if (sneaking) { + xa *= 0.3f; + ya *= 0.3f; + } + } + + /* + if (Controller::isTouched(moveStick)) { + xa = -Controller::getTransformedX(moveStick, 0.1f, 1.25f, true); + ya = +Controller::getTransformedY(moveStick, 0.1f, 1.25f, true); + } + */ +private: + bool wasSneakTouched; +}; + diff --git a/src/client/player/input/touchscreen/ITouchScreenModel.h b/src/client/player/input/touchscreen/ITouchScreenModel.h index be764e2..c3f0820 100755 --- a/src/client/player/input/touchscreen/ITouchScreenModel.h +++ b/src/client/player/input/touchscreen/ITouchScreenModel.h @@ -1,14 +1,12 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER__ITouchScreenModel_H__ -#define NET_MINECRAFT_CLIENT_PLAYER__ITouchScreenModel_H__ - -#include "../../../../platform/input/Mouse.h" - -class ITouchScreenModel -{ -public: - virtual ~ITouchScreenModel() {} - virtual int getPointerId(const MouseAction& m) { return m.pointerId; } - virtual int getPointerId(int x, int y, int pid) { return pid; } -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER__ITouchScreenModel_H__*/ +#pragma once + +#include "../../../../platform/input/Mouse.h" + +class ITouchScreenModel +{ +public: + virtual ~ITouchScreenModel() {} + virtual int getPointerId(const MouseAction& m) { return m.pointerId; } + virtual int getPointerId(int x, int y, int pid) { return pid; } +}; + diff --git a/src/client/player/input/touchscreen/TouchAreaModel.h b/src/client/player/input/touchscreen/TouchAreaModel.h index 636b2a3..3a937de 100755 --- a/src/client/player/input/touchscreen/TouchAreaModel.h +++ b/src/client/player/input/touchscreen/TouchAreaModel.h @@ -1,339 +1,337 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER__TouchAreaModel_H__ -#define NET_MINECRAFT_CLIENT_PLAYER__TouchAreaModel_H__ - -#include "ITouchScreenModel.h" -#include -#include "../../../../platform/time.h" - -/// Interface for an area that can be point tested -class IArea{ -public: - IArea() - : deleteMe(true) - {} - - virtual ~IArea() {}; - virtual bool isInside(float x, float y) = 0; - //virtual void expandRectToInclude(float& l, float& t, float& r, float& b) {} - - bool deleteMe; -}; - -/// Holder for multiple pairs -class TouchAreaModel: public ITouchScreenModel -{ -public: - TouchAreaModel() {} - - ~TouchAreaModel() { - clear(); - } - - void clear() { - for (unsigned int i = 0; i < _areas.size(); ++i) { - Area* a = _areas[i]; - if (a->area && a->area->deleteMe) - delete a->area; - delete a; - } - _areas.clear(); - } - - int getPointerId(const MouseAction& m) { - return getPointerId(m.x, m.y, m.pointerId); - } - - int getPointerId(int x, int y, int pid) { - //static Stopwatch w; - //w.printEvery(200, "IArea"); - //w.start(); - float fx = (float)x, fy = (float) y; - for (unsigned int i = 0; i < _areas.size(); ++i) { - const Area* a = _areas[i]; - if (a->area->isInside(fx, fy)) { - //w.stop(); - return a->areaId; - } - } - //w.stop(); - return pid; - } - - void addArea(int areaId, IArea* area) { - Area* a = new Area(); - a->area = area; - a->areaId = areaId; - - _areas.push_back( a ); - } - -private: - struct Area { - IArea* area; - int areaId; - }; - - std::vector _areas; -}; - -/// Area represented by a polygon -class PolygonArea: public IArea -{ -public: - PolygonArea(int numPoints, const float* xp, const float* yp) - : _numPoints(numPoints) - { - _x = new float[numPoints]; - _y = new float[numPoints]; - - for (int i = 0; i < numPoints; ++i) { - _x[i] = xp[i]; - _y[i] = yp[i]; - } - } - - ~PolygonArea() { - delete[] _x; - delete[] _y; - } - - virtual bool isInside(float x, float y) - { - bool c = false; - for (int i = 0, j = _numPoints-1; i < _numPoints; j = i++) { - if ((((_y[i] <= y) && (y < _y[j])) || - ((_y[j] <= y) && (y < _y[i]))) && - (x < (_x[j] - _x[i]) * (y - _y[i]) / (_y[j] - _y[i]) + _x[i])) - c = !c; - } - return c == 1; - } - -//private: - float* _x; - float* _y; - int _numPoints; -}; - -/// Area represented by a rectangle -class RectangleArea: public IArea -{ -public: - RectangleArea(float x0, float y0, float x1, float y1) - : _x0(x0), - _x1(x1), - _y0(y0), - _y1(y1) - {} - - virtual bool isInside(float x, float y) { - return x >= _x0 && x <= _x1 - && y >= _y0 && y <= _y1; - } - - virtual float centerX() - { - return _x0 + (_x1 - _x0) * .5f; - } - - virtual float centerY() - { - return _y0 + (_y1 - _y0) * .5f; - } - -//private: - float _x0, _x1; - float _y0, _y1; -}; - -/// An area represented by a circle -class CircleArea: public IArea -{ -public: - CircleArea(float x, float y, float r) - : _x(x), _y(y), _rr(r*r) - {} - - virtual bool isInside(float x, float y) { - const float dx = x - _x; - const float dy = y - _y; - return (dx*dx + dy*dy) <= _rr; - } - -private: - float _x, _y; - float _rr; -}; - -/// Inside any area in include list but none of exclude list -class IncludeExcludeArea: public IArea -{ -public: - IncludeExcludeArea() {} - - ~IncludeExcludeArea() { - clear(); - } - - void clear() { - if (deleteMe) { - for (unsigned int i = 0; i < _includes.size(); ++i) { - IArea* area = _includes[i]; - if (area->deleteMe) delete area; - } - for (unsigned int i = 0; i < _excludes.size(); ++i) { - IArea* area = _excludes[i]; - if (area->deleteMe) delete area; - } - } - _includes.clear(); - _excludes.clear(); - } - - void include(IArea* area) { _includes.push_back(area); } - void exclude(IArea* area) { _excludes.push_back(area); } - - virtual bool isInside(float x, float y) { - for (unsigned int i = 0; i < _includes.size(); ++i) - if (_includes[i]->isInside(x, y)) { - bool good = true; - //@todo: cache _exclude-test results - for (unsigned int j = 0; j < _excludes.size(); ++j) - if (_excludes[j]->isInside(x, y)) { - good = false; - break; - } - if (good) { - return true; - } - } - return false; - } - -private: - std::vector _includes; - std::vector _excludes; -}; - - -/// At least one of the areas -class OrArea: public IArea -{ -public: - OrArea(IArea* a, IArea* b) - : _a(a), - _b(b) - {} - - ~OrArea() { - if (deleteMe) { - if (_a->deleteMe) delete _a; - if (_b->deleteMe) delete _b; - } - } - - virtual bool isInside(float x, float y) { - return _a->isInside(x, y) || _b->isInside(x, y); - } - -private: - IArea* _a; - IArea* _b; -}; - -/// In both areas -class AndArea: public IArea -{ -public: - AndArea(IArea* a, IArea* b) - : _a(a), - _b(b) - {} - - ~AndArea() { - if (deleteMe) { - if (_a->deleteMe) delete _a; - if (_b->deleteMe) delete _b; - } - } - - virtual bool isInside(float x, float y) { - return _a->isInside(x, y) && _b->isInside(x, y); - } - -private: - IArea* _a; - IArea* _b; -}; - -/// Exactly one of the areas -class XorArea: public IArea -{ -public: - XorArea(IArea* a, IArea* b) - : _a(a), - _b(b) - {} - - ~XorArea() { - if (deleteMe) { - if (_a->deleteMe) delete _a; - if (_b->deleteMe) delete _b; - } - } - - virtual bool isInside(float x, float y) { - return _a->isInside(x, y) ^ _b->isInside(x, y); - } - -private: - IArea* _a; - IArea* _b; -}; - -/// Everything except this area -class NotArea: public IArea -{ -public: - NotArea(IArea* a) - : _a(a) - {} - - ~NotArea() { - if (deleteMe && _a->deleteMe) delete _a; - } - - virtual bool isInside(float x, float y) { - return !_a->isInside(x, y); - } - -private: - IArea* _a; -}; - -/// First area, but not second -/// This is semantically the same as AndArea( a, new NotArea(b) ) -class DifferenceArea: public IArea -{ -public: - DifferenceArea(IArea* a, IArea* b) - : _a(a), - _b(b) - {} - - ~DifferenceArea() { - if (deleteMe) { - if (_a->deleteMe) delete _a; - if (_b->deleteMe) delete _b; - } - } - - virtual bool isInside(float x, float y) { - return _a->isInside(x, y) && !_b->isInside(x, y); - } -private: - IArea* _a; - IArea* _b; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER__TouchAreaModel_H__*/ +#pragma once + +#include "ITouchScreenModel.h" +#include +#include "../../../../platform/time.h" + +/// Interface for an area that can be point tested +class IArea{ +public: + IArea() + : deleteMe(true) + {} + + virtual ~IArea() {}; + virtual bool isInside(float x, float y) = 0; + //virtual void expandRectToInclude(float& l, float& t, float& r, float& b) {} + + bool deleteMe; +}; + +/// Holder for multiple pairs +class TouchAreaModel: public ITouchScreenModel +{ +public: + TouchAreaModel() {} + + ~TouchAreaModel() { + clear(); + } + + void clear() { + for (unsigned int i = 0; i < _areas.size(); ++i) { + Area* a = _areas[i]; + if (a->area && a->area->deleteMe) + delete a->area; + delete a; + } + _areas.clear(); + } + + int getPointerId(const MouseAction& m) { + return getPointerId(m.x, m.y, m.pointerId); + } + + int getPointerId(int x, int y, int pid) { + //static Stopwatch w; + //w.printEvery(200, "IArea"); + //w.start(); + float fx = (float)x, fy = (float) y; + for (unsigned int i = 0; i < _areas.size(); ++i) { + const Area* a = _areas[i]; + if (a->area->isInside(fx, fy)) { + //w.stop(); + return a->areaId; + } + } + //w.stop(); + return pid; + } + + void addArea(int areaId, IArea* area) { + Area* a = new Area(); + a->area = area; + a->areaId = areaId; + + _areas.push_back( a ); + } + +private: + struct Area { + IArea* area; + int areaId; + }; + + std::vector _areas; +}; + +/// Area represented by a polygon +class PolygonArea: public IArea +{ +public: + PolygonArea(int numPoints, const float* xp, const float* yp) + : _numPoints(numPoints) + { + _x = new float[numPoints]; + _y = new float[numPoints]; + + for (int i = 0; i < numPoints; ++i) { + _x[i] = xp[i]; + _y[i] = yp[i]; + } + } + + ~PolygonArea() { + delete[] _x; + delete[] _y; + } + + virtual bool isInside(float x, float y) + { + bool c = false; + for (int i = 0, j = _numPoints-1; i < _numPoints; j = i++) { + if ((((_y[i] <= y) && (y < _y[j])) || + ((_y[j] <= y) && (y < _y[i]))) && + (x < (_x[j] - _x[i]) * (y - _y[i]) / (_y[j] - _y[i]) + _x[i])) + c = !c; + } + return c == 1; + } + +//private: + float* _x; + float* _y; + int _numPoints; +}; + +/// Area represented by a rectangle +class RectangleArea: public IArea +{ +public: + RectangleArea(float x0, float y0, float x1, float y1) + : _x0(x0), + _x1(x1), + _y0(y0), + _y1(y1) + {} + + virtual bool isInside(float x, float y) { + return x >= _x0 && x <= _x1 + && y >= _y0 && y <= _y1; + } + + virtual float centerX() + { + return _x0 + (_x1 - _x0) * .5f; + } + + virtual float centerY() + { + return _y0 + (_y1 - _y0) * .5f; + } + +//private: + float _x0, _x1; + float _y0, _y1; +}; + +/// An area represented by a circle +class CircleArea: public IArea +{ +public: + CircleArea(float x, float y, float r) + : _x(x), _y(y), _rr(r*r) + {} + + virtual bool isInside(float x, float y) { + const float dx = x - _x; + const float dy = y - _y; + return (dx*dx + dy*dy) <= _rr; + } + +private: + float _x, _y; + float _rr; +}; + +/// Inside any area in include list but none of exclude list +class IncludeExcludeArea: public IArea +{ +public: + IncludeExcludeArea() {} + + ~IncludeExcludeArea() { + clear(); + } + + void clear() { + if (deleteMe) { + for (unsigned int i = 0; i < _includes.size(); ++i) { + IArea* area = _includes[i]; + if (area->deleteMe) delete area; + } + for (unsigned int i = 0; i < _excludes.size(); ++i) { + IArea* area = _excludes[i]; + if (area->deleteMe) delete area; + } + } + _includes.clear(); + _excludes.clear(); + } + + void include(IArea* area) { _includes.push_back(area); } + void exclude(IArea* area) { _excludes.push_back(area); } + + virtual bool isInside(float x, float y) { + for (unsigned int i = 0; i < _includes.size(); ++i) + if (_includes[i]->isInside(x, y)) { + bool good = true; + //@todo: cache _exclude-test results + for (unsigned int j = 0; j < _excludes.size(); ++j) + if (_excludes[j]->isInside(x, y)) { + good = false; + break; + } + if (good) { + return true; + } + } + return false; + } + +private: + std::vector _includes; + std::vector _excludes; +}; + + +/// At least one of the areas +class OrArea: public IArea +{ +public: + OrArea(IArea* a, IArea* b) + : _a(a), + _b(b) + {} + + ~OrArea() { + if (deleteMe) { + if (_a->deleteMe) delete _a; + if (_b->deleteMe) delete _b; + } + } + + virtual bool isInside(float x, float y) { + return _a->isInside(x, y) || _b->isInside(x, y); + } + +private: + IArea* _a; + IArea* _b; +}; + +/// In both areas +class AndArea: public IArea +{ +public: + AndArea(IArea* a, IArea* b) + : _a(a), + _b(b) + {} + + ~AndArea() { + if (deleteMe) { + if (_a->deleteMe) delete _a; + if (_b->deleteMe) delete _b; + } + } + + virtual bool isInside(float x, float y) { + return _a->isInside(x, y) && _b->isInside(x, y); + } + +private: + IArea* _a; + IArea* _b; +}; + +/// Exactly one of the areas +class XorArea: public IArea +{ +public: + XorArea(IArea* a, IArea* b) + : _a(a), + _b(b) + {} + + ~XorArea() { + if (deleteMe) { + if (_a->deleteMe) delete _a; + if (_b->deleteMe) delete _b; + } + } + + virtual bool isInside(float x, float y) { + return _a->isInside(x, y) ^ _b->isInside(x, y); + } + +private: + IArea* _a; + IArea* _b; +}; + +/// Everything except this area +class NotArea: public IArea +{ +public: + NotArea(IArea* a) + : _a(a) + {} + + ~NotArea() { + if (deleteMe && _a->deleteMe) delete _a; + } + + virtual bool isInside(float x, float y) { + return !_a->isInside(x, y); + } + +private: + IArea* _a; +}; + +/// First area, but not second +/// This is semantically the same as AndArea( a, new NotArea(b) ) +class DifferenceArea: public IArea +{ +public: + DifferenceArea(IArea* a, IArea* b) + : _a(a), + _b(b) + {} + + ~DifferenceArea() { + if (deleteMe) { + if (_a->deleteMe) delete _a; + if (_b->deleteMe) delete _b; + } + } + + virtual bool isInside(float x, float y) { + return _a->isInside(x, y) && !_b->isInside(x, y); + } +private: + IArea* _a; + IArea* _b; +}; + diff --git a/src/client/player/input/touchscreen/TouchInputHolder.h b/src/client/player/input/touchscreen/TouchInputHolder.h index afda575..b2ae433 100755 --- a/src/client/player/input/touchscreen/TouchInputHolder.h +++ b/src/client/player/input/touchscreen/TouchInputHolder.h @@ -1,471 +1,469 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER_INPUT_TOUCHSCREEN_TouchInputHolder_H__ -#define NET_MINECRAFT_CLIENT_PLAYER_INPUT_TOUCHSCREEN_TouchInputHolder_H__ - -#include "../IInputHolder.h" -#include "TouchscreenInput.h" - -#include "../ITurnInput.h" -#include "TouchAreaModel.h" -#include "../../../../platform/input/Multitouch.h" -#include "../../../../platform/time.h" -#include "../../../../util/SmoothFloat.h" - -#include "../../../../world/entity/player/Player.h" -#include "../../../../world/entity/player/Inventory.h" - -template -class ModifyNotify { -public: - ModifyNotify() - : _changed(false) - {} - - T& getOld() { return _old; } - T& getNew() { return _new; } - - bool update(T& val) { - _changed = !equals(val); - if (_changed) { - _old = _new; - _new = val; - } - return _changed; - } - - bool hasChanged() const { return _changed; } - - virtual bool equals(const T& newVal) { - return _old != newVal; - } -protected: - T _old; -private: - T _new; - bool _changed; -}; - -// -// Implementation for unified [Turn & Build Input] -// -class UnifiedTurnBuild: public GuiComponent, - public ITurnInput, - public IBuildInput -{ -public: - static const int MODE_OFFSET = 1; - static const int MODE_DELTA = 2; - - UnifiedTurnBuild(int turnMode, int width, int height, float maxMovementDelta, float sensitivity, IInputHolder* holder, Minecraft* minecraft) - : mode(turnMode), - _holder(holder), - _options(&minecraft->options), - cxO(0), cyO(0), - wasActive(false), - _totalMoveDelta(0), - _maxMovement(maxMovementDelta), - _lastPlayer(0), - screenArea(-1, -1, 0, 0), - allowPicking(false), - state(State_None), - moveArea(-1,-1,0,0), - joyTouchArea(-1, -1, 0, 0), - inventoryArea(-1,-1, 0, 0), - pauseArea(-1, -1, 0, 0), - _buildMovement(0), - _sentFirstRemove(false), - _canDestroy(false), - _forceCanUse(false) - { - _area.deleteMe = false; - setSensitivity(sensitivity); - //((ITurnInput*)this)->onConfigChanged(createConfig(minecraft)); - onConfigChanged(createConfig(minecraft)); - - _lastBuildDownTime = _startTurnTime = getTimeS(); - } - - void setSensitivity(float sensitivity) { - _sensitivity = sensitivity; - } - - virtual void onConfigChanged(const Config& c) { - if (false && _options->getBooleanValue(OPTIONS_IS_JOY_TOUCH_AREA)) { - int touchWidth = c.width - (int)inventoryArea._x1; - if (touchWidth > (int)c.minecraft->pixelCalc.millimetersToPixels(60)) - touchWidth = (int)c.minecraft->pixelCalc.millimetersToPixels(60); - - int touchHeight = (int)(c.height * 0.4f); - if (touchHeight > (int)c.minecraft->pixelCalc.millimetersToPixels(40)) - touchHeight = (int)c.minecraft->pixelCalc.millimetersToPixels(40); - - joyTouchArea._x0 = (float)(c.width - touchWidth); - joyTouchArea._y0 = (float)(c.height - touchHeight); - joyTouchArea._x1 = (float)c.width; - joyTouchArea._y1 = (float)c.height; - - _area.clear(); - _area.include (&joyTouchArea); - _model.clear(); - _model.addArea(AREA_TURN, &_area); - } else { - screenArea = RectangleArea(0, 0, (float)c.width, (float)c.height); - // Expand the move area a bit - const float border = 10; - const float widen = (moveArea._x1-moveArea._x0) * 0.05f + border; // ~5% wider - moveArea._x0 -= widen; - moveArea._x1 += widen; - const float heighten = (moveArea._y1-moveArea._y0) * 0.05f + border; // ~5% taller - moveArea._y0 -= heighten; - moveArea._y1 += heighten; - - pauseArea._x0 -= border; - pauseArea._x1 += border; - pauseArea._y0 -= border; - pauseArea._y1 += border; - - //LOGI("move: %f, %f, %f, %f\n", moveArea._x0, moveArea._y0, moveArea._x1, moveArea._y1); - - _area.clear(); - _area.include(&screenArea); - _area.exclude(&moveArea); - _area.exclude(&inventoryArea); -#ifdef __APPLE__ - _area.exclude(&pauseArea); -#endif /*__APPLE__*/ - //LOGI("Movearea: %f %f %f% f\n", moveArea._x0, moveArea._x1, moveArea._y0, moveArea._y1); - - _model.clear(); - _model.addArea(AREA_TURN, &_area); - } - } - - float calcNewAlpha(float current, float wanted) { - if (wanted > current) - return Mth::clamp(current + 0.02f, 0.0f, wanted); - if (wanted < current) - return Mth::clamp(current - 0.04f, wanted, 1.0f); - return current; - } - - // - // Implementation for the ITurnInput part - // - TurnDelta getTurnDelta() { - float dx = 0, dy = 0; - const float now = getTimeS(); - - float cx = 0; - float cy = 0; - bool isActive = false; - - const int* pointerIds; - bool wasFirstMovement = false; - int pointerCount = Multitouch::getActivePointerIds(&pointerIds); - for (int i = 0; i < pointerCount; ++i) { - int p = pointerIds[i]; - int x = Multitouch::getX(p); - int y = Multitouch::getY(p); - int areaId = _model.getPointerId(x, y, p); - - if (areaId == AREA_TURN) { - isActive = true; - cx = (float)x * 0.5f; - cy = (float)y * -0.5f; - wasFirstMovement = Multitouch::wasFirstMovement(p); - break; - } - } - if (isActive && !wasActive) { - _startTurnTime = now; - _totalMoveDelta = 0; - bool isInMovement = _lastPlayer? getSpeedSquared(_lastPlayer) > 0.01f/*.25f*/ : false; - //state = isInMovement? State_Turn : State_Deciding; - state = State_Deciding; - _canDestroy = !isInMovement; - _forceCanUse = false; - if (!_canDestroy && (_lastPlayer && _lastPlayer->canUseCarriedItemWhileMoving())) { - _forceCanUse = true; - _canDestroy = true; - } - _sentFirstRemove = false; - } else if (wasActive && !isActive) { - _sentFirstRemove = false; - state = State_None; - //_inBuild = false; - } - - if (MODE_DELTA == mode && (wasActive || isActive)) { -// const float dt = getDeltaTime(); -// const float MaxTurnX = 100.0f; -// const float MaxTurnY = 100.0f; - const float DeadZone = 0;//0.25f * dt;//0.02f; - - if (!wasActive) { - cxO = cx; - cyO = cy; - } - if (isActive) { - dx = _sensitivity * linearTransform(cx - cxO, DeadZone);// * MaxTurnX; - dy = _sensitivity * linearTransform(cy - cyO, DeadZone);// * MaxTurnY; - - float moveDelta = ( Mth::abs(dx) + Mth::abs(dy) ); - //LOGI("moveDelta is : %f\n", moveDelta); - - if (moveDelta > _maxMovement) { - dx = 0; - dy = 0; - moveDelta = 0; - } - _totalMoveDelta += moveDelta; - - if (state == State_Deciding && _totalMoveDelta >= MaxBuildMovement/* && !_forceCanUse*/) - state = State_Turn; - - // If a certain time has passed since we pressed button; check if - // we've moved enough to prevent removal state to become activated - const float since = now - _startTurnTime; - if (state == State_Deciding && (since >= (0.001f*RemovalMilliseconds))) { - //LOGI("DECIDED!: %f\n", _totalMoveDelta); - bool isInMovement = _lastPlayer? getSpeedSquared(_lastPlayer) > 0.01f/*.25f*/ : false; - if (!_forceCanUse && (_totalMoveDelta > 20.0f || isInMovement)) { - state = State_Turn; - } else { - state = State_Destroy; - _canDestroy = true; - } - } - - // Removing the pointer ketchup-effect that's built into some devices - if (wasFirstMovement) { - dx = dy = 0; - } - - cxO = cx; - cyO = cy; - //LOGI("move delta: %f (%f, %f), %d\n", moveDelta, dx, dy, state); - } - } else { - // Wasn't active, and isn't active! - state = State_None; - } - - updateFeedbackProgressAlpha(now); - - wasActive = isActive; - return TurnDelta(dx, -dy); - } - - void updateFeedbackProgressAlpha(float now) { - const float MinAlphaValue = -0.05f; - if (_canDestroy) { - // Hack to test out fading in feedback circle - const float since = now - _startTurnTime; - if (state == State_Deciding) { - const float wantedAlpha = since / (0.001f*RemovalMilliseconds); - _holder->alpha = wantedAlpha * wantedAlpha; - } else { - if (state == State_Destroy) { - _holder->alpha = calcNewAlpha(_holder->alpha, 1); - } else if (state == State_Turn || state == State_None) { - _holder->alpha = calcNewAlpha(_holder->alpha, 0); - } - - } - } else { - _holder->alpha = MinAlphaValue; - } - //LOGI("state: %d, canDestroy: %d %d\n", state, _canDestroy, _forceCanUse); - //LOGI("alpha: %f\n", _holder->alpha); - } - - bool isInsideArea(float x, float y) { - return _area.isInside(x, y); - } - - int mode; - - static float getSpeedSquared(Entity* m) { - const float xd = m->x - m->xo; - const float yd = m->y - m->yo; - const float zd = m->z - m->zo; - const float speedSquared = xd*xd + yd*yd + zd*zd; - return speedSquared; - } - - void render(float alpha) { - if (_options->getBooleanValue(OPTIONS_IS_JOY_TOUCH_AREA)) { - fill( (int) (Gui::InvGuiScale * joyTouchArea._x0), - (int) (Gui::InvGuiScale * joyTouchArea._y0), - (int) (Gui::InvGuiScale * joyTouchArea._x1), - (int) (Gui::InvGuiScale * joyTouchArea._y1), 0x40000000);//0x20ffffff); - } - } - - // - // Implementation for the IBuildInput part - // - virtual bool tickBuild(Player* player, BuildActionIntention* bai) { - _lastPlayer = player; - - if (state == State_Destroy) { - if (!_sentFirstRemove) { - *bai = BuildActionIntention((_forceCanUse?0:BuildActionIntention::BAI_FIRSTREMOVE) | BuildActionIntention::BAI_INTERACT); - _sentFirstRemove = true; - } else { - *bai = BuildActionIntention((_forceCanUse?0:BuildActionIntention::BAI_REMOVE) | BuildActionIntention::BAI_INTERACT); - } - return true; - } - - // Rewind the queue, in case someone has used it up before - Multitouch::rewind(); - const float now = getTimeS(); - allowPicking = false; - bool handled = false; - - while (Multitouch::next()) { - MouseAction& m = Multitouch::getEvent(); - if (m.action == MouseAction::ACTION_MOVE) continue; - - int areaId = _model.getPointerId(m.x, m.y, m.pointerId); - if (areaId != AREA_TURN) continue; - - allowPicking = true; - //LOGI("down? %d, up? %d (%d, %d)\n", z && (m.data == MouseAction::DATA_DOWN), z && (m.data == MouseAction::DATA_UP), m.x, m.y); - - if (_totalMoveDelta <= MaxBuildMovement && (m.data == MouseAction::DATA_UP && !handled)) { - const float since = now - _lastBuildDownTime; - //LOGI("move: (%d) %.2f - %f\n", state, _totalMoveDelta, since); - if (state <= State_Deciding) { - if (since >= 0.0f && since < 0.25f) { - // We've pressed and released in haste; Let's build! - *bai = BuildActionIntention(BuildActionIntention::BAI_BUILD | BuildActionIntention::BAI_ATTACK); - handled = true; - } - } - state = State_None; - } else if (m.data == MouseAction::DATA_DOWN) { - _lastBuildDownTime = now; - _buildMovement = 0; - state = State_Deciding; - } - } - return handled; - } - - bool allowPicking; - float alpha; - SmoothFloat smoothAlpha; - - RectangleArea screenArea; - RectangleArea moveArea; - RectangleArea joyTouchArea; - RectangleArea inventoryArea; - RectangleArea pauseArea; - -private: - IInputHolder* _holder; - - // Turn - int cid; - float cxO, cyO; - bool wasActive; - - TouchAreaModel _model; - IncludeExcludeArea _area; - - bool _decidedTurnMode; - - float _startTurnTime; - float _totalMoveDelta; - float _maxMovement; - float _sensitivity; - - Player* _lastPlayer; - - // Build - float _lastBuildDownTime; - float _buildMovement; - bool _sentFirstRemove; - bool _canDestroy; - bool _forceCanUse; - - int state; - static const int State_None = 0; - static const int State_Deciding = 1; - static const int State_Turn = 2; - static const int State_Destroy = 3; - static const int State_Build = 4; // Will never happen - - static const int MaxBuildMovement = 20; - static const int RemovalMilliseconds = 400; - - static const int AREA_TURN = 100; - Options* _options; -}; - -class Minecraft; - -#if defined(_MSC_VER) - #pragma warning( disable : 4355 ) // 'this' pointer in initialization list which is perfectly legal -#endif - -class TouchInputHolder: public IInputHolder -{ -public: - TouchInputHolder(Minecraft* mc, Options* options) - : _mc(mc), - _move(mc, options), - _turnBuild(UnifiedTurnBuild::MODE_DELTA, mc->width, mc->height, (float)MovementLimit, 1, this, mc) - { - onConfigChanged(createConfig(mc)); - } - ~TouchInputHolder() { - } - - virtual void onConfigChanged(const Config& c) { - _move.onConfigChanged(c); - _turnBuild.moveArea = _move.getRectangleArea(); - _turnBuild.pauseArea = _move.getPauseRectangleArea(); - _turnBuild.inventoryArea = _mc->gui.getRectangleArea( _mc->options.getBooleanValue(OPTIONS_IS_LEFT_HANDED)? 1 : -1 ); - _turnBuild.setSensitivity(c.options->getBooleanValue(OPTIONS_IS_JOY_TOUCH_AREA)? 1.8f : 1.0f); - ((ITurnInput*)&_turnBuild)->onConfigChanged(c); - } - - virtual bool allowPicking() { - const int* pointerIds; - int pointerCount = Multitouch::getActivePointerIds(&pointerIds); - for (int i = 0; i < pointerCount; ++i) { - int p = pointerIds[i]; - const float x = Multitouch::getX(p); - const float y = Multitouch::getY(p); - - if (_turnBuild.isInsideArea(x, y)) { - mousex = x; - mousey = y; - return true; - } - } - - return false; - // return _turnBuild.allowPicking; - } - - virtual void render(float alpha) { - _turnBuild.render(alpha); - } - - virtual IMoveInput* getMoveInput() { return &_move; } - virtual ITurnInput* getTurnInput() { return &_turnBuild; } - virtual IBuildInput* getBuildInput() { return &_turnBuild; } - -private: - TouchscreenInput_TestFps _move; - UnifiedTurnBuild _turnBuild; - - Minecraft* _mc; - - static const int MovementLimit = 200; // per update -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER_INPUT_TOUCHSCREEN_TouchInputHolder_H__*/ +#pragma once + +#include "../IInputHolder.h" +#include "TouchscreenInput.h" + +#include "../ITurnInput.h" +#include "TouchAreaModel.h" +#include "../../../../platform/input/Multitouch.h" +#include "../../../../platform/time.h" +#include "../../../../util/SmoothFloat.h" + +#include "../../../../world/entity/player/Player.h" +#include "../../../../world/entity/player/Inventory.h" + +template +class ModifyNotify { +public: + ModifyNotify() + : _changed(false) + {} + + T& getOld() { return _old; } + T& getNew() { return _new; } + + bool update(T& val) { + _changed = !equals(val); + if (_changed) { + _old = _new; + _new = val; + } + return _changed; + } + + bool hasChanged() const { return _changed; } + + virtual bool equals(const T& newVal) { + return _old != newVal; + } +protected: + T _old; +private: + T _new; + bool _changed; +}; + +// +// Implementation for unified [Turn & Build Input] +// +class UnifiedTurnBuild: public GuiComponent, + public ITurnInput, + public IBuildInput +{ +public: + static const int MODE_OFFSET = 1; + static const int MODE_DELTA = 2; + + UnifiedTurnBuild(int turnMode, int width, int height, float maxMovementDelta, float sensitivity, IInputHolder* holder, Minecraft* minecraft) + : mode(turnMode), + _holder(holder), + _options(&minecraft->options), + cxO(0), cyO(0), + wasActive(false), + _totalMoveDelta(0), + _maxMovement(maxMovementDelta), + _lastPlayer(0), + screenArea(-1, -1, 0, 0), + allowPicking(false), + state(State_None), + moveArea(-1,-1,0,0), + joyTouchArea(-1, -1, 0, 0), + inventoryArea(-1,-1, 0, 0), + pauseArea(-1, -1, 0, 0), + _buildMovement(0), + _sentFirstRemove(false), + _canDestroy(false), + _forceCanUse(false) + { + _area.deleteMe = false; + setSensitivity(sensitivity); + //((ITurnInput*)this)->onConfigChanged(createConfig(minecraft)); + onConfigChanged(createConfig(minecraft)); + + _lastBuildDownTime = _startTurnTime = getTimeS(); + } + + void setSensitivity(float sensitivity) { + _sensitivity = sensitivity; + } + + virtual void onConfigChanged(const Config& c) { + if (false && _options->getBooleanValue(OPTIONS_IS_JOY_TOUCH_AREA)) { + int touchWidth = c.width - (int)inventoryArea._x1; + if (touchWidth > (int)c.minecraft->pixelCalc.millimetersToPixels(60)) + touchWidth = (int)c.minecraft->pixelCalc.millimetersToPixels(60); + + int touchHeight = (int)(c.height * 0.4f); + if (touchHeight > (int)c.minecraft->pixelCalc.millimetersToPixels(40)) + touchHeight = (int)c.minecraft->pixelCalc.millimetersToPixels(40); + + joyTouchArea._x0 = (float)(c.width - touchWidth); + joyTouchArea._y0 = (float)(c.height - touchHeight); + joyTouchArea._x1 = (float)c.width; + joyTouchArea._y1 = (float)c.height; + + _area.clear(); + _area.include (&joyTouchArea); + _model.clear(); + _model.addArea(AREA_TURN, &_area); + } else { + screenArea = RectangleArea(0, 0, (float)c.width, (float)c.height); + // Expand the move area a bit + const float border = 10; + const float widen = (moveArea._x1-moveArea._x0) * 0.05f + border; // ~5% wider + moveArea._x0 -= widen; + moveArea._x1 += widen; + const float heighten = (moveArea._y1-moveArea._y0) * 0.05f + border; // ~5% taller + moveArea._y0 -= heighten; + moveArea._y1 += heighten; + + pauseArea._x0 -= border; + pauseArea._x1 += border; + pauseArea._y0 -= border; + pauseArea._y1 += border; + + //LOGI("move: %f, %f, %f, %f\n", moveArea._x0, moveArea._y0, moveArea._x1, moveArea._y1); + + _area.clear(); + _area.include(&screenArea); + _area.exclude(&moveArea); + _area.exclude(&inventoryArea); +#ifdef __APPLE__ + _area.exclude(&pauseArea); +#endif /*__APPLE__*/ + //LOGI("Movearea: %f %f %f% f\n", moveArea._x0, moveArea._x1, moveArea._y0, moveArea._y1); + + _model.clear(); + _model.addArea(AREA_TURN, &_area); + } + } + + float calcNewAlpha(float current, float wanted) { + if (wanted > current) + return Mth::clamp(current + 0.02f, 0.0f, wanted); + if (wanted < current) + return Mth::clamp(current - 0.04f, wanted, 1.0f); + return current; + } + + // + // Implementation for the ITurnInput part + // + TurnDelta getTurnDelta() { + float dx = 0, dy = 0; + const float now = getTimeS(); + + float cx = 0; + float cy = 0; + bool isActive = false; + + const int* pointerIds; + bool wasFirstMovement = false; + int pointerCount = Multitouch::getActivePointerIds(&pointerIds); + for (int i = 0; i < pointerCount; ++i) { + int p = pointerIds[i]; + int x = Multitouch::getX(p); + int y = Multitouch::getY(p); + int areaId = _model.getPointerId(x, y, p); + + if (areaId == AREA_TURN) { + isActive = true; + cx = (float)x * 0.5f; + cy = (float)y * -0.5f; + wasFirstMovement = Multitouch::wasFirstMovement(p); + break; + } + } + if (isActive && !wasActive) { + _startTurnTime = now; + _totalMoveDelta = 0; + bool isInMovement = _lastPlayer? getSpeedSquared(_lastPlayer) > 0.01f/*.25f*/ : false; + //state = isInMovement? State_Turn : State_Deciding; + state = State_Deciding; + _canDestroy = !isInMovement; + _forceCanUse = false; + if (!_canDestroy && (_lastPlayer && _lastPlayer->canUseCarriedItemWhileMoving())) { + _forceCanUse = true; + _canDestroy = true; + } + _sentFirstRemove = false; + } else if (wasActive && !isActive) { + _sentFirstRemove = false; + state = State_None; + //_inBuild = false; + } + + if (MODE_DELTA == mode && (wasActive || isActive)) { +// const float dt = getDeltaTime(); +// const float MaxTurnX = 100.0f; +// const float MaxTurnY = 100.0f; + const float DeadZone = 0;//0.25f * dt;//0.02f; + + if (!wasActive) { + cxO = cx; + cyO = cy; + } + if (isActive) { + dx = _sensitivity * linearTransform(cx - cxO, DeadZone);// * MaxTurnX; + dy = _sensitivity * linearTransform(cy - cyO, DeadZone);// * MaxTurnY; + + float moveDelta = ( Mth::abs(dx) + Mth::abs(dy) ); + //LOGI("moveDelta is : %f\n", moveDelta); + + if (moveDelta > _maxMovement) { + dx = 0; + dy = 0; + moveDelta = 0; + } + _totalMoveDelta += moveDelta; + + if (state == State_Deciding && _totalMoveDelta >= MaxBuildMovement/* && !_forceCanUse*/) + state = State_Turn; + + // If a certain time has passed since we pressed button; check if + // we've moved enough to prevent removal state to become activated + const float since = now - _startTurnTime; + if (state == State_Deciding && (since >= (0.001f*RemovalMilliseconds))) { + //LOGI("DECIDED!: %f\n", _totalMoveDelta); + bool isInMovement = _lastPlayer? getSpeedSquared(_lastPlayer) > 0.01f/*.25f*/ : false; + if (!_forceCanUse && (_totalMoveDelta > 20.0f || isInMovement)) { + state = State_Turn; + } else { + state = State_Destroy; + _canDestroy = true; + } + } + + // Removing the pointer ketchup-effect that's built into some devices + if (wasFirstMovement) { + dx = dy = 0; + } + + cxO = cx; + cyO = cy; + //LOGI("move delta: %f (%f, %f), %d\n", moveDelta, dx, dy, state); + } + } else { + // Wasn't active, and isn't active! + state = State_None; + } + + updateFeedbackProgressAlpha(now); + + wasActive = isActive; + return TurnDelta(dx, -dy); + } + + void updateFeedbackProgressAlpha(float now) { + const float MinAlphaValue = -0.05f; + if (_canDestroy) { + // Hack to test out fading in feedback circle + const float since = now - _startTurnTime; + if (state == State_Deciding) { + const float wantedAlpha = since / (0.001f*RemovalMilliseconds); + _holder->alpha = wantedAlpha * wantedAlpha; + } else { + if (state == State_Destroy) { + _holder->alpha = calcNewAlpha(_holder->alpha, 1); + } else if (state == State_Turn || state == State_None) { + _holder->alpha = calcNewAlpha(_holder->alpha, 0); + } + + } + } else { + _holder->alpha = MinAlphaValue; + } + //LOGI("state: %d, canDestroy: %d %d\n", state, _canDestroy, _forceCanUse); + //LOGI("alpha: %f\n", _holder->alpha); + } + + bool isInsideArea(float x, float y) { + return _area.isInside(x, y); + } + + int mode; + + static float getSpeedSquared(Entity* m) { + const float xd = m->x - m->xo; + const float yd = m->y - m->yo; + const float zd = m->z - m->zo; + const float speedSquared = xd*xd + yd*yd + zd*zd; + return speedSquared; + } + + void render(float alpha) { + if (_options->getBooleanValue(OPTIONS_IS_JOY_TOUCH_AREA)) { + fill( (int) (Gui::InvGuiScale * joyTouchArea._x0), + (int) (Gui::InvGuiScale * joyTouchArea._y0), + (int) (Gui::InvGuiScale * joyTouchArea._x1), + (int) (Gui::InvGuiScale * joyTouchArea._y1), 0x40000000);//0x20ffffff); + } + } + + // + // Implementation for the IBuildInput part + // + virtual bool tickBuild(Player* player, BuildActionIntention* bai) { + _lastPlayer = player; + + if (state == State_Destroy) { + if (!_sentFirstRemove) { + *bai = BuildActionIntention((_forceCanUse?0:BuildActionIntention::BAI_FIRSTREMOVE) | BuildActionIntention::BAI_INTERACT); + _sentFirstRemove = true; + } else { + *bai = BuildActionIntention((_forceCanUse?0:BuildActionIntention::BAI_REMOVE) | BuildActionIntention::BAI_INTERACT); + } + return true; + } + + // Rewind the queue, in case someone has used it up before + Multitouch::rewind(); + const float now = getTimeS(); + allowPicking = false; + bool handled = false; + + while (Multitouch::next()) { + MouseAction& m = Multitouch::getEvent(); + if (m.action == MouseAction::ACTION_MOVE) continue; + + int areaId = _model.getPointerId(m.x, m.y, m.pointerId); + if (areaId != AREA_TURN) continue; + + allowPicking = true; + //LOGI("down? %d, up? %d (%d, %d)\n", z && (m.data == MouseAction::DATA_DOWN), z && (m.data == MouseAction::DATA_UP), m.x, m.y); + + if (_totalMoveDelta <= MaxBuildMovement && (m.data == MouseAction::DATA_UP && !handled)) { + const float since = now - _lastBuildDownTime; + //LOGI("move: (%d) %.2f - %f\n", state, _totalMoveDelta, since); + if (state <= State_Deciding) { + if (since >= 0.0f && since < 0.25f) { + // We've pressed and released in haste; Let's build! + *bai = BuildActionIntention(BuildActionIntention::BAI_BUILD | BuildActionIntention::BAI_ATTACK); + handled = true; + } + } + state = State_None; + } else if (m.data == MouseAction::DATA_DOWN) { + _lastBuildDownTime = now; + _buildMovement = 0; + state = State_Deciding; + } + } + return handled; + } + + bool allowPicking; + float alpha; + SmoothFloat smoothAlpha; + + RectangleArea screenArea; + RectangleArea moveArea; + RectangleArea joyTouchArea; + RectangleArea inventoryArea; + RectangleArea pauseArea; + +private: + IInputHolder* _holder; + + // Turn + int cid; + float cxO, cyO; + bool wasActive; + + TouchAreaModel _model; + IncludeExcludeArea _area; + + bool _decidedTurnMode; + + float _startTurnTime; + float _totalMoveDelta; + float _maxMovement; + float _sensitivity; + + Player* _lastPlayer; + + // Build + float _lastBuildDownTime; + float _buildMovement; + bool _sentFirstRemove; + bool _canDestroy; + bool _forceCanUse; + + int state; + static const int State_None = 0; + static const int State_Deciding = 1; + static const int State_Turn = 2; + static const int State_Destroy = 3; + static const int State_Build = 4; // Will never happen + + static const int MaxBuildMovement = 20; + static const int RemovalMilliseconds = 400; + + static const int AREA_TURN = 100; + Options* _options; +}; + +class Minecraft; + +#if defined(_MSC_VER) + #pragma warning( disable : 4355 ) // 'this' pointer in initialization list which is perfectly legal +#endif + +class TouchInputHolder: public IInputHolder +{ +public: + TouchInputHolder(Minecraft* mc, Options* options) + : _mc(mc), + _move(mc, options), + _turnBuild(UnifiedTurnBuild::MODE_DELTA, mc->width, mc->height, (float)MovementLimit, 1, this, mc) + { + onConfigChanged(createConfig(mc)); + } + ~TouchInputHolder() { + } + + virtual void onConfigChanged(const Config& c) { + _move.onConfigChanged(c); + _turnBuild.moveArea = _move.getRectangleArea(); + _turnBuild.pauseArea = _move.getPauseRectangleArea(); + _turnBuild.inventoryArea = _mc->gui.getRectangleArea( _mc->options.getBooleanValue(OPTIONS_IS_LEFT_HANDED)? 1 : -1 ); + _turnBuild.setSensitivity(c.options->getBooleanValue(OPTIONS_IS_JOY_TOUCH_AREA)? 1.8f : 1.0f); + ((ITurnInput*)&_turnBuild)->onConfigChanged(c); + } + + virtual bool allowPicking() { + const int* pointerIds; + int pointerCount = Multitouch::getActivePointerIds(&pointerIds); + for (int i = 0; i < pointerCount; ++i) { + int p = pointerIds[i]; + const float x = Multitouch::getX(p); + const float y = Multitouch::getY(p); + + if (_turnBuild.isInsideArea(x, y)) { + mousex = x; + mousey = y; + return true; + } + } + + return false; + // return _turnBuild.allowPicking; + } + + virtual void render(float alpha) { + _turnBuild.render(alpha); + } + + virtual IMoveInput* getMoveInput() { return &_move; } + virtual ITurnInput* getTurnInput() { return &_turnBuild; } + virtual IBuildInput* getBuildInput() { return &_turnBuild; } + +private: + TouchscreenInput_TestFps _move; + UnifiedTurnBuild _turnBuild; + + Minecraft* _mc; + + static const int MovementLimit = 200; // per update +}; + diff --git a/src/client/player/input/touchscreen/TouchTurnInput.h b/src/client/player/input/touchscreen/TouchTurnInput.h index eaa2e96..8252164 100755 --- a/src/client/player/input/touchscreen/TouchTurnInput.h +++ b/src/client/player/input/touchscreen/TouchTurnInput.h @@ -1,88 +1,86 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER_INPUT_TOUCHSCREEN_TouchTurnInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER_INPUT_TOUCHSCREEN_TouchTurnInput_H__ - -#include "../ITurnInput.h" -#include "TouchAreaModel.h" -#include "../../../../platform/input/Multitouch.h" - -class TouchTurnInput: public ITurnInput -{ -public: - static const int MODE_OFFSET = 1; - static const int MODE_DELTA = 2; - - TouchTurnInput(int mode_) - : mode(mode_), - cxO(0), cyO(0), - wasActive(false) - { - } - - TurnDelta getTurnDelta() { - float dx = 0, dy = 0; - - float cx = 0; - float cy = 0; - bool isActive = false; - - const int* pointerIds; - int pointerCount = Multitouch::getActivePointerIds(&pointerIds); - for (int i = 0; i < pointerCount; ++i) { - int p = pointerIds[i]; - int x = Multitouch::getX(p); - int y = Multitouch::getY(p); - int areaId = _model.getPointerId(x, y, p); - - if (areaId == AREA_TURN) { - isActive = true; - cx = (float)x * 0.5f; - cy = (float)y * -0.5f; - break; - } - } - - if (MODE_OFFSET == mode) { - //float dt = getDeltaTime(); - //const float MaxTurnX = 250.0f; - //const float MaxTurnY = 200.0f; - //float cx = isActive? Controller::getX(cid) : cxO * 0.7f; - //float cy = isActive? Controller::getY(cid) : cyO * 0.7f; - //dx = linearTransform( cx, 0.1f, MaxTurnX ) * dt; - //dy = linearTransform( cy, 0.1f, MaxTurnY ) * dt; - //cxO = cx; - //cyO = cy; - } else - if (MODE_DELTA == mode && (wasActive || isActive)) { -// const float dt = getDeltaTime(); -// const float MaxTurnX = 100.0f; -// const float MaxTurnY = 100.0f; - const float DeadZone = 0;//0.25f * dt;//0.02f; - - if (!wasActive) { - cxO = cx; - cyO = cy; - } - if (isActive) { - dx = linearTransform(cx - cxO, DeadZone);// * MaxTurnX; - dy = linearTransform(cy - cyO, DeadZone);// * MaxTurnY; - cxO = cx; - cyO = cy; - } - } - - wasActive = isActive; - return TurnDelta(dx, -dy); - } - - int mode; -private: - int cid; - float cxO, cyO; - bool wasActive; - - TouchAreaModel _model; - - static const int AREA_TURN = 100; -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER_INPUT_TOUCHSCREEN_TouchTurnInput_H__*/ +#pragma once + +#include "../ITurnInput.h" +#include "TouchAreaModel.h" +#include "../../../../platform/input/Multitouch.h" + +class TouchTurnInput: public ITurnInput +{ +public: + static const int MODE_OFFSET = 1; + static const int MODE_DELTA = 2; + + TouchTurnInput(int mode_) + : mode(mode_), + cxO(0), cyO(0), + wasActive(false) + { + } + + TurnDelta getTurnDelta() { + float dx = 0, dy = 0; + + float cx = 0; + float cy = 0; + bool isActive = false; + + const int* pointerIds; + int pointerCount = Multitouch::getActivePointerIds(&pointerIds); + for (int i = 0; i < pointerCount; ++i) { + int p = pointerIds[i]; + int x = Multitouch::getX(p); + int y = Multitouch::getY(p); + int areaId = _model.getPointerId(x, y, p); + + if (areaId == AREA_TURN) { + isActive = true; + cx = (float)x * 0.5f; + cy = (float)y * -0.5f; + break; + } + } + + if (MODE_OFFSET == mode) { + //float dt = getDeltaTime(); + //const float MaxTurnX = 250.0f; + //const float MaxTurnY = 200.0f; + //float cx = isActive? Controller::getX(cid) : cxO * 0.7f; + //float cy = isActive? Controller::getY(cid) : cyO * 0.7f; + //dx = linearTransform( cx, 0.1f, MaxTurnX ) * dt; + //dy = linearTransform( cy, 0.1f, MaxTurnY ) * dt; + //cxO = cx; + //cyO = cy; + } else + if (MODE_DELTA == mode && (wasActive || isActive)) { +// const float dt = getDeltaTime(); +// const float MaxTurnX = 100.0f; +// const float MaxTurnY = 100.0f; + const float DeadZone = 0;//0.25f * dt;//0.02f; + + if (!wasActive) { + cxO = cx; + cyO = cy; + } + if (isActive) { + dx = linearTransform(cx - cxO, DeadZone);// * MaxTurnX; + dy = linearTransform(cy - cyO, DeadZone);// * MaxTurnY; + cxO = cx; + cyO = cy; + } + } + + wasActive = isActive; + return TurnDelta(dx, -dy); + } + + int mode; +private: + int cid; + float cxO, cyO; + bool wasActive; + + TouchAreaModel _model; + + static const int AREA_TURN = 100; +}; + diff --git a/src/client/player/input/touchscreen/TouchscreenInput.h b/src/client/player/input/touchscreen/TouchscreenInput.h index 515f0d8..3bd20d3 100755 --- a/src/client/player/input/touchscreen/TouchscreenInput.h +++ b/src/client/player/input/touchscreen/TouchscreenInput.h @@ -1,80 +1,78 @@ -#ifndef NET_MINECRAFT_CLIENT_PLAYER_INPUT_TOUCHSCREEN_TouchscreenInput_H__ -#define NET_MINECRAFT_CLIENT_PLAYER_INPUT_TOUCHSCREEN_TouchscreenInput_H__ - -//package net.minecraft.client.player; - -#include "../IMoveInput.h" -#include "../../../gui/GuiComponent.h" -#include "TouchAreaModel.h" -#include "../../../renderer/RenderChunk.h" - -class Options; -class Player; -class Minecraft; -class PolygonArea; - -// @todo: extract a separate MoveInput (-> merge XperiaPlayInput) -class TouchscreenInput_TestFps: public IMoveInput, - public GuiComponent -{ -public: - static const int KEY_UP = 0; - static const int KEY_DOWN = 1; - static const int KEY_LEFT = 2; - static const int KEY_RIGHT = 3; - static const int KEY_JUMP = 4; - static const int KEY_SNEAK = 5; - static const int KEY_CRAFT = 6; - static const int NumKeys = 7; - - TouchscreenInput_TestFps(Minecraft* mc, Options* options); - ~TouchscreenInput_TestFps(); - - void onConfigChanged(const Config& c); - - void tick(Player* player); - void render(float a); - - void setKey(int key, bool state); - void releaseAllKeys(); - - const RectangleArea& getRectangleArea(); - const RectangleArea& getPauseRectangleArea(); - -private: - void clear(); - - RectangleArea _boundingRectangle; - - bool _keys[NumKeys]; - Options* _options; - - bool _pressedJump; - bool _forward; - bool _northJump; - bool _renderFlightImage; - TouchAreaModel _model; - Minecraft* _minecraft; - - RectangleArea* aLeft; - RectangleArea* aRight; - RectangleArea* aUp; - RectangleArea* aDown; - RectangleArea* aPause; - RectangleArea* aChat; - //RectangleArea* aUpJump; - RectangleArea* aJump; - RectangleArea* aUpLeft; - RectangleArea* aUpRight; - bool _pauseIsDown; - - RenderChunk _render; - bool _allowHeightChange; - float _sneakTapTime; - - bool _buttons[8]; - bool isButtonDown(int areaId); - void rebuild(); -}; - -#endif /*NET_MINECRAFT_CLIENT_PLAYER_INPUT_TOUCHSCREEN_TouchscreenInput_H__*/ +#pragma once + +//package net.minecraft.client.player; + +#include "../IMoveInput.h" +#include "../../../gui/GuiComponent.h" +#include "TouchAreaModel.h" +#include "../../../renderer/RenderChunk.h" + +class Options; +class Player; +class Minecraft; +class PolygonArea; + +// @todo: extract a separate MoveInput (-> merge XperiaPlayInput) +class TouchscreenInput_TestFps: public IMoveInput, + public GuiComponent +{ +public: + static const int KEY_UP = 0; + static const int KEY_DOWN = 1; + static const int KEY_LEFT = 2; + static const int KEY_RIGHT = 3; + static const int KEY_JUMP = 4; + static const int KEY_SNEAK = 5; + static const int KEY_CRAFT = 6; + static const int NumKeys = 7; + + TouchscreenInput_TestFps(Minecraft* mc, Options* options); + ~TouchscreenInput_TestFps(); + + void onConfigChanged(const Config& c); + + void tick(Player* player); + void render(float a); + + void setKey(int key, bool state); + void releaseAllKeys(); + + const RectangleArea& getRectangleArea(); + const RectangleArea& getPauseRectangleArea(); + +private: + void clear(); + + RectangleArea _boundingRectangle; + + bool _keys[NumKeys]; + Options* _options; + + bool _pressedJump; + bool _forward; + bool _northJump; + bool _renderFlightImage; + TouchAreaModel _model; + Minecraft* _minecraft; + + RectangleArea* aLeft; + RectangleArea* aRight; + RectangleArea* aUp; + RectangleArea* aDown; + RectangleArea* aPause; + RectangleArea* aChat; + //RectangleArea* aUpJump; + RectangleArea* aJump; + RectangleArea* aUpLeft; + RectangleArea* aUpRight; + bool _pauseIsDown; + + RenderChunk _render; + bool _allowHeightChange; + float _sneakTapTime; + + bool _buttons[8]; + bool isButtonDown(int areaId); + void rebuild(); +}; + diff --git a/src/client/renderer/Chunk.h b/src/client/renderer/Chunk.h index 569e078..a532da6 100755 --- a/src/client/renderer/Chunk.h +++ b/src/client/renderer/Chunk.h @@ -1,74 +1,72 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__Chunk_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__Chunk_H__ - -//package net.minecraft.client.renderer; - -#include "RenderChunk.h" -#include "../../world/phys/AABB.h" - -class Level; -class Entity; -class Culler; -class Tesselator; - -// @note: TileEntity stuff is stripped away -class Chunk -{ - static const int NumLayers = 3; -public: - Chunk(Level* level_, int x, int y, int z, int size, int lists_, GLuint* ptrBuf = NULL); - - void setPos(int x, int y, int z); - - void rebuild(); - void setDirty(); - void setClean(); - bool isDirty(); - void reset(); - - float distanceToSqr(const Entity* player) const; - float squishedDistanceToSqr(const Entity* player) const; - - //@todo @fix - int getAllLists(int displayLists[], int p, int layer); - int getList(int layer); - - RenderChunk& getRenderChunk(int layer); - - bool isEmpty(); - void cull(Culler* culler); - - void renderBB(); - static void resetUpdates(); - -private: - void translateToPos(); -public: - Level* level; - - static int updates;// = 0; - - int x, y, z, xs, ys, zs; - bool empty[NumLayers]; - int xm, ym, zm; - float radius; - AABB bb; - - int id; - bool visible; - bool occlusion_visible; - bool occlusion_querying; - int occlusion_id; - bool skyLit; - - RenderChunk renderChunk[NumLayers]; -private: - Tesselator& t; - int lists; - GLuint* vboBuffers; - bool compiled; - bool dirty; - bool _empty; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__Chunk_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include "RenderChunk.h" +#include "../../world/phys/AABB.h" + +class Level; +class Entity; +class Culler; +class Tesselator; + +// @note: TileEntity stuff is stripped away +class Chunk +{ + static const int NumLayers = 3; +public: + Chunk(Level* level_, int x, int y, int z, int size, int lists_, GLuint* ptrBuf = NULL); + + void setPos(int x, int y, int z); + + void rebuild(); + void setDirty(); + void setClean(); + bool isDirty(); + void reset(); + + float distanceToSqr(const Entity* player) const; + float squishedDistanceToSqr(const Entity* player) const; + + //@todo @fix + int getAllLists(int displayLists[], int p, int layer); + int getList(int layer); + + RenderChunk& getRenderChunk(int layer); + + bool isEmpty(); + void cull(Culler* culler); + + void renderBB(); + static void resetUpdates(); + +private: + void translateToPos(); +public: + Level* level; + + static int updates;// = 0; + + int x, y, z, xs, ys, zs; + bool empty[NumLayers]; + int xm, ym, zm; + float radius; + AABB bb; + + int id; + bool visible; + bool occlusion_visible; + bool occlusion_querying; + int occlusion_id; + bool skyLit; + + RenderChunk renderChunk[NumLayers]; +private: + Tesselator& t; + int lists; + GLuint* vboBuffers; + bool compiled; + bool dirty; + bool _empty; +}; + diff --git a/src/client/renderer/ChunkRenderer.h b/src/client/renderer/ChunkRenderer.h index 8f4cef2..91b2b8b 100755 --- a/src/client/renderer/ChunkRenderer.h +++ b/src/client/renderer/ChunkRenderer.h @@ -1,22 +1,20 @@ -#ifndef CHUNKRENDERER_H__ -#define CHUNKRENDERER_H__ - -#include "gles.h" -#include "../../world/level/Region.h" - -class ChunkRenderer { -public: - ChunkRenderer(const Region& region) - : r(region) - { - } - - void render() { - //glTranslate(r.xc1, - } - -private: - const Region& r; -}; - -#endif /*CHUNKRENDERER_H__*/ +#pragma once + +#include "gles.h" +#include "../../world/level/Region.h" + +class ChunkRenderer { +public: + ChunkRenderer(const Region& region) + : r(region) + { + } + + void render() { + //glTranslate(r.xc1, + } + +private: + const Region& r; +}; + diff --git a/src/client/renderer/Color4.h b/src/client/renderer/Color4.h index 6b34fea..c37b5c3 100755 --- a/src/client/renderer/Color4.h +++ b/src/client/renderer/Color4.h @@ -1,53 +1,51 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__Color4_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__Color4_H__ - -class Color4 -{ -public: - GLfloat r; - GLfloat g; - GLfloat b; - GLfloat a; - - Color4(GLfloat r_, GLfloat g_, GLfloat b_, GLfloat a_ = 0) - : r(r_), - g(g_), - b(b_), - a(a_) - {} - - Color4(int hex) { - r = ((hex>>16)& 255) / 255.0f; - g = ((hex>>8) & 255) / 255.0f; - b = (hex&255) / 255.0f; - a = (hex >> 24) / 255.0f; - } - - void add(GLfloat val, bool modifyAlpha) { - r += val; - g += val; - b += val; - if (modifyAlpha) a += val; - sanitize(); - } - void mul(GLfloat val, bool modifyAlpha) { - r *= val; - g *= val; - b *= val; - if (modifyAlpha) a *= val; - sanitize(); - } -private: - void sanitize() { - range(r); - range(g); - range(b); - range(a); - } - inline void range(GLfloat& v) { - if (v < 0) v = 0; - if (v > 1) v = 1; - } -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__Color4_H__*/ +#pragma once + +class Color4 +{ +public: + GLfloat r; + GLfloat g; + GLfloat b; + GLfloat a; + + Color4(GLfloat r_, GLfloat g_, GLfloat b_, GLfloat a_ = 0) + : r(r_), + g(g_), + b(b_), + a(a_) + {} + + Color4(int hex) { + r = ((hex>>16)& 255) / 255.0f; + g = ((hex>>8) & 255) / 255.0f; + b = (hex&255) / 255.0f; + a = (hex >> 24) / 255.0f; + } + + void add(GLfloat val, bool modifyAlpha) { + r += val; + g += val; + b += val; + if (modifyAlpha) a += val; + sanitize(); + } + void mul(GLfloat val, bool modifyAlpha) { + r *= val; + g *= val; + b *= val; + if (modifyAlpha) a *= val; + sanitize(); + } +private: + void sanitize() { + range(r); + range(g); + range(b); + range(a); + } + inline void range(GLfloat& v) { + if (v < 0) v = 0; + if (v > 1) v = 1; + } +}; + diff --git a/src/client/renderer/DirtyChunkSorter.h b/src/client/renderer/DirtyChunkSorter.h index 2a5a690..9f2e1d4 100755 --- a/src/client/renderer/DirtyChunkSorter.h +++ b/src/client/renderer/DirtyChunkSorter.h @@ -1,35 +1,33 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__DirtyChunkSorter_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__DirtyChunkSorter_H__ - -//package net.minecraft.client.renderer; - -#include "../../world/entity/Entity.h" -#include "Chunk.h" - -class DirtyChunkSorter -{ - Entity* cameraEntity; - -public: - DirtyChunkSorter(Entity* cameraEntity) { - this->cameraEntity = cameraEntity; - } - - // @attn: c0 > c1 - bool operator() (Chunk* c0, Chunk* c1) { - bool i0 = c0->visible; - bool i1 = c1->visible; - if (i0 && !i1) return false; // 1; - if (i1 && !i0) return true; // -1; - - float d0 = c0->distanceToSqr(cameraEntity); - float d1 = c1->distanceToSqr(cameraEntity); - - if (d0 < d1) return false; // 1; - if (d0 > d1) return true; // -1; - - return c0->id > c1->id;// ? -1 : 1; - } -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__DirtyChunkSorter_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include "../../world/entity/Entity.h" +#include "Chunk.h" + +class DirtyChunkSorter +{ + Entity* cameraEntity; + +public: + DirtyChunkSorter(Entity* cameraEntity) { + this->cameraEntity = cameraEntity; + } + + // @attn: c0 > c1 + bool operator() (Chunk* c0, Chunk* c1) { + bool i0 = c0->visible; + bool i1 = c1->visible; + if (i0 && !i1) return false; // 1; + if (i1 && !i0) return true; // -1; + + float d0 = c0->distanceToSqr(cameraEntity); + float d1 = c1->distanceToSqr(cameraEntity); + + if (d0 < d1) return false; // 1; + if (d0 > d1) return true; // -1; + + return c0->id > c1->id;// ? -1 : 1; + } +}; + diff --git a/src/client/renderer/DistanceChunkSorter.h b/src/client/renderer/DistanceChunkSorter.h index c4bfa9d..5ab4158 100755 --- a/src/client/renderer/DistanceChunkSorter.h +++ b/src/client/renderer/DistanceChunkSorter.h @@ -1,27 +1,25 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__DistanceChunkSorter_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__DistanceChunkSorter_H__ - -//package net.minecraft.client.renderer; - -#include "../../world/entity/Entity.h" -#include "Chunk.h" - -class DistanceChunkSorter -{ - Entity* player; - -public: - DistanceChunkSorter(Entity* player) { - this->player = player; - } - - bool operator() (const Chunk* c0, const Chunk* c1) { - float d0 = c0->distanceToSqr(player); - float d1 = c1->distanceToSqr(player); - if (d0 > 32 * 32 && c0->y < 64) d0 *= 10.0f; - if (d1 > 32 * 32 && c1->y < 64) d1 *= 10.0f; - return d0 < d1;//? -1 : 1; - } -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__DistanceChunkSorter_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include "../../world/entity/Entity.h" +#include "Chunk.h" + +class DistanceChunkSorter +{ + Entity* player; + +public: + DistanceChunkSorter(Entity* player) { + this->player = player; + } + + bool operator() (const Chunk* c0, const Chunk* c1) { + float d0 = c0->distanceToSqr(player); + float d1 = c1->distanceToSqr(player); + if (d0 > 32 * 32 && c0->y < 64) d0 *= 10.0f; + if (d1 > 32 * 32 && c1->y < 64) d1 *= 10.0f; + return d0 < d1;//? -1 : 1; + } +}; + diff --git a/src/client/renderer/EntityTileRenderer.h b/src/client/renderer/EntityTileRenderer.h index 9902d0f..1fb28dc 100755 --- a/src/client/renderer/EntityTileRenderer.h +++ b/src/client/renderer/EntityTileRenderer.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__EntityTileRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__EntityTileRenderer_H__ - -//package net.minecraft.client.renderer; - -#include "../../world/level/tile/entity/ChestTileEntity.h" -#include "tileentity/TileEntityRenderDispatcher.h" - -class Tile; - -class EntityTileRenderer -{ -public: - static EntityTileRenderer* instance; - - void render(Tile* tile, int data, float brightness); - - ChestTileEntity chest; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__EntityTileRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include "../../world/level/tile/entity/ChestTileEntity.h" +#include "tileentity/TileEntityRenderDispatcher.h" + +class Tile; + +class EntityTileRenderer +{ +public: + static EntityTileRenderer* instance; + + void render(Tile* tile, int data, float brightness); + + ChestTileEntity chest; +}; + diff --git a/src/client/renderer/GameRenderer.h b/src/client/renderer/GameRenderer.h index ca8d7ec..775d6c1 100755 --- a/src/client/renderer/GameRenderer.h +++ b/src/client/renderer/GameRenderer.h @@ -1,117 +1,115 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__GameRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__GameRenderer_H__ - -//package net.minecraft.client.renderer; - -#include "gles.h" -#include -#include "../../util/SmoothFloat.h" -#include "../../world/phys/Vec3.h" -#include "../gui/components/ImageButton.h" - -class Minecraft; -class Entity; -class ItemInHandRenderer; -class LevelRenderer; -class GameRenderer -{ -public: - GameRenderer(Minecraft* mc_); - ~GameRenderer(); - - void pick(float a); - - void updateAllChunks(); - - void zoomRegion(float zoom, float xa, float ya); - void unZoomRegion(); - void setupGuiScreen(bool clearColorBuffer); - - void tick(int nTick, int maxTick); - void render(float a); - void renderLevel(float a); - void renderItemInHand(float a, int eye); - - void onGraphicsReset(); - - void setupCamera(float a, int eye); - void moveCameraToPlayer(float a); - - void setupClearColor(float a); - float getFov(float a, bool applyEffects); -private: - void setupFog(int i); - - void tickFov(); - - - void bobHurt(float a); - void bobView(float a); - - bool updateFreeformPickDirection(float a, Vec3& outDir); - void prepareAndRenderClouds(LevelRenderer* levelRenderer, float a); - -public: - ItemInHandRenderer* itemInHandRenderer; - -private: - Minecraft* mc; - - float renderDistance; - int _tick; - Vec3 pickDirection; - - // smooth camera movement - SmoothFloat smoothTurnX; - SmoothFloat smoothTurnY; - - // // third-person distance etc - // SmoothFloat smoothDistance = /*new*/ SmoothFloat(); - // SmoothFloat smoothRotation = /*new*/ SmoothFloat(); - // SmoothFloat smoothTilt = /*new*/ SmoothFloat(); - // SmoothFloat smoothRoll = /*new*/ SmoothFloat(); - - float thirdDistance; - float thirdDistanceO; - float thirdRotation; - float thirdRotationO; - float thirdTilt; - float thirdTiltO; - - // zoom - float zoom; - float zoom_x; - float zoom_y; - - // fov modification - float fov, oFov; - float fovOffset; - float fovOffsetO; - float _setupCameraFov; - - // roll modification - float cameraRoll; - float cameraRollO; - - float fr; - float fg; - float fb; - - float fogBrO, fogBr; - - float _rotX; - float _rotY; - float _rotXlast; - float _rotYlast; - float _lastTickT; - - void saveMatrices(); - float lastProjMatrix[16]; - float lastModelMatrix[16]; - - // Scissor area that Minecraft::screen defines - bool useScreenScissor; - IntRectangle screenScissorArea; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__GameRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include "gles.h" +#include +#include "../../util/SmoothFloat.h" +#include "../../world/phys/Vec3.h" +#include "../gui/components/ImageButton.h" + +class Minecraft; +class Entity; +class ItemInHandRenderer; +class LevelRenderer; +class GameRenderer +{ +public: + GameRenderer(Minecraft* mc_); + ~GameRenderer(); + + void pick(float a); + + void updateAllChunks(); + + void zoomRegion(float zoom, float xa, float ya); + void unZoomRegion(); + void setupGuiScreen(bool clearColorBuffer); + + void tick(int nTick, int maxTick); + void render(float a); + void renderLevel(float a); + void renderItemInHand(float a, int eye); + + void onGraphicsReset(); + + void setupCamera(float a, int eye); + void moveCameraToPlayer(float a); + + void setupClearColor(float a); + float getFov(float a, bool applyEffects); +private: + void setupFog(int i); + + void tickFov(); + + + void bobHurt(float a); + void bobView(float a); + + bool updateFreeformPickDirection(float a, Vec3& outDir); + void prepareAndRenderClouds(LevelRenderer* levelRenderer, float a); + +public: + ItemInHandRenderer* itemInHandRenderer; + +private: + Minecraft* mc; + + float renderDistance; + int _tick; + Vec3 pickDirection; + + // smooth camera movement + SmoothFloat smoothTurnX; + SmoothFloat smoothTurnY; + + // // third-person distance etc + // SmoothFloat smoothDistance = /*new*/ SmoothFloat(); + // SmoothFloat smoothRotation = /*new*/ SmoothFloat(); + // SmoothFloat smoothTilt = /*new*/ SmoothFloat(); + // SmoothFloat smoothRoll = /*new*/ SmoothFloat(); + + float thirdDistance; + float thirdDistanceO; + float thirdRotation; + float thirdRotationO; + float thirdTilt; + float thirdTiltO; + + // zoom + float zoom; + float zoom_x; + float zoom_y; + + // fov modification + float fov, oFov; + float fovOffset; + float fovOffsetO; + float _setupCameraFov; + + // roll modification + float cameraRoll; + float cameraRollO; + + float fr; + float fg; + float fb; + + float fogBrO, fogBr; + + float _rotX; + float _rotY; + float _rotXlast; + float _rotYlast; + float _lastTickT; + + void saveMatrices(); + float lastProjMatrix[16]; + float lastModelMatrix[16]; + + // Scissor area that Minecraft::screen defines + bool useScreenScissor; + IntRectangle screenScissorArea; +}; + diff --git a/src/client/renderer/ItemInHandRenderer.h b/src/client/renderer/ItemInHandRenderer.h index 22e89b3..65e7033 100755 --- a/src/client/renderer/ItemInHandRenderer.h +++ b/src/client/renderer/ItemInHandRenderer.h @@ -1,57 +1,55 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__ItemInHandRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__ItemInHandRenderer_H__ - -//package net.minecraft.client.renderer; - -#include "TileRenderer.h" -#include "../renderer/RenderChunk.h" -#include "../../world/item/ItemInstance.h" - -class Minecraft; - -typedef struct RenderCall { - int itemId; - RenderChunk chunk; - std::string texture; - bool isFlat; -} RenderCall; - - -class ItemInHandRenderer -{ -public: - ItemInHandRenderer(Minecraft* mc); - - void tick(); - - void render(float a); - void renderItem(Mob* player, ItemInstance* item); - void renderScreenEffect(float a); - - void itemPlaced(); - void itemUsed(); - - void onGraphicsReset(); - -private: - void renderTex(float a, int tex); - void renderWater(float a); - void renderFire(float a); - -private: - int lastIconRendered; - int lastItemRendered; - int lastSlot; - ItemInstance item; - - Minecraft* mc; - //ItemInstance* selectedItem; - float height; - float oHeight; - TileRenderer tileRenderer; - - static const int MaxNumRenderObjects = 512; - RenderCall renderObjects[MaxNumRenderObjects]; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__ItemInHandRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include "TileRenderer.h" +#include "../renderer/RenderChunk.h" +#include "../../world/item/ItemInstance.h" + +class Minecraft; + +typedef struct RenderCall { + int itemId; + RenderChunk chunk; + std::string texture; + bool isFlat; +} RenderCall; + + +class ItemInHandRenderer +{ +public: + ItemInHandRenderer(Minecraft* mc); + + void tick(); + + void render(float a); + void renderItem(Mob* player, ItemInstance* item); + void renderScreenEffect(float a); + + void itemPlaced(); + void itemUsed(); + + void onGraphicsReset(); + +private: + void renderTex(float a, int tex); + void renderWater(float a); + void renderFire(float a); + +private: + int lastIconRendered; + int lastItemRendered; + int lastSlot; + ItemInstance item; + + Minecraft* mc; + //ItemInstance* selectedItem; + float height; + float oHeight; + TileRenderer tileRenderer; + + static const int MaxNumRenderObjects = 512; + RenderCall renderObjects[MaxNumRenderObjects]; +}; + diff --git a/src/client/renderer/LevelRenderer.h b/src/client/renderer/LevelRenderer.h index 73487cb..d646ef2 100755 --- a/src/client/renderer/LevelRenderer.h +++ b/src/client/renderer/LevelRenderer.h @@ -1,130 +1,128 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__LevelRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__LevelRenderer_H__ - -//package net.minecraft.client.renderer; - -#include "../../world/level/LevelListener.h" -#include "../../world/phys/Vec3.h" -#include "RenderList.h" -#include "gles.h" -#include - -class MinecraftClient; -class Textures; -class Culler; -class Chunk; -class TileRenderer; -class Level; -class Mob; -class Player; -class HitResult; -class AABB; -class TripodCamera; - -class LevelRenderer: public LevelListener -{ -public: - static const int CHUNK_SIZE; - static const int MAX_VISIBLE_REBUILDS_PER_FRAME = 3; - static const int MAX_INVISIBLE_REBUILDS_PER_FRAME = 1; - - float xOld; - float yOld; - float zOld; - float destroyProgress; - - LevelRenderer(MinecraftClient& mc); - ~LevelRenderer(); - - void setLevel(Level* level); - void allChanged(); - - int render(Mob* player, int layer, float alpha); - void renderDebug(const AABB& b, float a) const; - - void renderSky(float alpha); - void renderClouds(float alpha); - void renderEntities(Vec3 cam, Culler* culler, float a); - void renderSameAsLast(int layer, float alpha); - void renderHit(Player* player, const HitResult& h, int mode, /*ItemInstance*/void* inventoryItem, float a); - void renderHitOutline(Player* player, const HitResult& h, int mode, /*ItemInstance*/void* inventoryItem, float a); - void renderHitSelect(Player* player, const HitResult& h, int mode, /*ItemInstance*/void* inventoryItem, float a); - void entityAdded(Entity* entity); - - void tick(); - bool updateDirtyChunks(Mob* player, bool force); - void setDirty(int x0, int y0, int z0, int x1, int y1, int z1); - void tileChanged(int x, int y, int z); - void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1); - void cull(Culler* culler, float a); - void skyColorChanged(); - - //void addParticle(ParticleType::Id name, float x, float y, float z, float xa, float ya, float za, int data); - void addParticle(const std::string& name, float x, float y, float z, float xa, float ya, float za, int data); - void playSound(const std::string& name, float x, float y, float z, float volume, float pitch); - void takePicture(TripodCamera* cam, Entity* entity); - - void levelEvent(Player* source, int type, int x, int y, int z, int data); - - std::string gatherStats1(); - - void render(const AABB& b) const; - void onGraphicsReset(); -private: - void generateSky(); - - int renderChunks(int from, int to, int layer, float alpha); - void resortChunks(int xc, int yc, int zc); - void deleteChunks(); - //void checkQueryResults(int from, int to); - inline int getLinearCoord(int x, int y, int z) { - return (z * yChunks + y) * xChunks + x; - } - int noEntityRenderFrames; - int totalEntities; - int renderedEntities; - int culledEntities; - - std::vector _renderChunks; - - int cullStep; - //static const int renderListsLength = 4; - RenderList renderList;//[renderListsLength]; - - int totalChunks, offscreenChunks, occludedChunks, renderedChunks, emptyChunks; - int chunkFixOffs; - - int xMinChunk, yMinChunk, zMinChunk; - int xMaxChunk, yMaxChunk, zMaxChunk; - - Level* level; - std::vector dirtyChunks; - - Chunk** chunks; - Chunk** sortedChunks; - int chunksLength; -public: - TileRenderer* tileRenderer; -private: - int xChunks, yChunks, zChunks; - int chunkLists; - Minecraft* mc; - - bool occlusionCheck; - int lastViewDistance; - - int ticks; - int starList, skyList, darkList; - - int numListsOrBuffers; - GLuint* chunkBuffers; - GLuint skyBuffer; - int skyVertexCount; - -// /*public*/ std::vector renderableTileEntities; - Textures* textures; -// /*private*/ TileRenderer tileRenderer; -// /*private*/ IntBuffer occlusionCheckIds; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__LevelRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include "../../world/level/LevelListener.h" +#include "../../world/phys/Vec3.h" +#include "RenderList.h" +#include "gles.h" +#include + +class MinecraftClient; +class Textures; +class Culler; +class Chunk; +class TileRenderer; +class Level; +class Mob; +class Player; +class HitResult; +class AABB; +class TripodCamera; + +class LevelRenderer: public LevelListener +{ +public: + static const int CHUNK_SIZE; + static const int MAX_VISIBLE_REBUILDS_PER_FRAME = 3; + static const int MAX_INVISIBLE_REBUILDS_PER_FRAME = 1; + + float xOld; + float yOld; + float zOld; + float destroyProgress; + + LevelRenderer(MinecraftClient& mc); + ~LevelRenderer(); + + void setLevel(Level* level); + void allChanged(); + + int render(Mob* player, int layer, float alpha); + void renderDebug(const AABB& b, float a) const; + + void renderSky(float alpha); + void renderClouds(float alpha); + void renderEntities(Vec3 cam, Culler* culler, float a); + void renderSameAsLast(int layer, float alpha); + void renderHit(Player* player, const HitResult& h, int mode, /*ItemInstance*/void* inventoryItem, float a); + void renderHitOutline(Player* player, const HitResult& h, int mode, /*ItemInstance*/void* inventoryItem, float a); + void renderHitSelect(Player* player, const HitResult& h, int mode, /*ItemInstance*/void* inventoryItem, float a); + void entityAdded(Entity* entity); + + void tick(); + bool updateDirtyChunks(Mob* player, bool force); + void setDirty(int x0, int y0, int z0, int x1, int y1, int z1); + void tileChanged(int x, int y, int z); + void setTilesDirty(int x0, int y0, int z0, int x1, int y1, int z1); + void cull(Culler* culler, float a); + void skyColorChanged(); + + //void addParticle(ParticleType::Id name, float x, float y, float z, float xa, float ya, float za, int data); + void addParticle(const std::string& name, float x, float y, float z, float xa, float ya, float za, int data); + void playSound(const std::string& name, float x, float y, float z, float volume, float pitch); + void takePicture(TripodCamera* cam, Entity* entity); + + void levelEvent(Player* source, int type, int x, int y, int z, int data); + + std::string gatherStats1(); + + void render(const AABB& b) const; + void onGraphicsReset(); +private: + void generateSky(); + + int renderChunks(int from, int to, int layer, float alpha); + void resortChunks(int xc, int yc, int zc); + void deleteChunks(); + //void checkQueryResults(int from, int to); + inline int getLinearCoord(int x, int y, int z) { + return (z * yChunks + y) * xChunks + x; + } + int noEntityRenderFrames; + int totalEntities; + int renderedEntities; + int culledEntities; + + std::vector _renderChunks; + + int cullStep; + //static const int renderListsLength = 4; + RenderList renderList;//[renderListsLength]; + + int totalChunks, offscreenChunks, occludedChunks, renderedChunks, emptyChunks; + int chunkFixOffs; + + int xMinChunk, yMinChunk, zMinChunk; + int xMaxChunk, yMaxChunk, zMaxChunk; + + Level* level; + std::vector dirtyChunks; + + Chunk** chunks; + Chunk** sortedChunks; + int chunksLength; +public: + TileRenderer* tileRenderer; +private: + int xChunks, yChunks, zChunks; + int chunkLists; + Minecraft* mc; + + bool occlusionCheck; + int lastViewDistance; + + int ticks; + int starList, skyList, darkList; + + int numListsOrBuffers; + GLuint* chunkBuffers; + GLuint skyBuffer; + int skyVertexCount; + +// /*public*/ std::vector renderableTileEntities; + Textures* textures; +// /*private*/ TileRenderer tileRenderer; +// /*private*/ IntBuffer occlusionCheckIds; +}; + diff --git a/src/client/renderer/RenderChunk.h b/src/client/renderer/RenderChunk.h index dc582e4..adc452f 100755 --- a/src/client/renderer/RenderChunk.h +++ b/src/client/renderer/RenderChunk.h @@ -1,24 +1,22 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__RenderChunk_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__RenderChunk_H__ - -//package net.minecraft.client.renderer; - -#include "gles.h" -#include "../../world/phys/Vec3.h" - -class RenderChunk -{ -public: - RenderChunk(); - RenderChunk(GLuint vboId_, int vertexCount_); - - GLuint vboId; - GLsizei vertexCount; - int id; - Vec3 pos; - -private: - static int runningId; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__RenderChunk_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include "gles.h" +#include "../../world/phys/Vec3.h" + +class RenderChunk +{ +public: + RenderChunk(); + RenderChunk(GLuint vboId_, int vertexCount_); + + GLuint vboId; + GLsizei vertexCount; + int id; + Vec3 pos; + +private: + static int runningId; +}; + diff --git a/src/client/renderer/RenderChunkHandler.h b/src/client/renderer/RenderChunkHandler.h index f31f345..5c785bb 100755 --- a/src/client/renderer/RenderChunkHandler.h +++ b/src/client/renderer/RenderChunkHandler.h @@ -1,23 +1,21 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__RenderChunkHandler_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__RenderChunkHandler_H__ - -#include -#include "RenderChunk.h" - -typedef std::vector ChunkList; - -class RenderChunkHandler -{ -public: - int vboCount; - ChunkList chunks; - - RenderChunkHandler() { - vboCount = Tesselator::getVboCount(); - } - - void render() { - } -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__RenderChunkHandler_H__*/ +#pragma once + +#include +#include "RenderChunk.h" + +typedef std::vector ChunkList; + +class RenderChunkHandler +{ +public: + int vboCount; + ChunkList chunks; + + RenderChunkHandler() { + vboCount = Tesselator::getVboCount(); + } + + void render() { + } +}; + diff --git a/src/client/renderer/RenderList.h b/src/client/renderer/RenderList.h index c8c9270..7a008cc 100755 --- a/src/client/renderer/RenderList.h +++ b/src/client/renderer/RenderList.h @@ -1,41 +1,39 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__RenderList_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__RenderList_H__ - -//package net.minecraft.client.renderer; - -class RenderChunk; - -class RenderList -{ - static const int MAX_NUM_OBJECTS = 1024 * 3; - -public: - RenderList(); - ~RenderList(); - - void init(float xOff, float yOff, float zOff); - - void add(int list); - void addR(const RenderChunk& chunk); - - inline void next() { ++listIndex; } - - void render(); - void renderChunks(); - - void clear(); - - - float xOff, yOff, zOff; - int* lists; - RenderChunk* rlists; - - int listIndex; - bool inited; - bool rendered; - -private: - int bufferLimit; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__RenderList_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +class RenderChunk; + +class RenderList +{ + static const int MAX_NUM_OBJECTS = 1024 * 3; + +public: + RenderList(); + ~RenderList(); + + void init(float xOff, float yOff, float zOff); + + void add(int list); + void addR(const RenderChunk& chunk); + + inline void next() { ++listIndex; } + + void render(); + void renderChunks(); + + void clear(); + + + float xOff, yOff, zOff; + int* lists; + RenderChunk* rlists; + + int listIndex; + bool inited; + bool rendered; + +private: + int bufferLimit; +}; + diff --git a/src/client/renderer/Tesselator.h b/src/client/renderer/Tesselator.h index 148dff0..d6d3c08 100755 --- a/src/client/renderer/Tesselator.h +++ b/src/client/renderer/Tesselator.h @@ -1,130 +1,128 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__Tesselator_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__Tesselator_H__ - -//package net.minecraft.client.renderer; - -#include -#include "RenderChunk.h" -#include "gles.h" -#include "VertecDecl.h" - -extern const int VertexSizeBytes; - -typedef VertexDeclPTC VERTEX; -typedef std::map IntGLMap; - - -class Tesselator -{ - static const int MAX_MEMORY_USE = 16 * 1024 * 1024; - static const int MAX_FLOATS = MAX_MEMORY_USE / 4 / 2; - - Tesselator(int size); - -public: - static const int ACCESS_DYNAMIC = 1; - static const int ACCESS_STATIC = 2; - - static Tesselator instance; - - ~Tesselator(); - - void init(); - void clear(); - - void begin(); - void begin(int mode); - void draw(); - RenderChunk end(bool useMine, int bufferId); - - void color(int c); - void color(int c, int alpha); - void color(float r, float g, float b); - void color(float r, float g, float b, float a); - void color(int r, int g, int b); - void color(int r, int g, int b, int a); - void color(char r, char g, char b); - void colorABGR( int c ); - - void normal(float x, float y, float z); - void voidBeginAndEndCalls(bool doVoid); - - void tex(float u, float v); - - void vertex(float x, float y, float z); - void vertexUV(float x, float y, float z, float u, float v); - - void scale2d(float x, float y); - void resetScale(); - - void noColor(); - void enableColor(); -private: - void setAccessMode(int mode); -public: - - void offset(float xo, float yo, float zo); - void offset(const Vec3& v); - void addOffset(float x, float y, float z); - void addOffset(const Vec3& v); - - int getVboCount(); - - int getColor(); - - inline void beginOverride() { - begin(); - voidBeginAndEndCalls(true); - } - inline void endOverrideAndDraw() { - voidBeginAndEndCalls(false); - draw(); - } - inline bool isOverridden() { - return _voidBeginEnd; - } - inline RenderChunk endOverride(int bufferId) { - voidBeginAndEndCalls(false); - return end(true, bufferId); - } - -private: - Tesselator(const Tesselator& rhs) {} - Tesselator& operator=(const Tesselator& rhs) { return *this; } - VERTEX* _varray; - - int vertices; - - float xo, yo, zo; - float u, v; - unsigned int _color; - int _normal; - float _sx, _sy; - - bool hasColor; - bool hasTexture; - bool hasNormal; - bool _noColor; - bool _voidBeginEnd; - - int p; - int count; - - bool tesselating; - - bool vboMode; - int vboCounts; - int vboId; - GLuint* vboIds; - - int size; - int totalSize; - int maxVertices; - - int mode; - int accessMode; - - IntGLMap map; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__Tesselator_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include +#include "RenderChunk.h" +#include "gles.h" +#include "VertecDecl.h" + +extern const int VertexSizeBytes; + +typedef VertexDeclPTC VERTEX; +typedef std::map IntGLMap; + + +class Tesselator +{ + static const int MAX_MEMORY_USE = 16 * 1024 * 1024; + static const int MAX_FLOATS = MAX_MEMORY_USE / 4 / 2; + + Tesselator(int size); + +public: + static const int ACCESS_DYNAMIC = 1; + static const int ACCESS_STATIC = 2; + + static Tesselator instance; + + ~Tesselator(); + + void init(); + void clear(); + + void begin(); + void begin(int mode); + void draw(); + RenderChunk end(bool useMine, int bufferId); + + void color(int c); + void color(int c, int alpha); + void color(float r, float g, float b); + void color(float r, float g, float b, float a); + void color(int r, int g, int b); + void color(int r, int g, int b, int a); + void color(char r, char g, char b); + void colorABGR( int c ); + + void normal(float x, float y, float z); + void voidBeginAndEndCalls(bool doVoid); + + void tex(float u, float v); + + void vertex(float x, float y, float z); + void vertexUV(float x, float y, float z, float u, float v); + + void scale2d(float x, float y); + void resetScale(); + + void noColor(); + void enableColor(); +private: + void setAccessMode(int mode); +public: + + void offset(float xo, float yo, float zo); + void offset(const Vec3& v); + void addOffset(float x, float y, float z); + void addOffset(const Vec3& v); + + int getVboCount(); + + int getColor(); + + inline void beginOverride() { + begin(); + voidBeginAndEndCalls(true); + } + inline void endOverrideAndDraw() { + voidBeginAndEndCalls(false); + draw(); + } + inline bool isOverridden() { + return _voidBeginEnd; + } + inline RenderChunk endOverride(int bufferId) { + voidBeginAndEndCalls(false); + return end(true, bufferId); + } + +private: + Tesselator(const Tesselator& rhs) {} + Tesselator& operator=(const Tesselator& rhs) { return *this; } + VERTEX* _varray; + + int vertices; + + float xo, yo, zo; + float u, v; + unsigned int _color; + int _normal; + float _sx, _sy; + + bool hasColor; + bool hasTexture; + bool hasNormal; + bool _noColor; + bool _voidBeginEnd; + + int p; + int count; + + bool tesselating; + + bool vboMode; + int vboCounts; + int vboId; + GLuint* vboIds; + + int size; + int totalSize; + int maxVertices; + + int mode; + int accessMode; + + IntGLMap map; +}; + diff --git a/src/client/renderer/TextureData.h b/src/client/renderer/TextureData.h index 2c97797..b336ffb 100755 --- a/src/client/renderer/TextureData.h +++ b/src/client/renderer/TextureData.h @@ -1,37 +1,35 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__TextureData_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__TextureData_H__ - -enum TextureFormat -{ - TEXF_UNCOMPRESSED_8888, - TEXF_UNCOMPRESSED_565, - TEXF_UNCOMPRESSED_5551, - TEXF_UNCOMPRESSED_4444, - TEXF_COMPRESSED_PVRTC_565, - TEXF_COMPRESSED_PVRTC_5551, - TEXF_COMPRESSED_PVRTC_4444 -}; - -typedef struct TextureData { - TextureData() - : w(0), - h(0), - data(nullptr), - numBytes(0), - transparent(true), - memoryHandledExternally(false), - format(TEXF_UNCOMPRESSED_8888), - identifier(-1) - {} - - int w, h; - unsigned char* data; - int numBytes; - bool transparent; - bool memoryHandledExternally; - - TextureFormat format; - int identifier; -} TextureData; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__Textures_H__*/ +#pragma once + +enum TextureFormat +{ + TEXF_UNCOMPRESSED_8888, + TEXF_UNCOMPRESSED_565, + TEXF_UNCOMPRESSED_5551, + TEXF_UNCOMPRESSED_4444, + TEXF_COMPRESSED_PVRTC_565, + TEXF_COMPRESSED_PVRTC_5551, + TEXF_COMPRESSED_PVRTC_4444 +}; + +typedef struct TextureData { + TextureData() + : w(0), + h(0), + data(nullptr), + numBytes(0), + transparent(true), + memoryHandledExternally(false), + format(TEXF_UNCOMPRESSED_8888), + identifier(-1) + {} + + int w, h; + unsigned char* data; + int numBytes; + bool transparent; + bool memoryHandledExternally; + + TextureFormat format; + int identifier; +} TextureData; + diff --git a/src/client/renderer/Textures.h b/src/client/renderer/Textures.h index a38b33e..af3f4df 100755 --- a/src/client/renderer/Textures.h +++ b/src/client/renderer/Textures.h @@ -1,80 +1,78 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__Textures_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__Textures_H__ - -//package net.minecraft.client.renderer; - -#include -#include -#include -#include -#include "gles.h" -#include "TextureData.h" - -#define TEXTURES_INVALID_ID -1 -#define TEXTURES_MIPMAP 0 - -class DynamicTexture; -class Options; -class AppPlatform; - -typedef GLuint TextureId; -typedef std::map TextureMap; -typedef std::map TextureImageMap; - -//@todo: Should probably delete the data buffers with image data -// after we've created an OpenGL-texture, and rewrite the -// getTemporaryTextureData() to actually load from file IF -// it's only read ~once anyway. -class Textures -{ -public: - Textures(Options& options, IPlatform& platform) : m_options(options), m_platform(platform) {} - ~Textures(); - - void addDynamicTexture(DynamicTexture* dynamicTexture); - - inline void bind(TextureId id) { - if (id != TEXTURES_INVALID_ID && lastBoundTexture != id) { - glBindTexture2(GL_TEXTURE_2D, id); - lastBoundTexture = id; - ++textureChanges; - } else if (id == TEXTURES_INVALID_ID){ - LOGI("invalidId!\n"); - } - } - - TextureId loadTexture(const std::string& resourceName, bool inTextureFolder = true); - TextureId loadAndBindTexture(const std::string& resourceName); - - TextureId assignTexture(const std::string& resourceName, const TextureData& img); - const TextureData* getTemporaryTextureData(TextureId id); - - void tick(bool uploadToGraphicsCard); - - void clear(); - void reloadAll(); - - inline static bool isTextureIdValid(TextureId t) { return t != TEXTURES_INVALID_ID; } - -private: - int smoothBlend(int c0, int c1); - int crispBlend(int c0, int c1); - -public: - static int textureChanges; - -private: - TextureMap idMap; - TextureImageMap loadedImages; - - Options& m_options; - IPlatform& m_platform; - - bool clamp = false; - bool blur = false; - - int lastBoundTexture = TEXTURES_INVALID_ID; - std::vector dynamicTextures; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__Textures_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +#include +#include +#include +#include +#include "gles.h" +#include "TextureData.h" + +#define TEXTURES_INVALID_ID -1 +#define TEXTURES_MIPMAP 0 + +class DynamicTexture; +class Options; +class AppPlatform; + +typedef GLuint TextureId; +typedef std::map TextureMap; +typedef std::map TextureImageMap; + +//@todo: Should probably delete the data buffers with image data +// after we've created an OpenGL-texture, and rewrite the +// getTemporaryTextureData() to actually load from file IF +// it's only read ~once anyway. +class Textures +{ +public: + Textures(Options& options, IPlatform& platform) : m_options(options), m_platform(platform) {} + ~Textures(); + + void addDynamicTexture(DynamicTexture* dynamicTexture); + + inline void bind(TextureId id) { + if (id != TEXTURES_INVALID_ID && lastBoundTexture != id) { + glBindTexture2(GL_TEXTURE_2D, id); + lastBoundTexture = id; + ++textureChanges; + } else if (id == TEXTURES_INVALID_ID){ + LOGI("invalidId!\n"); + } + } + + TextureId loadTexture(const std::string& resourceName, bool inTextureFolder = true); + TextureId loadAndBindTexture(const std::string& resourceName); + + TextureId assignTexture(const std::string& resourceName, const TextureData& img); + const TextureData* getTemporaryTextureData(TextureId id); + + void tick(bool uploadToGraphicsCard); + + void clear(); + void reloadAll(); + + inline static bool isTextureIdValid(TextureId t) { return t != TEXTURES_INVALID_ID; } + +private: + int smoothBlend(int c0, int c1); + int crispBlend(int c0, int c1); + +public: + static int textureChanges; + +private: + TextureMap idMap; + TextureImageMap loadedImages; + + Options& m_options; + IPlatform& m_platform; + + bool clamp = false; + bool blur = false; + + int lastBoundTexture = TEXTURES_INVALID_ID; + std::vector dynamicTextures; +}; + diff --git a/src/client/renderer/TileRenderer.h b/src/client/renderer/TileRenderer.h index 02420dd..00a38b5 100755 --- a/src/client/renderer/TileRenderer.h +++ b/src/client/renderer/TileRenderer.h @@ -1,85 +1,83 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__TileRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__TileRenderer_H__ - -//package net.minecraft.client.renderer; - -class Tile; -class FenceTile; -class FenceGateTile; -class ThinFenceTile; -class StairTile; -class LevelSource; -class Material; - -class TileRenderer -{ -public: - TileRenderer(LevelSource* level = 0); - - void tesselateInWorld(Tile* tile, int x, int y, int z, int fixedTexture); - bool tesselateInWorld(Tile* tt, int x, int y, int z); - void tesselateInWorldNoCulling(Tile* tile, int x, int y, int z); - - bool tesselateTorchInWorld(Tile* tt, int x, int y, int z); - bool tesselateLadderInWorld(Tile* tt, int x, int y, int z); - bool tesselateCactusInWorld(Tile* tt, int x, int y, int z); - bool tesselateCactusInWorld(Tile* tt, int x, int y, int z, float r, float g, float b); - bool tesselateCrossInWorld(Tile* tt, int x, int y, int z); - bool tesselateStemInWorld(Tile* _tt, int x, int y, int z); - bool tesselateWaterInWorld(Tile* tt, int x, int y, int z); - bool tesselateStairsInWorld(StairTile* tt, int x, int y, int z); - bool tesselateDoorInWorld(Tile* tt, int x, int y, int z); - bool tesselateFenceInWorld(FenceTile* tt, int x, int y, int z); - bool tesselateThinFenceInWorld(ThinFenceTile* tt, int x, int y, int z); - bool tesselateFenceGateInWorld(FenceGateTile* tt, int x, int y, int z); - bool tesselateBedInWorld(Tile *tt, int x, int y, int z); - bool tesselateRowInWorld(Tile* tt, int x, int y, int z); - - void tesselateTorch(Tile* tt, float x, float y, float z, float xxa, float zza); - void tesselateCrossTexture(Tile* tt, int data, float x, float y, float z); - void tesselateStemTexture(Tile* tt, int data, float h, float x, float y, float z); - void tesselateStemDirTexture(Tile* tt, int data, int dir, float h, float x, float y, float z); - void tesselateRowTexture(Tile* tt, int data, float x, float y, float z); - - void renderBlock(Tile* tt, LevelSource* level, int x, int y, int z); - - /*public*/ - bool tesselateBlockInWorld(Tile* tt, int x, int y, int z); - bool tesselateBlockInWorld(Tile* tt, int x, int y, int z, float r, float g, float b); - bool tesselateBlockInWorldWithAmbienceOcclusion(Tile* tt, int pX, int pY, int pZ, float pBaseRed, float pBaseGreen, float pBaseBlue); - - void renderFaceDown(Tile* tt, float x, float y, float z, int tex); - void renderFaceUp(Tile* tt, float x, float y, float z, int tex); - void renderNorth(Tile* tt, float x, float y, float z, int tex); - void renderSouth(Tile* tt, float x, float y, float z, int tex); - void renderWest(Tile* tt, float x, float y, float z, int tex); - void renderEast(Tile* tt, float x, float y, float z, int tex); - - void renderTile(Tile* tile, int data); - void renderGuiTile(Tile* tile, int data); - - static bool canRender(int renderShape); -private: - float getWaterHeight(int x, int y, int z, const Material* m); - - LevelSource* level; - int fixedTexture; - bool xFlipTexture; - bool noCulling; - - bool applyAmbienceOcclusion; - float ll000, llx00, ll0y0, ll00z, llX00, ll0Y0, ll00Z; - float llxyz, llxy0, llxyZ, ll0yz, ll0yZ, llXyz, llXy0; - float llXyZ, llxYz, llxY0, llxYZ, ll0Yz, llXYz, llXY0; - float ll0YZ, llXYZ, llx0z, llX0z, llx0Z, llX0Z; - int blsmooth; - float c1r, c2r, c3r, c4r; - float c1g, c2g, c3g, c4g; - float c1b, c2b, c3b, c4b; - bool llTrans0Yz, llTransXY0, llTransxY0, llTrans0YZ; - bool llTransx0z, llTransX0Z, llTransx0Z, llTransX0z; - bool llTrans0yz, llTransXy0, llTransxy0, llTrans0yZ; -}; - - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__TileRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer; + +class Tile; +class FenceTile; +class FenceGateTile; +class ThinFenceTile; +class StairTile; +class LevelSource; +class Material; + +class TileRenderer +{ +public: + TileRenderer(LevelSource* level = 0); + + void tesselateInWorld(Tile* tile, int x, int y, int z, int fixedTexture); + bool tesselateInWorld(Tile* tt, int x, int y, int z); + void tesselateInWorldNoCulling(Tile* tile, int x, int y, int z); + + bool tesselateTorchInWorld(Tile* tt, int x, int y, int z); + bool tesselateLadderInWorld(Tile* tt, int x, int y, int z); + bool tesselateCactusInWorld(Tile* tt, int x, int y, int z); + bool tesselateCactusInWorld(Tile* tt, int x, int y, int z, float r, float g, float b); + bool tesselateCrossInWorld(Tile* tt, int x, int y, int z); + bool tesselateStemInWorld(Tile* _tt, int x, int y, int z); + bool tesselateWaterInWorld(Tile* tt, int x, int y, int z); + bool tesselateStairsInWorld(StairTile* tt, int x, int y, int z); + bool tesselateDoorInWorld(Tile* tt, int x, int y, int z); + bool tesselateFenceInWorld(FenceTile* tt, int x, int y, int z); + bool tesselateThinFenceInWorld(ThinFenceTile* tt, int x, int y, int z); + bool tesselateFenceGateInWorld(FenceGateTile* tt, int x, int y, int z); + bool tesselateBedInWorld(Tile *tt, int x, int y, int z); + bool tesselateRowInWorld(Tile* tt, int x, int y, int z); + + void tesselateTorch(Tile* tt, float x, float y, float z, float xxa, float zza); + void tesselateCrossTexture(Tile* tt, int data, float x, float y, float z); + void tesselateStemTexture(Tile* tt, int data, float h, float x, float y, float z); + void tesselateStemDirTexture(Tile* tt, int data, int dir, float h, float x, float y, float z); + void tesselateRowTexture(Tile* tt, int data, float x, float y, float z); + + void renderBlock(Tile* tt, LevelSource* level, int x, int y, int z); + + /*public*/ + bool tesselateBlockInWorld(Tile* tt, int x, int y, int z); + bool tesselateBlockInWorld(Tile* tt, int x, int y, int z, float r, float g, float b); + bool tesselateBlockInWorldWithAmbienceOcclusion(Tile* tt, int pX, int pY, int pZ, float pBaseRed, float pBaseGreen, float pBaseBlue); + + void renderFaceDown(Tile* tt, float x, float y, float z, int tex); + void renderFaceUp(Tile* tt, float x, float y, float z, int tex); + void renderNorth(Tile* tt, float x, float y, float z, int tex); + void renderSouth(Tile* tt, float x, float y, float z, int tex); + void renderWest(Tile* tt, float x, float y, float z, int tex); + void renderEast(Tile* tt, float x, float y, float z, int tex); + + void renderTile(Tile* tile, int data); + void renderGuiTile(Tile* tile, int data); + + static bool canRender(int renderShape); +private: + float getWaterHeight(int x, int y, int z, const Material* m); + + LevelSource* level; + int fixedTexture; + bool xFlipTexture; + bool noCulling; + + bool applyAmbienceOcclusion; + float ll000, llx00, ll0y0, ll00z, llX00, ll0Y0, ll00Z; + float llxyz, llxy0, llxyZ, ll0yz, ll0yZ, llXyz, llXy0; + float llXyZ, llxYz, llxY0, llxYZ, ll0Yz, llXYz, llXY0; + float ll0YZ, llXYZ, llx0z, llX0z, llx0Z, llX0Z; + int blsmooth; + float c1r, c2r, c3r, c4r; + float c1g, c2g, c3g, c4g; + float c1b, c2b, c3b, c4b; + bool llTrans0Yz, llTransXY0, llTransxY0, llTrans0YZ; + bool llTransx0z, llTransX0Z, llTransx0Z, llTransX0z; + bool llTrans0yz, llTransXy0, llTransxy0, llTrans0yZ; +}; + + diff --git a/src/client/renderer/VertecDecl.h b/src/client/renderer/VertecDecl.h index 8abc1d3..6f22a6d 100755 --- a/src/client/renderer/VertecDecl.h +++ b/src/client/renderer/VertecDecl.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__VertexDecl_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__VertexDecl_H__ - -typedef struct VertexDeclPTC -{ - GLfloat x, y, z; - GLfloat u, v; - GLuint color; - -} VertexDeclPTC; - -typedef struct VertexDeclPTCN -{ - GLfloat x, y, z; - GLfloat u, v; - GLuint color; - GLuint normal; - -} VertexDeclPTCN; - -#endif /*#ifndef NET_MINECRAFT_CLIENT_RENDERER__VertexDecl_H__ */ +#pragma once + +typedef struct VertexDeclPTC +{ + GLfloat x, y, z; + GLfloat u, v; + GLuint color; + +} VertexDeclPTC; + +typedef struct VertexDeclPTCN +{ + GLfloat x, y, z; + GLfloat u, v; + GLuint color; + GLuint normal; + +} VertexDeclPTCN; + diff --git a/src/client/renderer/culling/AllowAllCuller.h b/src/client/renderer/culling/AllowAllCuller.h index 9d408c9..09a664e 100755 --- a/src/client/renderer/culling/AllowAllCuller.h +++ b/src/client/renderer/culling/AllowAllCuller.h @@ -1,29 +1,27 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_CULLING__AllowAllCuller_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_CULLING__AllowAllCuller_H__ - -//package net.minecraft.client.renderer.culling; - -#include "Culler.h" - -class AABB; - -class AllowAllCuller: public Culler -{ -public: - bool isVisible(const AABB& bb) { - return true; - } - - bool cubeFullyInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) { - return true; - } - - bool cubeInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) { - return true; - } - - void prepare(float xOff, float yOff, float zOff) { - } -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_CULLING__AllowAllCuller_H__*/ +#pragma once + +//package net.minecraft.client.renderer.culling; + +#include "Culler.h" + +class AABB; + +class AllowAllCuller: public Culler +{ +public: + bool isVisible(const AABB& bb) { + return true; + } + + bool cubeFullyInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) { + return true; + } + + bool cubeInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) { + return true; + } + + void prepare(float xOff, float yOff, float zOff) { + } +}; + diff --git a/src/client/renderer/culling/Culler.h b/src/client/renderer/culling/Culler.h index bfd8c03..c3ad963 100755 --- a/src/client/renderer/culling/Culler.h +++ b/src/client/renderer/culling/Culler.h @@ -1,22 +1,20 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_CULLING__Culler_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_CULLING__Culler_H__ - -//package net.minecraft.client.renderer.culling; - -class AABB; - -class Culler -{ -public: - virtual ~Culler() {} - - virtual bool isVisible(const AABB& bb) = 0; - - virtual bool cubeInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) = 0; - - virtual bool cubeFullyInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) = 0; - - virtual void prepare(float xOff, float yOff, float zOff) {} -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_CULLING__Culler_H__*/ +#pragma once + +//package net.minecraft.client.renderer.culling; + +class AABB; + +class Culler +{ +public: + virtual ~Culler() {} + + virtual bool isVisible(const AABB& bb) = 0; + + virtual bool cubeInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) = 0; + + virtual bool cubeFullyInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) = 0; + + virtual void prepare(float xOff, float yOff, float zOff) {} +}; + diff --git a/src/client/renderer/culling/Frustum.h b/src/client/renderer/culling/Frustum.h index 25396e3..74d1104 100755 --- a/src/client/renderer/culling/Frustum.h +++ b/src/client/renderer/culling/Frustum.h @@ -1,163 +1,161 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_CULLING__Frustum_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_CULLING__Frustum_H__ - -//package net.minecraft.client.renderer.culling; - -/* import static org.lwjgl.opengl.GL11.* */ - - -// 1) Stolen and ported to java from the web somewhere. -// 2) ... and then ported back to C++! - -//***********************************************************************// -// // -// - "Talk to me like I'm a 3 year old!" Programming Lessons - // -// // -// $Author: DigiBen digiben@gametutorials.com // -// // -// $Program: Frustum Culling // -// // -// $Description: Demonstrates checking if shapes are in view // -// // -// $Date: 8/28/01 // -// // -//***********************************************************************// - -//#include "main.h" - -#include "FrustumData.h" -#include "../../../util/Mth.h" -#include "../gles.h" - -class Frustum: public FrustumData -{ -private: - static Frustum frustum; - -public: - static FrustumData& getFrustum() { - frustum.calculateFrustum(); - return frustum; - } - - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* - ///// - ///// This normalizes a plane (A side) from a given frustum. - ///// - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* -private: - void normalizePlane(float frustum[16][16], int side) - { - // Here we calculate the magnitude of the normal to the plane (point A B C) - // Remember that (A, B, C) is that same thing as the normal's (X, Y, Z). - // To calculate magnitude you use the equation: magnitude = sqrt( x^2 + y^2 + z^2) - float invMagnitude = Mth::invSqrt(frustum[side][A] * frustum[side][A] + frustum[side][B] * frustum[side][B] + frustum[side][C] * frustum[side][C]); - - // Then we divide the plane's values by it's magnitude. - // This makes it easier to work with. - frustum[side][A] *= invMagnitude; - frustum[side][B] *= invMagnitude; - frustum[side][C] *= invMagnitude; - frustum[side][D] *= invMagnitude; - } - - float _proj[16]; - float _modl[16]; - float _clip[16]; - - void calculateFrustum() - { - // glGetFloatv() is used to extract information about our OpenGL world. - // Below, we pass in GL_PROJECTION_MATRIX to abstract our projection matrix. - // It then stores the matrix into an array of [16]. - glGetFloatv(GL_PROJECTION_MATRIX, proj); - - // By passing in GL_MODELVIEW_MATRIX, we can abstract our model view matrix. - // This also stores it in an array of [16]. - glGetFloatv(GL_MODELVIEW_MATRIX, modl); - // Now that we have our modelview and projection matrix, if we combine these 2 matrices, - // it will give us our clipping planes. To combine 2 matrices, we multiply them. - - clip[0] = modl[0] * proj[0] + modl[1] * proj[4] + modl[2] * proj[8] + modl[3] * proj[12]; - clip[1] = modl[0] * proj[1] + modl[1] * proj[5] + modl[2] * proj[9] + modl[3] * proj[13]; - clip[2] = modl[0] * proj[2] + modl[1] * proj[6] + modl[2] * proj[10] + modl[3] * proj[14]; - clip[3] = modl[0] * proj[3] + modl[1] * proj[7] + modl[2] * proj[11] + modl[3] * proj[15]; - - clip[4] = modl[4] * proj[0] + modl[5] * proj[4] + modl[6] * proj[8] + modl[7] * proj[12]; - clip[5] = modl[4] * proj[1] + modl[5] * proj[5] + modl[6] * proj[9] + modl[7] * proj[13]; - clip[6] = modl[4] * proj[2] + modl[5] * proj[6] + modl[6] * proj[10] + modl[7] * proj[14]; - clip[7] = modl[4] * proj[3] + modl[5] * proj[7] + modl[6] * proj[11] + modl[7] * proj[15]; - - clip[8] = modl[8] * proj[0] + modl[9] * proj[4] + modl[10] * proj[8] + modl[11] * proj[12]; - clip[9] = modl[8] * proj[1] + modl[9] * proj[5] + modl[10] * proj[9] + modl[11] * proj[13]; - clip[10] = modl[8] * proj[2] + modl[9] * proj[6] + modl[10] * proj[10] + modl[11] * proj[14]; - clip[11] = modl[8] * proj[3] + modl[9] * proj[7] + modl[10] * proj[11] + modl[11] * proj[15]; - - clip[12] = modl[12] * proj[0] + modl[13] * proj[4] + modl[14] * proj[8] + modl[15] * proj[12]; - clip[13] = modl[12] * proj[1] + modl[13] * proj[5] + modl[14] * proj[9] + modl[15] * proj[13]; - clip[14] = modl[12] * proj[2] + modl[13] * proj[6] + modl[14] * proj[10] + modl[15] * proj[14]; - clip[15] = modl[12] * proj[3] + modl[13] * proj[7] + modl[14] * proj[11] + modl[15] * proj[15]; - - // Now we actually want to get the sides of the frustum. To do this we take - // the clipping planes we received above and extract the sides from them. - - // This will extract the RIGHT side of the frustum - m_Frustum[RIGHT][A] = clip[3] - clip[0]; - m_Frustum[RIGHT][B] = clip[7] - clip[4]; - m_Frustum[RIGHT][C] = clip[11] - clip[8]; - m_Frustum[RIGHT][D] = clip[15] - clip[12]; - - // Now that we have a normal (A,B,C) and a distance (D) to the plane, - // we want to normalize that normal and distance. - - // Normalize the RIGHT side - normalizePlane(m_Frustum, RIGHT); - - // This will extract the LEFT side of the frustum - m_Frustum[LEFT][A] = clip[3] + clip[0]; - m_Frustum[LEFT][B] = clip[7] + clip[4]; - m_Frustum[LEFT][C] = clip[11] + clip[8]; - m_Frustum[LEFT][D] = clip[15] + clip[12]; - - // Normalize the LEFT side - normalizePlane(m_Frustum, LEFT); - - // This will extract the BOTTOM side of the frustum - m_Frustum[BOTTOM][A] = clip[3] + clip[1]; - m_Frustum[BOTTOM][B] = clip[7] + clip[5]; - m_Frustum[BOTTOM][C] = clip[11] + clip[9]; - m_Frustum[BOTTOM][D] = clip[15] + clip[13]; - - // Normalize the BOTTOM side - normalizePlane(m_Frustum, BOTTOM); - - // This will extract the TOP side of the frustum - m_Frustum[TOP][A] = clip[3] - clip[1]; - m_Frustum[TOP][B] = clip[7] - clip[5]; - m_Frustum[TOP][C] = clip[11] - clip[9]; - m_Frustum[TOP][D] = clip[15] - clip[13]; - - // Normalize the TOP side - normalizePlane(m_Frustum, TOP); - - // This will extract the BACK side of the frustum - m_Frustum[BACK][A] = clip[3] - clip[2]; - m_Frustum[BACK][B] = clip[7] - clip[6]; - m_Frustum[BACK][C] = clip[11] - clip[10]; - m_Frustum[BACK][D] = clip[15] - clip[14]; - - // Normalize the BACK side - normalizePlane(m_Frustum, BACK); - - // This will extract the FRONT side of the frustum - m_Frustum[FRONT][A] = clip[3] + clip[2]; - m_Frustum[FRONT][B] = clip[7] + clip[6]; - m_Frustum[FRONT][C] = clip[11] + clip[10]; - m_Frustum[FRONT][D] = clip[15] + clip[14]; - - // Normalize the FRONT side - normalizePlane(m_Frustum, FRONT); - } -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_CULLING__Frustum_H__*/ +#pragma once + +//package net.minecraft.client.renderer.culling; + +/* import static org.lwjgl.opengl.GL11.* */ + + +// 1) Stolen and ported to java from the web somewhere. +// 2) ... and then ported back to C++! + +//***********************************************************************// +// // +// - "Talk to me like I'm a 3 year old!" Programming Lessons - // +// // +// $Author: DigiBen digiben@gametutorials.com // +// // +// $Program: Frustum Culling // +// // +// $Description: Demonstrates checking if shapes are in view // +// // +// $Date: 8/28/01 // +// // +//***********************************************************************// + +//#include "main.h" + +#include "FrustumData.h" +#include "../../../util/Mth.h" +#include "../gles.h" + +class Frustum: public FrustumData +{ +private: + static Frustum frustum; + +public: + static FrustumData& getFrustum() { + frustum.calculateFrustum(); + return frustum; + } + + ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + ///// + ///// This normalizes a plane (A side) from a given frustum. + ///// + ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* +private: + void normalizePlane(float frustum[16][16], int side) + { + // Here we calculate the magnitude of the normal to the plane (point A B C) + // Remember that (A, B, C) is that same thing as the normal's (X, Y, Z). + // To calculate magnitude you use the equation: magnitude = sqrt( x^2 + y^2 + z^2) + float invMagnitude = Mth::invSqrt(frustum[side][A] * frustum[side][A] + frustum[side][B] * frustum[side][B] + frustum[side][C] * frustum[side][C]); + + // Then we divide the plane's values by it's magnitude. + // This makes it easier to work with. + frustum[side][A] *= invMagnitude; + frustum[side][B] *= invMagnitude; + frustum[side][C] *= invMagnitude; + frustum[side][D] *= invMagnitude; + } + + float _proj[16]; + float _modl[16]; + float _clip[16]; + + void calculateFrustum() + { + // glGetFloatv() is used to extract information about our OpenGL world. + // Below, we pass in GL_PROJECTION_MATRIX to abstract our projection matrix. + // It then stores the matrix into an array of [16]. + glGetFloatv(GL_PROJECTION_MATRIX, proj); + + // By passing in GL_MODELVIEW_MATRIX, we can abstract our model view matrix. + // This also stores it in an array of [16]. + glGetFloatv(GL_MODELVIEW_MATRIX, modl); + // Now that we have our modelview and projection matrix, if we combine these 2 matrices, + // it will give us our clipping planes. To combine 2 matrices, we multiply them. + + clip[0] = modl[0] * proj[0] + modl[1] * proj[4] + modl[2] * proj[8] + modl[3] * proj[12]; + clip[1] = modl[0] * proj[1] + modl[1] * proj[5] + modl[2] * proj[9] + modl[3] * proj[13]; + clip[2] = modl[0] * proj[2] + modl[1] * proj[6] + modl[2] * proj[10] + modl[3] * proj[14]; + clip[3] = modl[0] * proj[3] + modl[1] * proj[7] + modl[2] * proj[11] + modl[3] * proj[15]; + + clip[4] = modl[4] * proj[0] + modl[5] * proj[4] + modl[6] * proj[8] + modl[7] * proj[12]; + clip[5] = modl[4] * proj[1] + modl[5] * proj[5] + modl[6] * proj[9] + modl[7] * proj[13]; + clip[6] = modl[4] * proj[2] + modl[5] * proj[6] + modl[6] * proj[10] + modl[7] * proj[14]; + clip[7] = modl[4] * proj[3] + modl[5] * proj[7] + modl[6] * proj[11] + modl[7] * proj[15]; + + clip[8] = modl[8] * proj[0] + modl[9] * proj[4] + modl[10] * proj[8] + modl[11] * proj[12]; + clip[9] = modl[8] * proj[1] + modl[9] * proj[5] + modl[10] * proj[9] + modl[11] * proj[13]; + clip[10] = modl[8] * proj[2] + modl[9] * proj[6] + modl[10] * proj[10] + modl[11] * proj[14]; + clip[11] = modl[8] * proj[3] + modl[9] * proj[7] + modl[10] * proj[11] + modl[11] * proj[15]; + + clip[12] = modl[12] * proj[0] + modl[13] * proj[4] + modl[14] * proj[8] + modl[15] * proj[12]; + clip[13] = modl[12] * proj[1] + modl[13] * proj[5] + modl[14] * proj[9] + modl[15] * proj[13]; + clip[14] = modl[12] * proj[2] + modl[13] * proj[6] + modl[14] * proj[10] + modl[15] * proj[14]; + clip[15] = modl[12] * proj[3] + modl[13] * proj[7] + modl[14] * proj[11] + modl[15] * proj[15]; + + // Now we actually want to get the sides of the frustum. To do this we take + // the clipping planes we received above and extract the sides from them. + + // This will extract the RIGHT side of the frustum + m_Frustum[RIGHT][A] = clip[3] - clip[0]; + m_Frustum[RIGHT][B] = clip[7] - clip[4]; + m_Frustum[RIGHT][C] = clip[11] - clip[8]; + m_Frustum[RIGHT][D] = clip[15] - clip[12]; + + // Now that we have a normal (A,B,C) and a distance (D) to the plane, + // we want to normalize that normal and distance. + + // Normalize the RIGHT side + normalizePlane(m_Frustum, RIGHT); + + // This will extract the LEFT side of the frustum + m_Frustum[LEFT][A] = clip[3] + clip[0]; + m_Frustum[LEFT][B] = clip[7] + clip[4]; + m_Frustum[LEFT][C] = clip[11] + clip[8]; + m_Frustum[LEFT][D] = clip[15] + clip[12]; + + // Normalize the LEFT side + normalizePlane(m_Frustum, LEFT); + + // This will extract the BOTTOM side of the frustum + m_Frustum[BOTTOM][A] = clip[3] + clip[1]; + m_Frustum[BOTTOM][B] = clip[7] + clip[5]; + m_Frustum[BOTTOM][C] = clip[11] + clip[9]; + m_Frustum[BOTTOM][D] = clip[15] + clip[13]; + + // Normalize the BOTTOM side + normalizePlane(m_Frustum, BOTTOM); + + // This will extract the TOP side of the frustum + m_Frustum[TOP][A] = clip[3] - clip[1]; + m_Frustum[TOP][B] = clip[7] - clip[5]; + m_Frustum[TOP][C] = clip[11] - clip[9]; + m_Frustum[TOP][D] = clip[15] - clip[13]; + + // Normalize the TOP side + normalizePlane(m_Frustum, TOP); + + // This will extract the BACK side of the frustum + m_Frustum[BACK][A] = clip[3] - clip[2]; + m_Frustum[BACK][B] = clip[7] - clip[6]; + m_Frustum[BACK][C] = clip[11] - clip[10]; + m_Frustum[BACK][D] = clip[15] - clip[14]; + + // Normalize the BACK side + normalizePlane(m_Frustum, BACK); + + // This will extract the FRONT side of the frustum + m_Frustum[FRONT][A] = clip[3] + clip[2]; + m_Frustum[FRONT][B] = clip[7] + clip[6]; + m_Frustum[FRONT][C] = clip[11] + clip[10]; + m_Frustum[FRONT][D] = clip[15] + clip[14]; + + // Normalize the FRONT side + normalizePlane(m_Frustum, FRONT); + } +}; + diff --git a/src/client/renderer/culling/FrustumCuller.h b/src/client/renderer/culling/FrustumCuller.h index 470c953..8429494 100755 --- a/src/client/renderer/culling/FrustumCuller.h +++ b/src/client/renderer/culling/FrustumCuller.h @@ -1,39 +1,37 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumCuller_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumCuller_H__ - -//package net.minecraft.client.renderer.culling; - -#include "FrustumData.h" -#include "Frustum.h" - -class FrustumCuller: public Culler { - -private: - FrustumData frustum; - float xOff, yOff, zOff; - -public: - FrustumCuller() { - frustum = Frustum::getFrustum(); - } - - void prepare(float xOff, float yOff, float zOff) { - this->xOff = xOff; - this->yOff = yOff; - this->zOff = zOff; - } - - bool cubeFullyInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { - return frustum.cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); - } - - bool cubeInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { - return frustum.cubeInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); - } - - bool isVisible(const AABB& bb) { - return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); - } -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumCuller_H__*/ +#pragma once + +//package net.minecraft.client.renderer.culling; + +#include "FrustumData.h" +#include "Frustum.h" + +class FrustumCuller: public Culler { + +private: + FrustumData frustum; + float xOff, yOff, zOff; + +public: + FrustumCuller() { + frustum = Frustum::getFrustum(); + } + + void prepare(float xOff, float yOff, float zOff) { + this->xOff = xOff; + this->yOff = yOff; + this->zOff = zOff; + } + + bool cubeFullyInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { + return frustum.cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); + } + + bool cubeInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { + return frustum.cubeInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); + } + + bool isVisible(const AABB& bb) { + return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); + } +}; + diff --git a/src/client/renderer/culling/FrustumData.h b/src/client/renderer/culling/FrustumData.h index f29a0de..5f2c4b6 100755 --- a/src/client/renderer/culling/FrustumData.h +++ b/src/client/renderer/culling/FrustumData.h @@ -1,97 +1,95 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumData_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumData_H__ - -//package net.minecraft.client.renderer.culling; - -#include "../../../world/phys/AABB.h" - -// We create an enum of the sides so we don't have to call each side 0 or 1. -// This way it makes it more understandable and readable when dealing with frustum sides. -class FrustumData -{ -public: - //enum FrustumSide - static const int RIGHT = 0; // The RIGHT side of the frustum - static const int LEFT = 1; // The LEFT side of the frustum - static const int BOTTOM = 2; // The BOTTOM side of the frustum - static const int TOP = 3; // The TOP side of the frustum - static const int BACK = 4; // The BACK side of the frustum - static const int FRONT = 5; // The FRONT side of the frustum - - // Like above, instead of saying a number for the ABC and D of the plane, we - // want to be more descriptive. - static const int A = 0; // The X value of the plane's normal - static const int B = 1; // The Y value of the plane's normal - static const int C = 2; // The Z value of the plane's normal - static const int D = 3; // The distance the plane is from the origin - - float m_Frustum[16][16]; - float proj[16]; - float modl[16]; - float clip[16]; - - bool pointInFrustum(float x, float y, float z) - { - for (int i = 0; i < 6; i++) - { - if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= 0) - { - return false; - } - } - - return true; - } - bool sphereInFrustum(float x, float y, float z, float radius) - { - for (int i = 0; i < 6; i++) - { - if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= -radius) - { - return false; - } - } - - return true; - } - bool cubeFullyInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) - { - for (int i = 0; i < 6; i++) - { - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - } - - return true; - } - - bool cubeInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) - { - for (int i = 0; i < 6; i++) - { - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - - return false; - } - - return true; - } - bool isVisible(const AABB& aabb) - { - return cubeInFrustum(aabb.x0, aabb.y0, aabb.z0, aabb.x1, aabb.y1, aabb.z1); - } -}; -#endif /*NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumData_H__*/ +#pragma once + +//package net.minecraft.client.renderer.culling; + +#include "../../../world/phys/AABB.h" + +// We create an enum of the sides so we don't have to call each side 0 or 1. +// This way it makes it more understandable and readable when dealing with frustum sides. +class FrustumData +{ +public: + //enum FrustumSide + static const int RIGHT = 0; // The RIGHT side of the frustum + static const int LEFT = 1; // The LEFT side of the frustum + static const int BOTTOM = 2; // The BOTTOM side of the frustum + static const int TOP = 3; // The TOP side of the frustum + static const int BACK = 4; // The BACK side of the frustum + static const int FRONT = 5; // The FRONT side of the frustum + + // Like above, instead of saying a number for the ABC and D of the plane, we + // want to be more descriptive. + static const int A = 0; // The X value of the plane's normal + static const int B = 1; // The Y value of the plane's normal + static const int C = 2; // The Z value of the plane's normal + static const int D = 3; // The distance the plane is from the origin + + float m_Frustum[16][16]; + float proj[16]; + float modl[16]; + float clip[16]; + + bool pointInFrustum(float x, float y, float z) + { + for (int i = 0; i < 6; i++) + { + if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= 0) + { + return false; + } + } + + return true; + } + bool sphereInFrustum(float x, float y, float z, float radius) + { + for (int i = 0; i < 6; i++) + { + if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= -radius) + { + return false; + } + } + + return true; + } + bool cubeFullyInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) + { + for (int i = 0; i < 6; i++) + { + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; + } + + return true; + } + + bool cubeInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) + { + for (int i = 0; i < 6; i++) + { + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; + + return false; + } + + return true; + } + bool isVisible(const AABB& aabb) + { + return cubeInFrustum(aabb.x0, aabb.y0, aabb.z0, aabb.x1, aabb.y1, aabb.z1); + } +}; diff --git a/src/client/renderer/culling/tmp/Frustum.h b/src/client/renderer/culling/tmp/Frustum.h index 012a28e..e8be6e8 100755 --- a/src/client/renderer/culling/tmp/Frustum.h +++ b/src/client/renderer/culling/tmp/Frustum.h @@ -1,172 +1,170 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_CULLING__Frustum_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_CULLING__Frustum_H__ - -//package net.minecraft.client.renderer.culling; - -/* import static org.lwjgl.opengl.GL11.* */ - -#include "java/nio/FloatBuffer.h" - -#include "client/MemoryTracker.h" - - -// Stolen and ported to java from the web somewhere. - -//***********************************************************************// -// // -// - "Talk to me like I'm a 3 year old!" Programming Lessons - // -// // -// $Author: DigiBen digiben@gametutorials.com // -// // -// $Program: Frustum Culling // -// // -// $Description: Demonstrates checking if shapes are in view // -// // -// $Date: 8/28/01 // -// // -//***********************************************************************// - -//#include "main.h" - -// We create an enum of the sides so we don't have to call each side 0 or 1. -// This way it makes it more understandable and readable when dealing with frustum sides. -/*public*/ class Frustum: public FrustumData -{ - /*private*/ static Frustum frustum = /*new*/ Frustum(); - - /*public*/ static FrustumData getFrustum() - { - frustum.calculateFrustum(); - return frustum; - } - - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* - ///// - ///// This normalizes a plane (A side) from a given frustum. - ///// - ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* - - /*private*/ void normalizePlane(float[][] frustum, int side) - { - // Here we calculate the magnitude of the normal to the plane (point A B C) - // Remember that (A, B, C) is that same thing as the normal's (X, Y, Z). - // To calculate magnitude you use the equation: magnitude = sqrt( x^2 + y^2 + z^2) - float magnitude = (float) util.Mth.sqrt(frustum[side][A] * frustum[side][A] + frustum[side][B] * frustum[side][B] + frustum[side][C] * frustum[side][C]); - - // Then we divide the plane's values by it's magnitude. - // This makes it easier to work with. - frustum[side][A] /= magnitude; - frustum[side][B] /= magnitude; - frustum[side][C] /= magnitude; - frustum[side][D] /= magnitude; - } - - /*private*/ FloatBuffer _proj = MemoryTracker.createFloatBuffer(16); - /*private*/ FloatBuffer _modl = MemoryTracker.createFloatBuffer(16); - /*private*/ FloatBuffer _clip = MemoryTracker.createFloatBuffer(16); - - /*private*/ void calculateFrustum() - { - _proj.clear(); - _modl.clear(); - _clip.clear(); - - // glGetFloatv() is used to extract information about our OpenGL world. - // Below, we pass in GL_PROJECTION_MATRIX to abstract our projection matrix. - // It then stores the matrix into an array of [16]. - glGetFloat(GL_PROJECTION_MATRIX, _proj); - - // By passing in GL_MODELVIEW_MATRIX, we can abstract our model view matrix. - // This also stores it in an array of [16]. - glGetFloat(GL_MODELVIEW_MATRIX, _modl); - - _proj.flip().limit(16); - _proj.get(proj); - _modl.flip().limit(16); - _modl.get(modl); - - // Now that we have our modelview and projection matrix, if we combine these 2 matrices, - // it will give us our clipping planes. To combine 2 matrices, we multiply them. - - clip[0] = modl[0] * proj[0] + modl[1] * proj[4] + modl[2] * proj[8] + modl[3] * proj[12]; - clip[1] = modl[0] * proj[1] + modl[1] * proj[5] + modl[2] * proj[9] + modl[3] * proj[13]; - clip[2] = modl[0] * proj[2] + modl[1] * proj[6] + modl[2] * proj[10] + modl[3] * proj[14]; - clip[3] = modl[0] * proj[3] + modl[1] * proj[7] + modl[2] * proj[11] + modl[3] * proj[15]; - - clip[4] = modl[4] * proj[0] + modl[5] * proj[4] + modl[6] * proj[8] + modl[7] * proj[12]; - clip[5] = modl[4] * proj[1] + modl[5] * proj[5] + modl[6] * proj[9] + modl[7] * proj[13]; - clip[6] = modl[4] * proj[2] + modl[5] * proj[6] + modl[6] * proj[10] + modl[7] * proj[14]; - clip[7] = modl[4] * proj[3] + modl[5] * proj[7] + modl[6] * proj[11] + modl[7] * proj[15]; - - clip[8] = modl[8] * proj[0] + modl[9] * proj[4] + modl[10] * proj[8] + modl[11] * proj[12]; - clip[9] = modl[8] * proj[1] + modl[9] * proj[5] + modl[10] * proj[9] + modl[11] * proj[13]; - clip[10] = modl[8] * proj[2] + modl[9] * proj[6] + modl[10] * proj[10] + modl[11] * proj[14]; - clip[11] = modl[8] * proj[3] + modl[9] * proj[7] + modl[10] * proj[11] + modl[11] * proj[15]; - - clip[12] = modl[12] * proj[0] + modl[13] * proj[4] + modl[14] * proj[8] + modl[15] * proj[12]; - clip[13] = modl[12] * proj[1] + modl[13] * proj[5] + modl[14] * proj[9] + modl[15] * proj[13]; - clip[14] = modl[12] * proj[2] + modl[13] * proj[6] + modl[14] * proj[10] + modl[15] * proj[14]; - clip[15] = modl[12] * proj[3] + modl[13] * proj[7] + modl[14] * proj[11] + modl[15] * proj[15]; - - // Now we actually want to get the sides of the frustum. To do this we take - // the clipping planes we received above and extract the sides from them. - - // This will extract the RIGHT side of the frustum - m_Frustum[RIGHT][A] = clip[3] - clip[0]; - m_Frustum[RIGHT][B] = clip[7] - clip[4]; - m_Frustum[RIGHT][C] = clip[11] - clip[8]; - m_Frustum[RIGHT][D] = clip[15] - clip[12]; - - // Now that we have a normal (A,B,C) and a distance (D) to the plane, - // we want to normalize that normal and distance. - - // Normalize the RIGHT side - normalizePlane(m_Frustum, RIGHT); - - // This will extract the LEFT side of the frustum - m_Frustum[LEFT][A] = clip[3] + clip[0]; - m_Frustum[LEFT][B] = clip[7] + clip[4]; - m_Frustum[LEFT][C] = clip[11] + clip[8]; - m_Frustum[LEFT][D] = clip[15] + clip[12]; - - // Normalize the LEFT side - normalizePlane(m_Frustum, LEFT); - - // This will extract the BOTTOM side of the frustum - m_Frustum[BOTTOM][A] = clip[3] + clip[1]; - m_Frustum[BOTTOM][B] = clip[7] + clip[5]; - m_Frustum[BOTTOM][C] = clip[11] + clip[9]; - m_Frustum[BOTTOM][D] = clip[15] + clip[13]; - - // Normalize the BOTTOM side - normalizePlane(m_Frustum, BOTTOM); - - // This will extract the TOP side of the frustum - m_Frustum[TOP][A] = clip[3] - clip[1]; - m_Frustum[TOP][B] = clip[7] - clip[5]; - m_Frustum[TOP][C] = clip[11] - clip[9]; - m_Frustum[TOP][D] = clip[15] - clip[13]; - - // Normalize the TOP side - normalizePlane(m_Frustum, TOP); - - // This will extract the BACK side of the frustum - m_Frustum[BACK][A] = clip[3] - clip[2]; - m_Frustum[BACK][B] = clip[7] - clip[6]; - m_Frustum[BACK][C] = clip[11] - clip[10]; - m_Frustum[BACK][D] = clip[15] - clip[14]; - - // Normalize the BACK side - normalizePlane(m_Frustum, BACK); - - // This will extract the FRONT side of the frustum - m_Frustum[FRONT][A] = clip[3] + clip[2]; - m_Frustum[FRONT][B] = clip[7] + clip[6]; - m_Frustum[FRONT][C] = clip[11] + clip[10]; - m_Frustum[FRONT][D] = clip[15] + clip[14]; - - // Normalize the FRONT side - normalizePlane(m_Frustum, FRONT); - } -} -#endif /*NET_MINECRAFT_CLIENT_RENDERER_CULLING__Frustum_H__*/ +#pragma once + +//package net.minecraft.client.renderer.culling; + +/* import static org.lwjgl.opengl.GL11.* */ + +#include "java/nio/FloatBuffer.h" + +#include "client/MemoryTracker.h" + + +// Stolen and ported to java from the web somewhere. + +//***********************************************************************// +// // +// - "Talk to me like I'm a 3 year old!" Programming Lessons - // +// // +// $Author: DigiBen digiben@gametutorials.com // +// // +// $Program: Frustum Culling // +// // +// $Description: Demonstrates checking if shapes are in view // +// // +// $Date: 8/28/01 // +// // +//***********************************************************************// + +//#include "main.h" + +// We create an enum of the sides so we don't have to call each side 0 or 1. +// This way it makes it more understandable and readable when dealing with frustum sides. +/*public*/ class Frustum: public FrustumData +{ + /*private*/ static Frustum frustum = /*new*/ Frustum(); + + /*public*/ static FrustumData getFrustum() + { + frustum.calculateFrustum(); + return frustum; + } + + ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + ///// + ///// This normalizes a plane (A side) from a given frustum. + ///// + ///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* + + /*private*/ void normalizePlane(float[][] frustum, int side) + { + // Here we calculate the magnitude of the normal to the plane (point A B C) + // Remember that (A, B, C) is that same thing as the normal's (X, Y, Z). + // To calculate magnitude you use the equation: magnitude = sqrt( x^2 + y^2 + z^2) + float magnitude = (float) util.Mth.sqrt(frustum[side][A] * frustum[side][A] + frustum[side][B] * frustum[side][B] + frustum[side][C] * frustum[side][C]); + + // Then we divide the plane's values by it's magnitude. + // This makes it easier to work with. + frustum[side][A] /= magnitude; + frustum[side][B] /= magnitude; + frustum[side][C] /= magnitude; + frustum[side][D] /= magnitude; + } + + /*private*/ FloatBuffer _proj = MemoryTracker.createFloatBuffer(16); + /*private*/ FloatBuffer _modl = MemoryTracker.createFloatBuffer(16); + /*private*/ FloatBuffer _clip = MemoryTracker.createFloatBuffer(16); + + /*private*/ void calculateFrustum() + { + _proj.clear(); + _modl.clear(); + _clip.clear(); + + // glGetFloatv() is used to extract information about our OpenGL world. + // Below, we pass in GL_PROJECTION_MATRIX to abstract our projection matrix. + // It then stores the matrix into an array of [16]. + glGetFloat(GL_PROJECTION_MATRIX, _proj); + + // By passing in GL_MODELVIEW_MATRIX, we can abstract our model view matrix. + // This also stores it in an array of [16]. + glGetFloat(GL_MODELVIEW_MATRIX, _modl); + + _proj.flip().limit(16); + _proj.get(proj); + _modl.flip().limit(16); + _modl.get(modl); + + // Now that we have our modelview and projection matrix, if we combine these 2 matrices, + // it will give us our clipping planes. To combine 2 matrices, we multiply them. + + clip[0] = modl[0] * proj[0] + modl[1] * proj[4] + modl[2] * proj[8] + modl[3] * proj[12]; + clip[1] = modl[0] * proj[1] + modl[1] * proj[5] + modl[2] * proj[9] + modl[3] * proj[13]; + clip[2] = modl[0] * proj[2] + modl[1] * proj[6] + modl[2] * proj[10] + modl[3] * proj[14]; + clip[3] = modl[0] * proj[3] + modl[1] * proj[7] + modl[2] * proj[11] + modl[3] * proj[15]; + + clip[4] = modl[4] * proj[0] + modl[5] * proj[4] + modl[6] * proj[8] + modl[7] * proj[12]; + clip[5] = modl[4] * proj[1] + modl[5] * proj[5] + modl[6] * proj[9] + modl[7] * proj[13]; + clip[6] = modl[4] * proj[2] + modl[5] * proj[6] + modl[6] * proj[10] + modl[7] * proj[14]; + clip[7] = modl[4] * proj[3] + modl[5] * proj[7] + modl[6] * proj[11] + modl[7] * proj[15]; + + clip[8] = modl[8] * proj[0] + modl[9] * proj[4] + modl[10] * proj[8] + modl[11] * proj[12]; + clip[9] = modl[8] * proj[1] + modl[9] * proj[5] + modl[10] * proj[9] + modl[11] * proj[13]; + clip[10] = modl[8] * proj[2] + modl[9] * proj[6] + modl[10] * proj[10] + modl[11] * proj[14]; + clip[11] = modl[8] * proj[3] + modl[9] * proj[7] + modl[10] * proj[11] + modl[11] * proj[15]; + + clip[12] = modl[12] * proj[0] + modl[13] * proj[4] + modl[14] * proj[8] + modl[15] * proj[12]; + clip[13] = modl[12] * proj[1] + modl[13] * proj[5] + modl[14] * proj[9] + modl[15] * proj[13]; + clip[14] = modl[12] * proj[2] + modl[13] * proj[6] + modl[14] * proj[10] + modl[15] * proj[14]; + clip[15] = modl[12] * proj[3] + modl[13] * proj[7] + modl[14] * proj[11] + modl[15] * proj[15]; + + // Now we actually want to get the sides of the frustum. To do this we take + // the clipping planes we received above and extract the sides from them. + + // This will extract the RIGHT side of the frustum + m_Frustum[RIGHT][A] = clip[3] - clip[0]; + m_Frustum[RIGHT][B] = clip[7] - clip[4]; + m_Frustum[RIGHT][C] = clip[11] - clip[8]; + m_Frustum[RIGHT][D] = clip[15] - clip[12]; + + // Now that we have a normal (A,B,C) and a distance (D) to the plane, + // we want to normalize that normal and distance. + + // Normalize the RIGHT side + normalizePlane(m_Frustum, RIGHT); + + // This will extract the LEFT side of the frustum + m_Frustum[LEFT][A] = clip[3] + clip[0]; + m_Frustum[LEFT][B] = clip[7] + clip[4]; + m_Frustum[LEFT][C] = clip[11] + clip[8]; + m_Frustum[LEFT][D] = clip[15] + clip[12]; + + // Normalize the LEFT side + normalizePlane(m_Frustum, LEFT); + + // This will extract the BOTTOM side of the frustum + m_Frustum[BOTTOM][A] = clip[3] + clip[1]; + m_Frustum[BOTTOM][B] = clip[7] + clip[5]; + m_Frustum[BOTTOM][C] = clip[11] + clip[9]; + m_Frustum[BOTTOM][D] = clip[15] + clip[13]; + + // Normalize the BOTTOM side + normalizePlane(m_Frustum, BOTTOM); + + // This will extract the TOP side of the frustum + m_Frustum[TOP][A] = clip[3] - clip[1]; + m_Frustum[TOP][B] = clip[7] - clip[5]; + m_Frustum[TOP][C] = clip[11] - clip[9]; + m_Frustum[TOP][D] = clip[15] - clip[13]; + + // Normalize the TOP side + normalizePlane(m_Frustum, TOP); + + // This will extract the BACK side of the frustum + m_Frustum[BACK][A] = clip[3] - clip[2]; + m_Frustum[BACK][B] = clip[7] - clip[6]; + m_Frustum[BACK][C] = clip[11] - clip[10]; + m_Frustum[BACK][D] = clip[15] - clip[14]; + + // Normalize the BACK side + normalizePlane(m_Frustum, BACK); + + // This will extract the FRONT side of the frustum + m_Frustum[FRONT][A] = clip[3] + clip[2]; + m_Frustum[FRONT][B] = clip[7] + clip[6]; + m_Frustum[FRONT][C] = clip[11] + clip[10]; + m_Frustum[FRONT][D] = clip[15] + clip[14]; + + // Normalize the FRONT side + normalizePlane(m_Frustum, FRONT); + } +} diff --git a/src/client/renderer/culling/tmp/FrustumCuller.h b/src/client/renderer/culling/tmp/FrustumCuller.h index 939093d..b23fd61 100755 --- a/src/client/renderer/culling/tmp/FrustumCuller.h +++ b/src/client/renderer/culling/tmp/FrustumCuller.h @@ -1,165 +1,163 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumCuller_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumCuller_H__ - -//package net.minecraft.client.renderer.culling; - -#include "Culler.h" -#include "../../../world/phys/AABB.h" - -class FrustumCuller: public Culler -{ - float xOff, yOff, zOff; - float frustum[6][4]; - -public: - FrustumCuller() { - ExtractFrustum(); - } - - void prepare(float xOff, float yOff, float zOff) { - this->xOff = xOff; - this->yOff = yOff; - this->zOff = zOff; - } - - //bool cubeFullyInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { - // return frustum.cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); - //} - - bool cubeFullyInFrustum( float x0, float y0, float z0, float x1, float y1, float z1 ) { - int c2 = 0; - for( int p = 0; p < 6; p++ ) { - int c = 0; - if( frustum[p][0] * (x0) + frustum[p][1] * (y0) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) c++; - if( frustum[p][0] * (x1) + frustum[p][1] * (y0) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) c++; - if( frustum[p][0] * (x0) + frustum[p][1] * (y1) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) c++; - if( frustum[p][0] * (x1) + frustum[p][1] * (y1) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) c++; - if( frustum[p][0] * (x0) + frustum[p][1] * (y0) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) c++; - if( frustum[p][0] * (x1) + frustum[p][1] * (y0) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) c++; - if( frustum[p][0] * (x0) + frustum[p][1] * (y1) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) c++; - if( frustum[p][0] * (x1) + frustum[p][1] * (y1) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) c++; - if( c == 0 ) - return false; // 0 - if( c == 8 ) - c2++; - } - return c2 == 6; //(c2 == 6) ? 2 : 1; - } - - bool isVisible(const AABB& bb) { - printf("cube is : %s\n", bb.toString().c_str()); - return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); - } - - bool cubeInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { - for(int p = 0; p < 6; p++ ) { - if( frustum[p][0] * (x0) + frustum[p][1] * (y0) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) continue; - if( frustum[p][0] * (x1) + frustum[p][1] * (y0) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) continue; - if( frustum[p][0] * (x0) + frustum[p][1] * (y1) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) continue; - if( frustum[p][0] * (x1) + frustum[p][1] * (y1) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) continue; - if( frustum[p][0] * (x0) + frustum[p][1] * (y0) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) continue; - if( frustum[p][0] * (x1) + frustum[p][1] * (y0) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) continue; - if( frustum[p][0] * (x0) + frustum[p][1] * (y1) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) continue; - if( frustum[p][0] * (x1) + frustum[p][1] * (y1) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) continue; - return false; - } - return true; - } - -private: - void ExtractFrustum() { - float proj[16]; - float modl[16]; - float clip[16]; - float t; - /* Get the current PROJECTION matrix from OpenGL */ - glGetFloatv( GL_PROJECTION_MATRIX, proj ); - /* Get the current MODELVIEW matrix from OpenGL */ - glGetFloatv( GL_MODELVIEW_MATRIX, modl ); - /* Combine the two matrices (multiply projection by modelview) */ - clip[ 0] = modl[ 0] * proj[ 0] + modl[ 1] * proj[ 4] + modl[ 2] * proj[ 8] + modl[ 3] * proj[12]; - clip[ 1] = modl[ 0] * proj[ 1] + modl[ 1] * proj[ 5] + modl[ 2] * proj[ 9] + modl[ 3] * proj[13]; - clip[ 2] = modl[ 0] * proj[ 2] + modl[ 1] * proj[ 6] + modl[ 2] * proj[10] + modl[ 3] * proj[14]; - clip[ 3] = modl[ 0] * proj[ 3] + modl[ 1] * proj[ 7] + modl[ 2] * proj[11] + modl[ 3] * proj[15]; - clip[ 4] = modl[ 4] * proj[ 0] + modl[ 5] * proj[ 4] + modl[ 6] * proj[ 8] + modl[ 7] * proj[12]; - clip[ 5] = modl[ 4] * proj[ 1] + modl[ 5] * proj[ 5] + modl[ 6] * proj[ 9] + modl[ 7] * proj[13]; - clip[ 6] = modl[ 4] * proj[ 2] + modl[ 5] * proj[ 6] + modl[ 6] * proj[10] + modl[ 7] * proj[14]; - clip[ 7] = modl[ 4] * proj[ 3] + modl[ 5] * proj[ 7] + modl[ 6] * proj[11] + modl[ 7] * proj[15]; - clip[ 8] = modl[ 8] * proj[ 0] + modl[ 9] * proj[ 4] + modl[10] * proj[ 8] + modl[11] * proj[12]; - clip[ 9] = modl[ 8] * proj[ 1] + modl[ 9] * proj[ 5] + modl[10] * proj[ 9] + modl[11] * proj[13]; - clip[10] = modl[ 8] * proj[ 2] + modl[ 9] * proj[ 6] + modl[10] * proj[10] + modl[11] * proj[14]; - clip[11] = modl[ 8] * proj[ 3] + modl[ 9] * proj[ 7] + modl[10] * proj[11] + modl[11] * proj[15]; - clip[12] = modl[12] * proj[ 0] + modl[13] * proj[ 4] + modl[14] * proj[ 8] + modl[15] * proj[12]; - clip[13] = modl[12] * proj[ 1] + modl[13] * proj[ 5] + modl[14] * proj[ 9] + modl[15] * proj[13]; - clip[14] = modl[12] * proj[ 2] + modl[13] * proj[ 6] + modl[14] * proj[10] + modl[15] * proj[14]; - clip[15] = modl[12] * proj[ 3] + modl[13] * proj[ 7] + modl[14] * proj[11] + modl[15] * proj[15]; - /* Extract the numbers for the RIGHT plane */ - frustum[0][0] = clip[ 3] - clip[ 0]; - frustum[0][1] = clip[ 7] - clip[ 4]; - frustum[0][2] = clip[11] - clip[ 8]; - frustum[0][3] = clip[15] - clip[12]; - /* Normalize the result */ - t = sqrt( frustum[0][0] * frustum[0][0] + frustum[0][1] * frustum[0][1] + frustum[0][2] * frustum[0][2] ); - frustum[0][0] /= t; - frustum[0][1] /= t; - frustum[0][2] /= t; - frustum[0][3] /= t; - /* Extract the numbers for the LEFT plane */ - frustum[1][0] = clip[ 3] + clip[ 0]; - frustum[1][1] = clip[ 7] + clip[ 4]; - frustum[1][2] = clip[11] + clip[ 8]; - frustum[1][3] = clip[15] + clip[12]; - /* Normalize the result */ - t = sqrt( frustum[1][0] * frustum[1][0] + frustum[1][1] * frustum[1][1] + frustum[1][2] * frustum[1][2] ); - frustum[1][0] /= t; - frustum[1][1] /= t; - frustum[1][2] /= t; - frustum[1][3] /= t; - /* Extract the BOTTOM plane */ - frustum[2][0] = clip[ 3] + clip[ 1]; - frustum[2][1] = clip[ 7] + clip[ 5]; - frustum[2][2] = clip[11] + clip[ 9]; - frustum[2][3] = clip[15] + clip[13]; - /* Normalize the result */ - t = sqrt( frustum[2][0] * frustum[2][0] + frustum[2][1] * frustum[2][1] + frustum[2][2] * frustum[2][2] ); - frustum[2][0] /= t; - frustum[2][1] /= t; - frustum[2][2] /= t; - frustum[2][3] /= t; - /* Extract the TOP plane */ - frustum[3][0] = clip[ 3] - clip[ 1]; - frustum[3][1] = clip[ 7] - clip[ 5]; - frustum[3][2] = clip[11] - clip[ 9]; - frustum[3][3] = clip[15] - clip[13]; - /* Normalize the result */ - t = sqrt( frustum[3][0] * frustum[3][0] + frustum[3][1] * frustum[3][1] + frustum[3][2] * frustum[3][2] ); - frustum[3][0] /= t; - frustum[3][1] /= t; - frustum[3][2] /= t; - frustum[3][3] /= t; - /* Extract the FAR plane */ - frustum[4][0] = clip[ 3] - clip[ 2]; - frustum[4][1] = clip[ 7] - clip[ 6]; - frustum[4][2] = clip[11] - clip[10]; - frustum[4][3] = clip[15] - clip[14]; - /* Normalize the result */ - t = sqrt( frustum[4][0] * frustum[4][0] + frustum[4][1] * frustum[4][1] + frustum[4][2] * frustum[4][2] ); - frustum[4][0] /= t; - frustum[4][1] /= t; - frustum[4][2] /= t; - frustum[4][3] /= t; - /* Extract the NEAR plane */ - frustum[5][0] = clip[ 3] + clip[ 2]; - frustum[5][1] = clip[ 7] + clip[ 6]; - frustum[5][2] = clip[11] + clip[10]; - frustum[5][3] = clip[15] + clip[14]; - /* Normalize the result */ - t = sqrt( frustum[5][0] * frustum[5][0] + frustum[5][1] * frustum[5][1] + frustum[5][2] * frustum[5][2] ); - frustum[5][0] /= t; - frustum[5][1] /= t; - frustum[5][2] /= t; - frustum[5][3] /= t; - } -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumCuller_H__*/ +#pragma once + +//package net.minecraft.client.renderer.culling; + +#include "Culler.h" +#include "../../../world/phys/AABB.h" + +class FrustumCuller: public Culler +{ + float xOff, yOff, zOff; + float frustum[6][4]; + +public: + FrustumCuller() { + ExtractFrustum(); + } + + void prepare(float xOff, float yOff, float zOff) { + this->xOff = xOff; + this->yOff = yOff; + this->zOff = zOff; + } + + //bool cubeFullyInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { + // return frustum.cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); + //} + + bool cubeFullyInFrustum( float x0, float y0, float z0, float x1, float y1, float z1 ) { + int c2 = 0; + for( int p = 0; p < 6; p++ ) { + int c = 0; + if( frustum[p][0] * (x0) + frustum[p][1] * (y0) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) c++; + if( frustum[p][0] * (x1) + frustum[p][1] * (y0) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) c++; + if( frustum[p][0] * (x0) + frustum[p][1] * (y1) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) c++; + if( frustum[p][0] * (x1) + frustum[p][1] * (y1) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) c++; + if( frustum[p][0] * (x0) + frustum[p][1] * (y0) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) c++; + if( frustum[p][0] * (x1) + frustum[p][1] * (y0) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) c++; + if( frustum[p][0] * (x0) + frustum[p][1] * (y1) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) c++; + if( frustum[p][0] * (x1) + frustum[p][1] * (y1) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) c++; + if( c == 0 ) + return false; // 0 + if( c == 8 ) + c2++; + } + return c2 == 6; //(c2 == 6) ? 2 : 1; + } + + bool isVisible(const AABB& bb) { + printf("cube is : %s\n", bb.toString().c_str()); + return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); + } + + bool cubeInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { + for(int p = 0; p < 6; p++ ) { + if( frustum[p][0] * (x0) + frustum[p][1] * (y0) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) continue; + if( frustum[p][0] * (x1) + frustum[p][1] * (y0) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) continue; + if( frustum[p][0] * (x0) + frustum[p][1] * (y1) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) continue; + if( frustum[p][0] * (x1) + frustum[p][1] * (y1) + frustum[p][2] * (z0) + frustum[p][3] > 0 ) continue; + if( frustum[p][0] * (x0) + frustum[p][1] * (y0) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) continue; + if( frustum[p][0] * (x1) + frustum[p][1] * (y0) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) continue; + if( frustum[p][0] * (x0) + frustum[p][1] * (y1) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) continue; + if( frustum[p][0] * (x1) + frustum[p][1] * (y1) + frustum[p][2] * (z1) + frustum[p][3] > 0 ) continue; + return false; + } + return true; + } + +private: + void ExtractFrustum() { + float proj[16]; + float modl[16]; + float clip[16]; + float t; + /* Get the current PROJECTION matrix from OpenGL */ + glGetFloatv( GL_PROJECTION_MATRIX, proj ); + /* Get the current MODELVIEW matrix from OpenGL */ + glGetFloatv( GL_MODELVIEW_MATRIX, modl ); + /* Combine the two matrices (multiply projection by modelview) */ + clip[ 0] = modl[ 0] * proj[ 0] + modl[ 1] * proj[ 4] + modl[ 2] * proj[ 8] + modl[ 3] * proj[12]; + clip[ 1] = modl[ 0] * proj[ 1] + modl[ 1] * proj[ 5] + modl[ 2] * proj[ 9] + modl[ 3] * proj[13]; + clip[ 2] = modl[ 0] * proj[ 2] + modl[ 1] * proj[ 6] + modl[ 2] * proj[10] + modl[ 3] * proj[14]; + clip[ 3] = modl[ 0] * proj[ 3] + modl[ 1] * proj[ 7] + modl[ 2] * proj[11] + modl[ 3] * proj[15]; + clip[ 4] = modl[ 4] * proj[ 0] + modl[ 5] * proj[ 4] + modl[ 6] * proj[ 8] + modl[ 7] * proj[12]; + clip[ 5] = modl[ 4] * proj[ 1] + modl[ 5] * proj[ 5] + modl[ 6] * proj[ 9] + modl[ 7] * proj[13]; + clip[ 6] = modl[ 4] * proj[ 2] + modl[ 5] * proj[ 6] + modl[ 6] * proj[10] + modl[ 7] * proj[14]; + clip[ 7] = modl[ 4] * proj[ 3] + modl[ 5] * proj[ 7] + modl[ 6] * proj[11] + modl[ 7] * proj[15]; + clip[ 8] = modl[ 8] * proj[ 0] + modl[ 9] * proj[ 4] + modl[10] * proj[ 8] + modl[11] * proj[12]; + clip[ 9] = modl[ 8] * proj[ 1] + modl[ 9] * proj[ 5] + modl[10] * proj[ 9] + modl[11] * proj[13]; + clip[10] = modl[ 8] * proj[ 2] + modl[ 9] * proj[ 6] + modl[10] * proj[10] + modl[11] * proj[14]; + clip[11] = modl[ 8] * proj[ 3] + modl[ 9] * proj[ 7] + modl[10] * proj[11] + modl[11] * proj[15]; + clip[12] = modl[12] * proj[ 0] + modl[13] * proj[ 4] + modl[14] * proj[ 8] + modl[15] * proj[12]; + clip[13] = modl[12] * proj[ 1] + modl[13] * proj[ 5] + modl[14] * proj[ 9] + modl[15] * proj[13]; + clip[14] = modl[12] * proj[ 2] + modl[13] * proj[ 6] + modl[14] * proj[10] + modl[15] * proj[14]; + clip[15] = modl[12] * proj[ 3] + modl[13] * proj[ 7] + modl[14] * proj[11] + modl[15] * proj[15]; + /* Extract the numbers for the RIGHT plane */ + frustum[0][0] = clip[ 3] - clip[ 0]; + frustum[0][1] = clip[ 7] - clip[ 4]; + frustum[0][2] = clip[11] - clip[ 8]; + frustum[0][3] = clip[15] - clip[12]; + /* Normalize the result */ + t = sqrt( frustum[0][0] * frustum[0][0] + frustum[0][1] * frustum[0][1] + frustum[0][2] * frustum[0][2] ); + frustum[0][0] /= t; + frustum[0][1] /= t; + frustum[0][2] /= t; + frustum[0][3] /= t; + /* Extract the numbers for the LEFT plane */ + frustum[1][0] = clip[ 3] + clip[ 0]; + frustum[1][1] = clip[ 7] + clip[ 4]; + frustum[1][2] = clip[11] + clip[ 8]; + frustum[1][3] = clip[15] + clip[12]; + /* Normalize the result */ + t = sqrt( frustum[1][0] * frustum[1][0] + frustum[1][1] * frustum[1][1] + frustum[1][2] * frustum[1][2] ); + frustum[1][0] /= t; + frustum[1][1] /= t; + frustum[1][2] /= t; + frustum[1][3] /= t; + /* Extract the BOTTOM plane */ + frustum[2][0] = clip[ 3] + clip[ 1]; + frustum[2][1] = clip[ 7] + clip[ 5]; + frustum[2][2] = clip[11] + clip[ 9]; + frustum[2][3] = clip[15] + clip[13]; + /* Normalize the result */ + t = sqrt( frustum[2][0] * frustum[2][0] + frustum[2][1] * frustum[2][1] + frustum[2][2] * frustum[2][2] ); + frustum[2][0] /= t; + frustum[2][1] /= t; + frustum[2][2] /= t; + frustum[2][3] /= t; + /* Extract the TOP plane */ + frustum[3][0] = clip[ 3] - clip[ 1]; + frustum[3][1] = clip[ 7] - clip[ 5]; + frustum[3][2] = clip[11] - clip[ 9]; + frustum[3][3] = clip[15] - clip[13]; + /* Normalize the result */ + t = sqrt( frustum[3][0] * frustum[3][0] + frustum[3][1] * frustum[3][1] + frustum[3][2] * frustum[3][2] ); + frustum[3][0] /= t; + frustum[3][1] /= t; + frustum[3][2] /= t; + frustum[3][3] /= t; + /* Extract the FAR plane */ + frustum[4][0] = clip[ 3] - clip[ 2]; + frustum[4][1] = clip[ 7] - clip[ 6]; + frustum[4][2] = clip[11] - clip[10]; + frustum[4][3] = clip[15] - clip[14]; + /* Normalize the result */ + t = sqrt( frustum[4][0] * frustum[4][0] + frustum[4][1] * frustum[4][1] + frustum[4][2] * frustum[4][2] ); + frustum[4][0] /= t; + frustum[4][1] /= t; + frustum[4][2] /= t; + frustum[4][3] /= t; + /* Extract the NEAR plane */ + frustum[5][0] = clip[ 3] + clip[ 2]; + frustum[5][1] = clip[ 7] + clip[ 6]; + frustum[5][2] = clip[11] + clip[10]; + frustum[5][3] = clip[15] + clip[14]; + /* Normalize the result */ + t = sqrt( frustum[5][0] * frustum[5][0] + frustum[5][1] * frustum[5][1] + frustum[5][2] * frustum[5][2] ); + frustum[5][0] /= t; + frustum[5][1] /= t; + frustum[5][2] /= t; + frustum[5][3] /= t; + } +}; + diff --git a/src/client/renderer/culling/tmp/FrustumData.h b/src/client/renderer/culling/tmp/FrustumData.h index 942b74c..3a6d9ba 100755 --- a/src/client/renderer/culling/tmp/FrustumData.h +++ b/src/client/renderer/culling/tmp/FrustumData.h @@ -1,102 +1,100 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumData_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumData_H__ - -//package net.minecraft.client.renderer.culling; - -#include "world/phys/AABB.h" - - -/*public*/ class FrustumData -{ - //enum FrustumSide - /*public*/ static const int RIGHT = 0; // The RIGHT side of the frustum - /*public*/ static const int LEFT = 1; // The LEFT side of the frustum - /*public*/ static const int BOTTOM = 2; // The BOTTOM side of the frustum - /*public*/ static const int TOP = 3; // The TOP side of the frustum - /*public*/ static const int BACK = 4; // The BACK side of the frustum - /*public*/ static const int FRONT = 5; // The FRONT side of the frustum - - // Like above, instead of saying a number for the ABC and D of the plane, we - // want to be more descriptive. - /*public*/ static const int A = 0; // The X value of the plane's normal - /*public*/ static const int B = 1; // The Y value of the plane's normal - /*public*/ static const int C = 2; // The Z value of the plane's normal - /*public*/ static const int D = 3; // The distance the plane is from the origin - - /*public*/ float[][] m_Frustum = /*new*/ float[16][16]; - /*public*/ float[] proj = /*new*/ float[16]; - /*public*/ float[] modl = /*new*/ float[16]; - /*public*/ float[] clip = /*new*/ float[16]; -/* - /*public*/ FrustumData(float[][] mFrustum, float[] proj, float[] modl, float[] clip) - { - m_Frustum = mFrustum; - this->proj = proj; - this->modl = modl; - this->clip = clip; - }*/ - /*public*/ bool pointInFrustum(float x, float y, float z) - { - for (int i = 0; i < 6; i++) - { - if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= 0) - { - return false; - } - } - - return true; - } - /*public*/ bool sphereInFrustum(float x, float y, float z, float radius) - { - for (int i = 0; i < 6; i++) - { - if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= -radius) - { - return false; - } - } - - return true; - } - /*public*/ bool cubeFullyInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) - { - for (int i = 0; i < 6; i++) - { - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; - } - - return true; - } - - /*public*/ bool cubeInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) - { - for (int i = 0; i < 6; i++) - { - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; - - return false; - } - - return true; - } - /*public*/ bool isVisible(AABB aabb) - { - return cubeInFrustum(aabb.x0, aabb.y0, aabb.z0, aabb.x1, aabb.y1, aabb.z1); - } -} -#endif /*NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumData_H__*/ +#pragma once + +//package net.minecraft.client.renderer.culling; + +#include "world/phys/AABB.h" + + +/*public*/ class FrustumData +{ + //enum FrustumSide + /*public*/ static const int RIGHT = 0; // The RIGHT side of the frustum + /*public*/ static const int LEFT = 1; // The LEFT side of the frustum + /*public*/ static const int BOTTOM = 2; // The BOTTOM side of the frustum + /*public*/ static const int TOP = 3; // The TOP side of the frustum + /*public*/ static const int BACK = 4; // The BACK side of the frustum + /*public*/ static const int FRONT = 5; // The FRONT side of the frustum + + // Like above, instead of saying a number for the ABC and D of the plane, we + // want to be more descriptive. + /*public*/ static const int A = 0; // The X value of the plane's normal + /*public*/ static const int B = 1; // The Y value of the plane's normal + /*public*/ static const int C = 2; // The Z value of the plane's normal + /*public*/ static const int D = 3; // The distance the plane is from the origin + + /*public*/ float[][] m_Frustum = /*new*/ float[16][16]; + /*public*/ float[] proj = /*new*/ float[16]; + /*public*/ float[] modl = /*new*/ float[16]; + /*public*/ float[] clip = /*new*/ float[16]; +/* + /*public*/ FrustumData(float[][] mFrustum, float[] proj, float[] modl, float[] clip) + { + m_Frustum = mFrustum; + this->proj = proj; + this->modl = modl; + this->clip = clip; + }*/ + /*public*/ bool pointInFrustum(float x, float y, float z) + { + for (int i = 0; i < 6; i++) + { + if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= 0) + { + return false; + } + } + + return true; + } + /*public*/ bool sphereInFrustum(float x, float y, float z, float radius) + { + for (int i = 0; i < 6; i++) + { + if (m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] <= -radius) + { + return false; + } + } + + return true; + } + /*public*/ bool cubeFullyInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) + { + for (int i = 0; i < 6; i++) + { + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; + if (!(m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0)) return false; + } + + return true; + } + + /*public*/ bool cubeInFrustum(float x1, float y1, float z1, float x2, float y2, float z2) + { + for (int i = 0; i < 6; i++) + { + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z1) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y1) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x1) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; + if (m_Frustum[i][A] * (x2) + m_Frustum[i][B] * (y2) + m_Frustum[i][C] * (z2) + m_Frustum[i][D] > 0) continue; + + return false; + } + + return true; + } + /*public*/ bool isVisible(AABB aabb) + { + return cubeInFrustum(aabb.x0, aabb.y0, aabb.z0, aabb.x1, aabb.y1, aabb.z1); + } +} diff --git a/src/client/renderer/culling/tmp/_FrustumCuller.h b/src/client/renderer/culling/tmp/_FrustumCuller.h index f93edac..6202855 100755 --- a/src/client/renderer/culling/tmp/_FrustumCuller.h +++ b/src/client/renderer/culling/tmp/_FrustumCuller.h @@ -1,37 +1,35 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumCuller_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumCuller_H__ - -//package net.minecraft.client.renderer.culling; - -#include "world/phys/AABB.h" - -/*public*/ class FrustumCuller: /*implements-interface*/ public Culler { - - /*private*/ FrustumData frustum; - - /*public*/ FrustumCuller() { - frustum = Frustum.getFrustum(); - } - - /*private*/ float xOff, yOff, zOff; - - /*public*/ void prepare(float xOff, float yOff, float zOff) { - this->xOff = xOff; - this->yOff = yOff; - this->zOff = zOff; - } - - /*public*/ bool cubeFullyInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { - return frustum.cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); - } - - /*public*/ bool cubeInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { - return frustum.cubeInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); - } - - /*public*/ bool isVisible(AABB bb) { - return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); - } -} - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_CULLING__FrustumCuller_H__*/ +#pragma once + +//package net.minecraft.client.renderer.culling; + +#include "world/phys/AABB.h" + +/*public*/ class FrustumCuller: /*implements-interface*/ public Culler { + + /*private*/ FrustumData frustum; + + /*public*/ FrustumCuller() { + frustum = Frustum.getFrustum(); + } + + /*private*/ float xOff, yOff, zOff; + + /*public*/ void prepare(float xOff, float yOff, float zOff) { + this->xOff = xOff; + this->yOff = yOff; + this->zOff = zOff; + } + + /*public*/ bool cubeFullyInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { + return frustum.cubeFullyInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); + } + + /*public*/ bool cubeInFrustum(float x0, float y0, float z0, float x1, float y1, float z1) { + return frustum.cubeInFrustum(x0 - xOff, y0 - yOff, z0 - zOff, x1 - xOff, y1 - yOff, z1 - zOff); + } + + /*public*/ bool isVisible(AABB bb) { + return cubeInFrustum(bb.x0, bb.y0, bb.z0, bb.x1, bb.y1, bb.z1); + } +} + diff --git a/src/client/renderer/entity/ArrowRenderer.h b/src/client/renderer/entity/ArrowRenderer.h index a69627f..a220122 100755 --- a/src/client/renderer/entity/ArrowRenderer.h +++ b/src/client/renderer/entity/ArrowRenderer.h @@ -1,9 +1,7 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ArrowRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ArrowRenderer_H__ -#include "EntityRenderer.h" - -class ArrowRenderer : public EntityRenderer { - void render(Entity* arrow, float x, float y, float z, float rot, float a); -}; - -#endif /* NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ArrowRenderer_H__ */ \ No newline at end of file +#pragma once +#include "EntityRenderer.h" + +class ArrowRenderer : public EntityRenderer { + void render(Entity* arrow, float x, float y, float z, float rot, float a); +}; + diff --git a/src/client/renderer/entity/ChickenRenderer.h b/src/client/renderer/entity/ChickenRenderer.h index f3e1bcf..1e9dc1a 100755 --- a/src/client/renderer/entity/ChickenRenderer.h +++ b/src/client/renderer/entity/ChickenRenderer.h @@ -1,22 +1,20 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ChickenRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ChickenRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "MobRenderer.h" - -class Mob; - -class ChickenRenderer: public MobRenderer -{ - typedef MobRenderer super; -public: - ChickenRenderer(Model* model, float shadow); - - void render(Entity* mob, float x, float y, float z, float rot, float a); - -protected: - float getBob(Mob* mob_, float a); -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ChickenRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "MobRenderer.h" + +class Mob; + +class ChickenRenderer: public MobRenderer +{ + typedef MobRenderer super; +public: + ChickenRenderer(Model* model, float shadow); + + void render(Entity* mob, float x, float y, float z, float rot, float a); + +protected: + float getBob(Mob* mob_, float a); +}; + diff --git a/src/client/renderer/entity/CreeperRenderer.h b/src/client/renderer/entity/CreeperRenderer.h index 594bc48..077d832 100755 --- a/src/client/renderer/entity/CreeperRenderer.h +++ b/src/client/renderer/entity/CreeperRenderer.h @@ -1,94 +1,92 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__CreeperRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__CreeperRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "MobRenderer.h" - -#include "../../model/CreeperModel.h" -#include "../../model/Model.h" -#include "../../../world/entity/monster/Creeper.h" -#include "../../../util/Mth.h" - -class CreeperRenderer: public MobRenderer -{ - typedef MobRenderer super; -public: - CreeperRenderer() - : super(new CreeperModel(), 0.5f) - { - } - -protected: - void scale(Mob* mob, float a) { - Creeper* creeper = (Creeper*) mob; - - float g = creeper->getSwelling(a); - - float wobble = 1.0f + Mth::sin(g * 100) * g * 0.01f; - if (g < 0) g = 0; - if (g > 1) g = 1; - g = g * g; - g = g * g; - float s = (1.0f + g * 0.4f) * wobble; - float hs = (1.0f + g * 0.1f) / wobble; - glScalef(s, hs, s); - } - - int getOverlayColor(Mob* mob, float br, float a) { - Creeper* creeper = (Creeper*) mob; - - float step = creeper->getSwelling(a); - - if ((int) (step * 10) % 2 == 0) return 0; - - int _a = (int) (step * 0.2f * 255); - if (_a < 0) _a = 0; - if (_a > 255) _a = 255; - - int r = 255; - int g = 255; - int b = 255; - - return (_a << 24) | (r << 16) | (g << 8) | b; - } - - // int prepareArmor(Mob* mob, int layer, float a) { - //Creeper* creeper = (Creeper*) mob; - // if (creeper->isPowered()) { - // if (layer == 1) { - // float time = mob->tickCount + a; - // bindTexture("/armor/power.png"); - // glMatrixMode(GL_TEXTURE); - // glLoadIdentity(); - // float uo = time * 0.01f; - // float vo = time * 0.01f; - // glTranslatef(uo, vo, 0); - // setArmor(armorModel); - // glMatrixMode(GL_MODELVIEW); - // glEnable(GL_BLEND); - // float br = 0.5f; - // glColor4f2(br, br, br, 1); - // glDisable(GL_LIGHTING); - // glBlendFunc2(GL_ONE, GL_ONE); - // return 1; - // } - // if (layer == 2) { - // glMatrixMode(GL_TEXTURE); - // glLoadIdentity(); - // glMatrixMode(GL_MODELVIEW); - // glEnable(GL_LIGHTING); - // glDisable(GL_BLEND); - // } - // } - // return -1; - // } - - // int prepareArmorOverlay(Mob* mob, int layer, float a) { - // return -1; - // } -//private: - //Model* armorModel = /*new*/ CreeperModel(2); -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__CreeperRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "MobRenderer.h" + +#include "../../model/CreeperModel.h" +#include "../../model/Model.h" +#include "../../../world/entity/monster/Creeper.h" +#include "../../../util/Mth.h" + +class CreeperRenderer: public MobRenderer +{ + typedef MobRenderer super; +public: + CreeperRenderer() + : super(new CreeperModel(), 0.5f) + { + } + +protected: + void scale(Mob* mob, float a) { + Creeper* creeper = (Creeper*) mob; + + float g = creeper->getSwelling(a); + + float wobble = 1.0f + Mth::sin(g * 100) * g * 0.01f; + if (g < 0) g = 0; + if (g > 1) g = 1; + g = g * g; + g = g * g; + float s = (1.0f + g * 0.4f) * wobble; + float hs = (1.0f + g * 0.1f) / wobble; + glScalef(s, hs, s); + } + + int getOverlayColor(Mob* mob, float br, float a) { + Creeper* creeper = (Creeper*) mob; + + float step = creeper->getSwelling(a); + + if ((int) (step * 10) % 2 == 0) return 0; + + int _a = (int) (step * 0.2f * 255); + if (_a < 0) _a = 0; + if (_a > 255) _a = 255; + + int r = 255; + int g = 255; + int b = 255; + + return (_a << 24) | (r << 16) | (g << 8) | b; + } + + // int prepareArmor(Mob* mob, int layer, float a) { + //Creeper* creeper = (Creeper*) mob; + // if (creeper->isPowered()) { + // if (layer == 1) { + // float time = mob->tickCount + a; + // bindTexture("/armor/power.png"); + // glMatrixMode(GL_TEXTURE); + // glLoadIdentity(); + // float uo = time * 0.01f; + // float vo = time * 0.01f; + // glTranslatef(uo, vo, 0); + // setArmor(armorModel); + // glMatrixMode(GL_MODELVIEW); + // glEnable(GL_BLEND); + // float br = 0.5f; + // glColor4f2(br, br, br, 1); + // glDisable(GL_LIGHTING); + // glBlendFunc2(GL_ONE, GL_ONE); + // return 1; + // } + // if (layer == 2) { + // glMatrixMode(GL_TEXTURE); + // glLoadIdentity(); + // glMatrixMode(GL_MODELVIEW); + // glEnable(GL_LIGHTING); + // glDisable(GL_BLEND); + // } + // } + // return -1; + // } + + // int prepareArmorOverlay(Mob* mob, int layer, float a) { + // return -1; + // } +//private: + //Model* armorModel = /*new*/ CreeperModel(2); +}; + diff --git a/src/client/renderer/entity/EntityRenderDispatcher.h b/src/client/renderer/entity/EntityRenderDispatcher.h index 06c4eac..1536370 100755 --- a/src/client/renderer/entity/EntityRenderDispatcher.h +++ b/src/client/renderer/entity/EntityRenderDispatcher.h @@ -1,76 +1,74 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__EntityRenderDispatcher_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__EntityRenderDispatcher_H__ - -//package net.minecraft.client.renderer.entity; - -#include -#include "../../../world/entity/EntityRendererId.h" - -class EntityRenderer; -class Level; -class Font; -class Textures; -class ItemInHandRenderer; -class Minecraft; -class Textures; -class Options; -class Entity; -class Mob; - -class EntityRenderDispatcher -{ - typedef std::map RendererMap; - typedef RendererMap::iterator RendererIterator; - typedef RendererMap::const_iterator RendererCIterator; - -public: - EntityRenderDispatcher(); - ~EntityRenderDispatcher(); - static EntityRenderDispatcher* getInstance(); - - static void destroy(); - - void prepare(Level* level, Font* font, Mob* player, Options* options, float a); - - void render(Entity* entity, float a); - void render(Entity* entity, float x, float y, float z, float rot, float a); - EntityRenderer* getRenderer( Entity* entity ); - EntityRenderer* getRenderer( EntityRendererId rendererId ); - - void setLevel(Level* level); - void setMinecraft(Minecraft* minecraft); - - float distanceToSqr(float x, float y, float z); - - Font* getFont(); - - void onGraphicsReset(); -private: - void assign(EntityRendererId id, EntityRenderer* renderer); -public: - ItemInHandRenderer* itemInHandRenderer; - - //TripodCameraRenderer tripodCameraRenderer; - - static float xOff, yOff, zOff; - - Textures* textures; - Level* level; - Minecraft* minecraft; - Mob* cameraEntity; - - float playerRotY; - float playerRotX; - Options* options; - - float xPlayer, yPlayer, zPlayer; - -private: - static EntityRenderDispatcher* instance; - - Font* _font; - // For onGraphicsReset etc - RendererMap _renderers; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__EntityRenderDispatcher_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include +#include "../../../world/entity/EntityRendererId.h" + +class EntityRenderer; +class Level; +class Font; +class Textures; +class ItemInHandRenderer; +class Minecraft; +class Textures; +class Options; +class Entity; +class Mob; + +class EntityRenderDispatcher +{ + typedef std::map RendererMap; + typedef RendererMap::iterator RendererIterator; + typedef RendererMap::const_iterator RendererCIterator; + +public: + EntityRenderDispatcher(); + ~EntityRenderDispatcher(); + static EntityRenderDispatcher* getInstance(); + + static void destroy(); + + void prepare(Level* level, Font* font, Mob* player, Options* options, float a); + + void render(Entity* entity, float a); + void render(Entity* entity, float x, float y, float z, float rot, float a); + EntityRenderer* getRenderer( Entity* entity ); + EntityRenderer* getRenderer( EntityRendererId rendererId ); + + void setLevel(Level* level); + void setMinecraft(Minecraft* minecraft); + + float distanceToSqr(float x, float y, float z); + + Font* getFont(); + + void onGraphicsReset(); +private: + void assign(EntityRendererId id, EntityRenderer* renderer); +public: + ItemInHandRenderer* itemInHandRenderer; + + //TripodCameraRenderer tripodCameraRenderer; + + static float xOff, yOff, zOff; + + Textures* textures; + Level* level; + Minecraft* minecraft; + Mob* cameraEntity; + + float playerRotY; + float playerRotX; + Options* options; + + float xPlayer, yPlayer, zPlayer; + +private: + static EntityRenderDispatcher* instance; + + Font* _font; + // For onGraphicsReset etc + RendererMap _renderers; +}; + diff --git a/src/client/renderer/entity/EntityRenderer.h b/src/client/renderer/entity/EntityRenderer.h index 318f7f2..dde97fe 100755 --- a/src/client/renderer/entity/EntityRenderer.h +++ b/src/client/renderer/entity/EntityRenderer.h @@ -1,40 +1,38 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__EntityRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__EntityRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include -#include "../../model/HumanoidModel.h" - -class Textures; -class Tesselator; -class EntityRenderDispatcher; -class Entity; -class AABB; -class Font; - -class EntityRenderer -{ -protected: - EntityRenderer(); -public: - virtual ~EntityRenderer() {} - void init(EntityRenderDispatcher* entityRenderDispatcher); - - virtual void render(Entity* entity, float x, float y, float z, float rot, float a) = 0; - static void render(const AABB& bb, float xo, float yo, float zo); - static void renderFlat(const AABB& bb); - - Font* getFont(); - - virtual void onGraphicsReset() {} - -protected: - void bindTexture(const std::string& resourceName); - - float shadowRadius; - float shadowStrength; - static EntityRenderDispatcher* entityRenderDispatcher; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__EntityRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include +#include "../../model/HumanoidModel.h" + +class Textures; +class Tesselator; +class EntityRenderDispatcher; +class Entity; +class AABB; +class Font; + +class EntityRenderer +{ +protected: + EntityRenderer(); +public: + virtual ~EntityRenderer() {} + void init(EntityRenderDispatcher* entityRenderDispatcher); + + virtual void render(Entity* entity, float x, float y, float z, float rot, float a) = 0; + static void render(const AABB& bb, float xo, float yo, float zo); + static void renderFlat(const AABB& bb); + + Font* getFont(); + + virtual void onGraphicsReset() {} + +protected: + void bindTexture(const std::string& resourceName); + + float shadowRadius; + float shadowStrength; + static EntityRenderDispatcher* entityRenderDispatcher; +}; + diff --git a/src/client/renderer/entity/FallingTileRenderer.h b/src/client/renderer/entity/FallingTileRenderer.h index 0147c8a..e987f4b 100755 --- a/src/client/renderer/entity/FallingTileRenderer.h +++ b/src/client/renderer/entity/FallingTileRenderer.h @@ -1,22 +1,20 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__FallingTileRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__FallingTileRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "EntityRenderer.h" - -class TileRenderer; - -class FallingTileRenderer: public EntityRenderer -{ - typedef EntityRenderer super; -public: - FallingTileRenderer(); - ~FallingTileRenderer(); - - void render(Entity* e, float x, float y, float z, float rot, float a); -private: - TileRenderer* tileRenderer; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__FallingTileRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "EntityRenderer.h" + +class TileRenderer; + +class FallingTileRenderer: public EntityRenderer +{ + typedef EntityRenderer super; +public: + FallingTileRenderer(); + ~FallingTileRenderer(); + + void render(Entity* e, float x, float y, float z, float rot, float a); +private: + TileRenderer* tileRenderer; +}; + diff --git a/src/client/renderer/entity/HumanoidMobRenderer.h b/src/client/renderer/entity/HumanoidMobRenderer.h index a78ade8..c02441e 100755 --- a/src/client/renderer/entity/HumanoidMobRenderer.h +++ b/src/client/renderer/entity/HumanoidMobRenderer.h @@ -1,31 +1,29 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__HumanoidMobRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__HumanoidMobRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "MobRenderer.h" - -class HumanoidModel; -class Mob; - -class HumanoidMobRenderer: public MobRenderer -{ - typedef MobRenderer super; -public: - HumanoidMobRenderer(HumanoidModel* humanoidModel, float shadow); - - void renderHand(); - void render(Entity* mob_, float x, float y, float z, float rot, float a); -protected: - void additionalRendering(Mob* mob, float a); - - HumanoidModel* humanoidModel; - - // Last rotation values for cape smoothing (reduces jitter) - float lastCapeXRot; - float lastCapeZRot; -private: - // i guess ill keep this just in case seomthing breaks -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__HumanoidMobRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "MobRenderer.h" + +class HumanoidModel; +class Mob; + +class HumanoidMobRenderer: public MobRenderer +{ + typedef MobRenderer super; +public: + HumanoidMobRenderer(HumanoidModel* humanoidModel, float shadow); + + void renderHand(); + void render(Entity* mob_, float x, float y, float z, float rot, float a); +protected: + void additionalRendering(Mob* mob, float a); + + HumanoidModel* humanoidModel; + + // Last rotation values for cape smoothing (reduces jitter) + float lastCapeXRot; + float lastCapeZRot; +private: + // i guess ill keep this just in case seomthing breaks +}; + diff --git a/src/client/renderer/entity/ItemRenderer.h b/src/client/renderer/entity/ItemRenderer.h index 9fb88f6..9931e7d 100755 --- a/src/client/renderer/entity/ItemRenderer.h +++ b/src/client/renderer/entity/ItemRenderer.h @@ -1,38 +1,36 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ItemRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ItemRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "EntityRenderer.h" -#include "../../../util/Random.h" - -class Font; -class Entity; -class ItemInstance; -class Textures; -class Tesselator; -class TileRenderer; - -class ItemRenderer: public EntityRenderer -{ -public: - ItemRenderer(); - - void render(Entity* itemEntity_, float x, float y, float z, float rot, float a); - static void renderGuiItem(Font* font, Textures* textures, const ItemInstance* item, float x, float y, bool fancy); - static void renderGuiItem(Font* font, Textures* textures, const ItemInstance* item, float x, float y, float w, float h, bool fancy); - static void renderGuiItemCorrect(Font* font, Textures* textures, const ItemInstance* item, int x, int y); - //void renderGuiItemDecorations(Font* font, Textures* textures, ItemInstance* item, int x, int y); - static void renderGuiItemDecorations(const ItemInstance* item, float x, float y); - - static void blit(float x, float y, float sx, float sy, float w, float h); - static int getAtlasPos(const ItemInstance* item); - - static void teardown_static(); -private: - static void fillRect(Tesselator& t, float x, float y, float w, float h, int c); - static TileRenderer* tileRenderer; - Random random; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ItemRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "EntityRenderer.h" +#include "../../../util/Random.h" + +class Font; +class Entity; +class ItemInstance; +class Textures; +class Tesselator; +class TileRenderer; + +class ItemRenderer: public EntityRenderer +{ +public: + ItemRenderer(); + + void render(Entity* itemEntity_, float x, float y, float z, float rot, float a); + static void renderGuiItem(Font* font, Textures* textures, const ItemInstance* item, float x, float y, bool fancy); + static void renderGuiItem(Font* font, Textures* textures, const ItemInstance* item, float x, float y, float w, float h, bool fancy); + static void renderGuiItemCorrect(Font* font, Textures* textures, const ItemInstance* item, int x, int y); + //void renderGuiItemDecorations(Font* font, Textures* textures, ItemInstance* item, int x, int y); + static void renderGuiItemDecorations(const ItemInstance* item, float x, float y); + + static void blit(float x, float y, float sx, float sy, float w, float h); + static int getAtlasPos(const ItemInstance* item); + + static void teardown_static(); +private: + static void fillRect(Tesselator& t, float x, float y, float w, float h, int c); + static TileRenderer* tileRenderer; + Random random; +}; + diff --git a/src/client/renderer/entity/ItemSpriteRenderer.h b/src/client/renderer/entity/ItemSpriteRenderer.h index 5987bc9..d62c105 100755 --- a/src/client/renderer/entity/ItemSpriteRenderer.h +++ b/src/client/renderer/entity/ItemSpriteRenderer.h @@ -1,18 +1,16 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ItemSpriteRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ItemSpriteRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "EntityRenderer.h" - -class ItemSpriteRenderer: public EntityRenderer -{ -public: - ItemSpriteRenderer(int icon); - - void render(Entity* e, float x, float y, float z, float rot, float a); -private: - int icon; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__ItemSpriteRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "EntityRenderer.h" + +class ItemSpriteRenderer: public EntityRenderer +{ +public: + ItemSpriteRenderer(int icon); + + void render(Entity* e, float x, float y, float z, float rot, float a); +private: + int icon; +}; + diff --git a/src/client/renderer/entity/MobRenderer.h b/src/client/renderer/entity/MobRenderer.h index fee7786..5f53638 100755 --- a/src/client/renderer/entity/MobRenderer.h +++ b/src/client/renderer/entity/MobRenderer.h @@ -1,51 +1,49 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__MobRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__MobRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "EntityRenderer.h" - -#include - -class Model; -class Entity; -class Mob; - -class MobRenderer: public EntityRenderer -{ - static const int MAX_ARMOR_LAYERS = 4; -public: - // @note: MobRenderer::model will be deleted automagically - // Armor models (setArmor(Model*)) is to be deleted by derived classes. - MobRenderer(Model* model, float shadow); - ~MobRenderer(); - - virtual int prepareArmor(Mob* mob, int layer, float a); - - virtual void setupPosition(Entity* mob, float x, float y, float z); - virtual void setupRotations(Entity* mob_, float bob, float bodyRot, float a); - - virtual float getAttackAnim(Mob* mob, float a); - virtual float getBob(Mob* mob, float a); - - virtual float getFlipDegrees(Mob* mob); - - virtual int getOverlayColor(Mob* mob, float br, float a); - - virtual void scale(Mob* mob, float a); - - virtual void render(Entity* mob_, float x, float y, float z, float rot, float a); - virtual void renderName(Mob* mob, float x, float y, float z); - virtual void renderNameTag(Mob* mob, const std::string& name, float x, float y, float z, int maxDist); - virtual void additionalRendering(Mob* mob, float a); - - virtual void onGraphicsReset(); -protected: - void setArmor(Model* armor); - Model* getArmor(); - Model* model; // allows derived renderers to swap models dynamically for skin formats -private: - Model* armor; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__MobRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "EntityRenderer.h" + +#include + +class Model; +class Entity; +class Mob; + +class MobRenderer: public EntityRenderer +{ + static const int MAX_ARMOR_LAYERS = 4; +public: + // @note: MobRenderer::model will be deleted automagically + // Armor models (setArmor(Model*)) is to be deleted by derived classes. + MobRenderer(Model* model, float shadow); + ~MobRenderer(); + + virtual int prepareArmor(Mob* mob, int layer, float a); + + virtual void setupPosition(Entity* mob, float x, float y, float z); + virtual void setupRotations(Entity* mob_, float bob, float bodyRot, float a); + + virtual float getAttackAnim(Mob* mob, float a); + virtual float getBob(Mob* mob, float a); + + virtual float getFlipDegrees(Mob* mob); + + virtual int getOverlayColor(Mob* mob, float br, float a); + + virtual void scale(Mob* mob, float a); + + virtual void render(Entity* mob_, float x, float y, float z, float rot, float a); + virtual void renderName(Mob* mob, float x, float y, float z); + virtual void renderNameTag(Mob* mob, const std::string& name, float x, float y, float z, int maxDist); + virtual void additionalRendering(Mob* mob, float a); + + virtual void onGraphicsReset(); +protected: + void setArmor(Model* armor); + Model* getArmor(); + Model* model; // allows derived renderers to swap models dynamically for skin formats +private: + Model* armor; +}; + diff --git a/src/client/renderer/entity/PaintingRenderer.h b/src/client/renderer/entity/PaintingRenderer.h index cc8d6ac..58b3333 100755 --- a/src/client/renderer/entity/PaintingRenderer.h +++ b/src/client/renderer/entity/PaintingRenderer.h @@ -1,12 +1,10 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__PaintingRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__PaintingRenderer_H__ -#include "EntityRenderer.h" -class Painting; -class PaintingRenderer : public EntityRenderer { -public: - void render(Entity* entity, float x, float y, float z, float rot, float a); -private: - void renderPainting(Painting* painting, int w, int h, int uo, int vo, float a); -}; - -#endif /* NET_MINECRAFT_CLIENT_RENDERER_ENTITY__PaintingRenderer_H__ */ \ No newline at end of file +#pragma once +#include "EntityRenderer.h" +class Painting; +class PaintingRenderer : public EntityRenderer { +public: + void render(Entity* entity, float x, float y, float z, float rot, float a); +private: + void renderPainting(Painting* painting, int w, int h, int uo, int vo, float a); +}; + diff --git a/src/client/renderer/entity/PigRenderer.h b/src/client/renderer/entity/PigRenderer.h index 80edbac..261456a 100755 --- a/src/client/renderer/entity/PigRenderer.h +++ b/src/client/renderer/entity/PigRenderer.h @@ -1,29 +1,27 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__PigRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__PigRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "../../model/Model.h" -#include "../../../world/entity/animal/Pig.h" - -class PigRenderer: public MobRenderer -{ - typedef MobRenderer super; -public: - PigRenderer(Model* model, Model* armor, float shadow) - : super(model, shadow) - { - // setArmor(armor); - } - - //void render(Entity* mob, float x, float y, float z, float rot, float a) { - // super::render(mob, x, y, z, rot, a); - //} -protected: - //int prepareArmor(Entity* pig, int layer, float a) { - // bindTexture("/mob/saddle.png"); - // return (layer == 0 && pig->hasSaddle()) ? 1 : -1; - //} -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__PigRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "../../model/Model.h" +#include "../../../world/entity/animal/Pig.h" + +class PigRenderer: public MobRenderer +{ + typedef MobRenderer super; +public: + PigRenderer(Model* model, Model* armor, float shadow) + : super(model, shadow) + { + // setArmor(armor); + } + + //void render(Entity* mob, float x, float y, float z, float rot, float a) { + // super::render(mob, x, y, z, rot, a); + //} +protected: + //int prepareArmor(Entity* pig, int layer, float a) { + // bindTexture("/mob/saddle.png"); + // return (layer == 0 && pig->hasSaddle()) ? 1 : -1; + //} +}; + diff --git a/src/client/renderer/entity/PlayerRenderer.h b/src/client/renderer/entity/PlayerRenderer.h index d4b25e2..1552277 100755 --- a/src/client/renderer/entity/PlayerRenderer.h +++ b/src/client/renderer/entity/PlayerRenderer.h @@ -1,30 +1,28 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__PlayerRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__PlayerRenderer_H__ - -#include "HumanoidMobRenderer.h" - -class PlayerRenderer : public HumanoidMobRenderer -{ - typedef HumanoidMobRenderer super; -public: - PlayerRenderer(HumanoidModel* humanoidModel, float shadow); - ~PlayerRenderer(); - - virtual int prepareArmor(Mob* mob, int layer, float a); - bool isModernPlayerSkin(Mob* mob); - virtual void render(Entity* mob, float x, float y, float z, float rot, float a); - - virtual void setupPosition(Entity* mob, float x, float y, float z); - virtual void setupRotations(Entity* mob, float bob, float bodyRot, float a); - - virtual void renderName(Mob* mob, float x, float y, float z); - virtual void onGraphicsReset(); -private: - HumanoidModel* playerModel32; - HumanoidModel* playerModel64; - HumanoidModel* armorParts1; - HumanoidModel* armorParts2; -}; - - -#endif /* NET_MINECRAFT_CLIENT_RENDERER_ENTITY__PlayerRenderer_H__ */ \ No newline at end of file +#pragma once + +#include "HumanoidMobRenderer.h" + +class PlayerRenderer : public HumanoidMobRenderer +{ + typedef HumanoidMobRenderer super; +public: + PlayerRenderer(HumanoidModel* humanoidModel, float shadow); + ~PlayerRenderer(); + + virtual int prepareArmor(Mob* mob, int layer, float a); + bool isModernPlayerSkin(Mob* mob); + virtual void render(Entity* mob, float x, float y, float z, float rot, float a); + + virtual void setupPosition(Entity* mob, float x, float y, float z); + virtual void setupRotations(Entity* mob, float bob, float bodyRot, float a); + + virtual void renderName(Mob* mob, float x, float y, float z); + virtual void onGraphicsReset(); +private: + HumanoidModel* playerModel32; + HumanoidModel* playerModel64; + HumanoidModel* armorParts1; + HumanoidModel* armorParts2; +}; + + diff --git a/src/client/renderer/entity/SheepRenderer.h b/src/client/renderer/entity/SheepRenderer.h index 7998933..c074d45 100755 --- a/src/client/renderer/entity/SheepRenderer.h +++ b/src/client/renderer/entity/SheepRenderer.h @@ -1,20 +1,18 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__SheepRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__SheepRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "MobRenderer.h" -class Mob; - -class SheepRenderer: public MobRenderer -{ - typedef MobRenderer super; - -public: - SheepRenderer(Model* model, Model* armor, float shadow); - ~SheepRenderer(); -protected: - int prepareArmor(Mob* sheep, int layer, float a); -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__SheepRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "MobRenderer.h" +class Mob; + +class SheepRenderer: public MobRenderer +{ + typedef MobRenderer super; + +public: + SheepRenderer(Model* model, Model* armor, float shadow); + ~SheepRenderer(); +protected: + int prepareArmor(Mob* sheep, int layer, float a); +}; + diff --git a/src/client/renderer/entity/SpiderRenderer.h b/src/client/renderer/entity/SpiderRenderer.h index 9bdfdc8..ef41f95 100755 --- a/src/client/renderer/entity/SpiderRenderer.h +++ b/src/client/renderer/entity/SpiderRenderer.h @@ -1,46 +1,44 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__SpiderRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__SpiderRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "MobRenderer.h" - -#include "../gles.h" -#include "../../model/SpiderModel.h" -#include "../../../world/entity/monster/Spider.h" - -class SpiderRenderer: public MobRenderer -{ - typedef MobRenderer super; -public: - SpiderRenderer() - : super(new SpiderModel(), 1.0f) - { - //this->setArmor(/*new*/ SpiderModel()); - } - -protected: - float getFlipDegrees(Mob* spider) { - return 180; - } - -// int prepareArmor(Mob* spider, int layer, float a) { -// if (layer != 0) return -1; -// bindTexture("/mob/spider_eyes.png"); -// float br = 1.0f; -// glEnable(GL_BLEND); -// glDisable(GL_ALPHA_TEST); -//// glBlendFunc2(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); -// glBlendFunc2(GL_ONE, GL_ONE); -// glColor4f2(1, 1, 1, br); -// return 1; -// } - - /*@Override*/ - void scale(Mob* mob, float a) { - float scale = ((Spider*)mob)->getModelScale(); - glScalef(scale, scale, scale); - } -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__SpiderRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "MobRenderer.h" + +#include "../gles.h" +#include "../../model/SpiderModel.h" +#include "../../../world/entity/monster/Spider.h" + +class SpiderRenderer: public MobRenderer +{ + typedef MobRenderer super; +public: + SpiderRenderer() + : super(new SpiderModel(), 1.0f) + { + //this->setArmor(/*new*/ SpiderModel()); + } + +protected: + float getFlipDegrees(Mob* spider) { + return 180; + } + +// int prepareArmor(Mob* spider, int layer, float a) { +// if (layer != 0) return -1; +// bindTexture("/mob/spider_eyes.png"); +// float br = 1.0f; +// glEnable(GL_BLEND); +// glDisable(GL_ALPHA_TEST); +//// glBlendFunc2(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); +// glBlendFunc2(GL_ONE, GL_ONE); +// glColor4f2(1, 1, 1, br); +// return 1; +// } + + /*@Override*/ + void scale(Mob* mob, float a) { + float scale = ((Spider*)mob)->getModelScale(); + glScalef(scale, scale, scale); + } +}; + diff --git a/src/client/renderer/entity/TntRenderer.h b/src/client/renderer/entity/TntRenderer.h index efa0e0d..c5fdd37 100755 --- a/src/client/renderer/entity/TntRenderer.h +++ b/src/client/renderer/entity/TntRenderer.h @@ -1,18 +1,16 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__TntRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__TntRenderer_H__ - -//package net.minecraft.client.renderer.entity; - -#include "EntityRenderer.h" -#include "../TileRenderer.h" - -class TntRenderer: public EntityRenderer -{ -public: - TntRenderer(); - void render(Entity* tnt_, float x, float y, float z, float rot, float a); - - TileRenderer tileRenderer; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__TntRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.entity; + +#include "EntityRenderer.h" +#include "../TileRenderer.h" + +class TntRenderer: public EntityRenderer +{ +public: + TntRenderer(); + void render(Entity* tnt_, float x, float y, float z, float rot, float a); + + TileRenderer tileRenderer; +}; + diff --git a/src/client/renderer/entity/TripodCameraRenderer.h b/src/client/renderer/entity/TripodCameraRenderer.h index 35d4058..16d5d34 100755 --- a/src/client/renderer/entity/TripodCameraRenderer.h +++ b/src/client/renderer/entity/TripodCameraRenderer.h @@ -1,29 +1,27 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_ENTITY__TripodCameraRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_ENTITY__TripodCameraRenderer_H__ - -#include "EntityRenderer.h" -#include "../TileRenderer.h" -#include "../../model/geom/ModelPart.h" -#include "../../../world/level/tile/Tile.h" - - -class TripodCamera; - -class TripodCameraRenderer: public EntityRenderer -{ - TileRenderer tileRenderer; - -public: - TripodCameraRenderer(); - - void render(Entity* cam_, float x, float y, float z, float rot, float a); - //void render( Tesselator &t ); - - static float getFlashTime(const TripodCamera* c, float a); - -private: - Tile tripod; - ModelPart cameraCube; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_ENTITY__TripodCameraRenderer_H__*/ +#pragma once + +#include "EntityRenderer.h" +#include "../TileRenderer.h" +#include "../../model/geom/ModelPart.h" +#include "../../../world/level/tile/Tile.h" + + +class TripodCamera; + +class TripodCameraRenderer: public EntityRenderer +{ + TileRenderer tileRenderer; + +public: + TripodCameraRenderer(); + + void render(Entity* cam_, float x, float y, float z, float rot, float a); + //void render( Tesselator &t ); + + static float getFlashTime(const TripodCamera* c, float a); + +private: + Tile tripod; + ModelPart cameraCube; +}; + diff --git a/src/client/renderer/gles.h b/src/client/renderer/gles.h index 7b7e4fd..569da1b 100755 --- a/src/client/renderer/gles.h +++ b/src/client/renderer/gles.h @@ -1,148 +1,146 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER__gles_H__ -#define NET_MINECRAFT_CLIENT_RENDERER__gles_H__ - -#include "../../platform/log.h" -#include "../Options.h" - -// Android should always run OPENGL_ES -#if defined(ANDROID) || defined(__APPLE__) || defined(RPI) - #define OPENGL_ES -#endif - -// Other systems might run it, if they #define OPENGL_ES -// #if defined(OPENGL_ES) // || defined(ANDROID) - #define USE_VBO - #define GL_QUADS 0x0007 - #if defined(__APPLE__) - #import - #import - #elif defined(ANDROID) || defined(__EMSCRIPTEN__) - #include - #include - #else - #include - - // https://github.com/programmer1o1/MinecraftPE-v0.6.1/blob/main/handheld/src/client/renderer/gles.h#L135-L138 - #define glFogx(a,b) glFogi(a,b) - #define glOrthof(a,b,c,d,e,f) glOrtho(a,b,c,d,e,f) - #define glClearDepthf(x) glClearDepth(x) - #define glDepthRangef(a,b) glDepthRange(a,b) - #endif -// #else -// // Uglyness to fix redeclaration issues -// #ifdef WIN32 -// #include -// #include -// #endif -// #include -// #include - -// #define glFogx(a,b) glFogi(a,b) -// #define glOrthof(a,b,c,d,e,f) glOrtho(a,b,c,d,e,f) -// #endif - - -#define GLERRDEBUG 1 -#if GLERRDEBUG -//#define GLERR(x) if((x) != 0) { LOGI("GLError: " #x "(%d)\n", __LINE__) } -#define GLERR(x) do { const int errCode = glGetError(); if (errCode != 0) LOGE("OpenGL ERROR @%d: #%d @ (%s : %d)\n", x, errCode, __FILE__, __LINE__); } while (0) -#else -#define GLERR(x) x -#endif - -void anGenBuffers(GLsizei n, GLuint* buffer); - -#ifdef USE_VBO -#define drawArrayVT_NoState drawArrayVT -#define drawArrayVTC_NoState drawArrayVTC -void drawArrayVT(int bufferId, int vertices, int vertexSize = 24, unsigned int mode = GL_TRIANGLES); -#ifndef drawArrayVT_NoState -//void drawArrayVT_NoState(int bufferId, int vertices, int vertexSize = 24); -#endif -void drawArrayVTC(int bufferId, int vertices, int vertexSize = 24); -#ifndef drawArrayVTC_NoState -void drawArrayVTC_NoState(int bufferId, int vertices, int vertexSize = 24); -#endif -#endif - -void glInit(); -void gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar); -int glhUnProjectf( float winx, float winy, float winz, - float *modelview, float *projection, - int *viewport, float *objectCoordinate); - -// Used for "debugging" (...). Obviously stupid dependency on Options (and ugly gl*2 calls). -#ifdef GLDEBUG - #define glTranslatef2(x, y, z) do{ if (Options::debugGl) LOGI("glTrans @ %s:%d: %f,%f,%f\n", __FILE__, __LINE__, x, y, z); glTranslatef(x, y, z); GLERR(0); } while(0) - #define glRotatef2(a, x, y, z) do{ if (Options::debugGl) LOGI("glRotat @ %s:%d: %f,%f,%f,%f\n", __FILE__, __LINE__, a, x, y, z); glRotatef(a, x, y, z); GLERR(1); } while(0) - #define glScalef2(x, y, z) do{ if (Options::debugGl) LOGI("glScale @ %s:%d: %f,%f,%f\n", __FILE__, __LINE__, x, y, z); glScalef(x, y, z); GLERR(2); } while(0) - #define glPushMatrix2() do{ if (Options::debugGl) LOGI("glPushM @ %s:%d\n", __FILE__, __LINE__); glPushMatrix(); GLERR(3); } while(0) - #define glPopMatrix2() do{ if (Options::debugGl) LOGI("glPopM @ %s:%d\n", __FILE__, __LINE__); glPopMatrix(); GLERR(4); } while(0) - #define glLoadIdentity2() do{ if (Options::debugGl) LOGI("glLoadI @ %s:%d\n", __FILE__, __LINE__); glLoadIdentity(); GLERR(5); } while(0) - - #define glVertexPointer2(a, b, c, d) do{ if (Options::debugGl) LOGI("glVertexPtr @ %s:%d : %d\n", __FILE__, __LINE__, 0); glVertexPointer(a, b, c, d); GLERR(6); } while(0) - #define glColorPointer2(a, b, c, d) do{ if (Options::debugGl) LOGI("glColorPtr @ %s:%d : %d\n", __FILE__, __LINE__, 0); glColorPointer(a, b, c, d); GLERR(7); } while(0) - #define glTexCoordPointer2(a, b, c, d) do{ if (Options::debugGl) LOGI("glTexPtr @ %s:%d : %d\n", __FILE__, __LINE__, 0); glTexCoordPointer(a, b, c, d); GLERR(8); } while(0) - #define glEnableClientState2(s) do{ if (Options::debugGl) LOGI("glEnableClient @ %s:%d : %d\n", __FILE__, __LINE__, 0); glEnableClientState(s); GLERR(9); } while(0) - #define glDisableClientState2(s) do{ if (Options::debugGl) LOGI("glDisableClient @ %s:%d : %d\n", __FILE__, __LINE__, 0); glDisableClientState(s); GLERR(10); } while(0) - #define glDrawArrays2(m, o, v) do{ if (Options::debugGl) LOGI("glDrawA @ %s:%d : %d\n", __FILE__, __LINE__, 0); glDrawArrays(m,o,v); GLERR(11); } while(0) - - #define glTexParameteri2(m, o, v) do{ if (Options::debugGl) LOGI("glTexParameteri @ %s:%d : %d\n", __FILE__, __LINE__, v); glTexParameteri(m,o,v); GLERR(12); } while(0) - #define glTexImage2D2(a,b,c,d,e,f,g,height,i) do{ if (Options::debugGl) LOGI("glTexImage2D @ %s:%d : %d\n", __FILE__, __LINE__, 0); glTexImage2D(a,b,c,d,e,f,g,height,i); GLERR(13); } while(0) - #define glTexSubImage2D2(a,b,c,d,e,f,g,height,i) do{ if (Options::debugGl) LOGI("glTexSubImage2D @ %s:%d : %d\n", __FILE__, __LINE__, 0); glTexSubImage2D(a,b,c,d,e,f,g,height,i); GLERR(14); } while(0) - #define glGenBuffers2(s, id) do{ if (Options::debugGl) LOGI("glGenBuffers @ %s:%d : %d\n", __FILE__, __LINE__, id); anGenBuffers(s, id); GLERR(15); } while(0) - #define glBindBuffer2(s, id) do{ if (Options::debugGl) LOGI("glBindBuffer @ %s:%d : %d\n", __FILE__, __LINE__, id); glBindBuffer(s, id); GLERR(16); } while(0) - #define glBufferData2(a, b, c, d) do{ if (Options::debugGl) LOGI("glBufferData @ %s:%d : %d\n", __FILE__, __LINE__, d); glBufferData(a, b, c, d); GLERR(17); } while(0) - #define glBindTexture2(m, z) do{ if (Options::debugGl) LOGI("glBindTexture @ %s:%d : %d\n", __FILE__, __LINE__, z); glBindTexture(m, z); GLERR(18); } while(0) - - #define glEnable2(s) do{ if (Options::debugGl) LOGI("glEnable @ %s:%d : %d\n", __FILE__, __LINE__, s); glEnable(s); GLERR(19); } while(0) - #define glDisable2(s) do{ if (Options::debugGl) LOGI("glDisable @ %s:%d : %d\n", __FILE__, __LINE__, s); glDisable(s); GLERR(20); } while(0) - - #define glColor4f2(r, g, b, a) do{ if (Options::debugGl) LOGI("glColor4f2 @ %s:%d : (%f,%f,%f,%f)\n", __FILE__, __LINE__, r,g,b,a); glColor4f(r,g,b,a); GLERR(21); } while(0) - - //#define glBlendMode2(s) do{ if (Options::debugGl) LOGI("glEnable @ %s:%d : %d\n", __FILE__, __LINE__, s); glEnable(s); GLERR(19); } while(0) - #define glBlendFunc2(src, dst) do{ if (Options::debugGl) LOGI("glBlendFunc @ %s:%d : %d - %d\n", __FILE__, __LINE__, src, dst); glBlendFunc(src, dst); GLERR(23); } while(0) - #define glShadeModel2(s) do{ if (Options::debugGl) LOGI("glShadeModel @ %s:%d : %d\n", __FILE__, __LINE__, s); glShadeModel(s); GLERR(25); } while(0) -#else - #define glTranslatef2 glTranslatef - #define glRotatef2 glRotatef - #define glScalef2 glScalef - #define glPushMatrix2 glPushMatrix - #define glPopMatrix2 glPopMatrix - #define glLoadIdentity2 glLoadIdentity - - #define glVertexPointer2 glVertexPointer - #define glColorPointer2 glColorPointer - #define glTexCoordPointer2 glTexCoordPointer - #define glEnableClientState2 glEnableClientState - #define glDisableClientState2 glDisableClientState - #define glDrawArrays2 glDrawArrays - - #define glTexParameteri2 glTexParameteri - #define glTexImage2D2 glTexImage2D - #define glTexSubImage2D2 glTexSubImage2D - #define glGenBuffers2 anGenBuffers - #define glBindBuffer2 glBindBuffer - #define glBufferData2 glBufferData - #define glBindTexture2 glBindTexture - - #define glEnable2 glEnable - #define glDisable2 glDisable - - #define glColor4f2 glColor4f - #define glBlendFunc2 glBlendFunc - #define glShadeModel2 glShadeModel -#endif - -// -// Extensions -// -#ifdef WIN32 - #define glGetProcAddress(a) wglGetProcAddress(a) -#else - #define glGetProcAddress(a) (void*(0)) -#endif - - - -#endif /*NET_MINECRAFT_CLIENT_RENDERER__gles_H__ */ +#pragma once + +#include "../../platform/log.h" +#include "../Options.h" + +// Android should always run OPENGL_ES +#if defined(ANDROID) || defined(__APPLE__) || defined(RPI) + #define OPENGL_ES +#endif + +// Other systems might run it, if they #define OPENGL_ES +// #if defined(OPENGL_ES) // || defined(ANDROID) + #define USE_VBO + #define GL_QUADS 0x0007 + #if defined(__APPLE__) + #import + #import + #elif defined(ANDROID) || defined(__EMSCRIPTEN__) + #include + #include + #else + #include + + // https://github.com/programmer1o1/MinecraftPE-v0.6.1/blob/main/handheld/src/client/renderer/gles.h#L135-L138 + #define glFogx(a,b) glFogi(a,b) + #define glOrthof(a,b,c,d,e,f) glOrtho(a,b,c,d,e,f) + #define glClearDepthf(x) glClearDepth(x) + #define glDepthRangef(a,b) glDepthRange(a,b) + #endif +// #else +// // Uglyness to fix redeclaration issues +// #ifdef WIN32 +// #include +// #include +// #endif +// #include +// #include + +// #define glFogx(a,b) glFogi(a,b) +// #define glOrthof(a,b,c,d,e,f) glOrtho(a,b,c,d,e,f) +// #endif + + +#define GLERRDEBUG 1 +#if GLERRDEBUG +//#define GLERR(x) if((x) != 0) { LOGI("GLError: " #x "(%d)\n", __LINE__) } +#define GLERR(x) do { const int errCode = glGetError(); if (errCode != 0) LOGE("OpenGL ERROR @%d: #%d @ (%s : %d)\n", x, errCode, __FILE__, __LINE__); } while (0) +#else +#define GLERR(x) x +#endif + +void anGenBuffers(GLsizei n, GLuint* buffer); + +#ifdef USE_VBO +#define drawArrayVT_NoState drawArrayVT +#define drawArrayVTC_NoState drawArrayVTC +void drawArrayVT(int bufferId, int vertices, int vertexSize = 24, unsigned int mode = GL_TRIANGLES); +#ifndef drawArrayVT_NoState +//void drawArrayVT_NoState(int bufferId, int vertices, int vertexSize = 24); +#endif +void drawArrayVTC(int bufferId, int vertices, int vertexSize = 24); +#ifndef drawArrayVTC_NoState +void drawArrayVTC_NoState(int bufferId, int vertices, int vertexSize = 24); +#endif +#endif + +void glInit(); +void gluPerspective(GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar); +int glhUnProjectf( float winx, float winy, float winz, + float *modelview, float *projection, + int *viewport, float *objectCoordinate); + +// Used for "debugging" (...). Obviously stupid dependency on Options (and ugly gl*2 calls). +#ifdef GLDEBUG + #define glTranslatef2(x, y, z) do{ if (Options::debugGl) LOGI("glTrans @ %s:%d: %f,%f,%f\n", __FILE__, __LINE__, x, y, z); glTranslatef(x, y, z); GLERR(0); } while(0) + #define glRotatef2(a, x, y, z) do{ if (Options::debugGl) LOGI("glRotat @ %s:%d: %f,%f,%f,%f\n", __FILE__, __LINE__, a, x, y, z); glRotatef(a, x, y, z); GLERR(1); } while(0) + #define glScalef2(x, y, z) do{ if (Options::debugGl) LOGI("glScale @ %s:%d: %f,%f,%f\n", __FILE__, __LINE__, x, y, z); glScalef(x, y, z); GLERR(2); } while(0) + #define glPushMatrix2() do{ if (Options::debugGl) LOGI("glPushM @ %s:%d\n", __FILE__, __LINE__); glPushMatrix(); GLERR(3); } while(0) + #define glPopMatrix2() do{ if (Options::debugGl) LOGI("glPopM @ %s:%d\n", __FILE__, __LINE__); glPopMatrix(); GLERR(4); } while(0) + #define glLoadIdentity2() do{ if (Options::debugGl) LOGI("glLoadI @ %s:%d\n", __FILE__, __LINE__); glLoadIdentity(); GLERR(5); } while(0) + + #define glVertexPointer2(a, b, c, d) do{ if (Options::debugGl) LOGI("glVertexPtr @ %s:%d : %d\n", __FILE__, __LINE__, 0); glVertexPointer(a, b, c, d); GLERR(6); } while(0) + #define glColorPointer2(a, b, c, d) do{ if (Options::debugGl) LOGI("glColorPtr @ %s:%d : %d\n", __FILE__, __LINE__, 0); glColorPointer(a, b, c, d); GLERR(7); } while(0) + #define glTexCoordPointer2(a, b, c, d) do{ if (Options::debugGl) LOGI("glTexPtr @ %s:%d : %d\n", __FILE__, __LINE__, 0); glTexCoordPointer(a, b, c, d); GLERR(8); } while(0) + #define glEnableClientState2(s) do{ if (Options::debugGl) LOGI("glEnableClient @ %s:%d : %d\n", __FILE__, __LINE__, 0); glEnableClientState(s); GLERR(9); } while(0) + #define glDisableClientState2(s) do{ if (Options::debugGl) LOGI("glDisableClient @ %s:%d : %d\n", __FILE__, __LINE__, 0); glDisableClientState(s); GLERR(10); } while(0) + #define glDrawArrays2(m, o, v) do{ if (Options::debugGl) LOGI("glDrawA @ %s:%d : %d\n", __FILE__, __LINE__, 0); glDrawArrays(m,o,v); GLERR(11); } while(0) + + #define glTexParameteri2(m, o, v) do{ if (Options::debugGl) LOGI("glTexParameteri @ %s:%d : %d\n", __FILE__, __LINE__, v); glTexParameteri(m,o,v); GLERR(12); } while(0) + #define glTexImage2D2(a,b,c,d,e,f,g,height,i) do{ if (Options::debugGl) LOGI("glTexImage2D @ %s:%d : %d\n", __FILE__, __LINE__, 0); glTexImage2D(a,b,c,d,e,f,g,height,i); GLERR(13); } while(0) + #define glTexSubImage2D2(a,b,c,d,e,f,g,height,i) do{ if (Options::debugGl) LOGI("glTexSubImage2D @ %s:%d : %d\n", __FILE__, __LINE__, 0); glTexSubImage2D(a,b,c,d,e,f,g,height,i); GLERR(14); } while(0) + #define glGenBuffers2(s, id) do{ if (Options::debugGl) LOGI("glGenBuffers @ %s:%d : %d\n", __FILE__, __LINE__, id); anGenBuffers(s, id); GLERR(15); } while(0) + #define glBindBuffer2(s, id) do{ if (Options::debugGl) LOGI("glBindBuffer @ %s:%d : %d\n", __FILE__, __LINE__, id); glBindBuffer(s, id); GLERR(16); } while(0) + #define glBufferData2(a, b, c, d) do{ if (Options::debugGl) LOGI("glBufferData @ %s:%d : %d\n", __FILE__, __LINE__, d); glBufferData(a, b, c, d); GLERR(17); } while(0) + #define glBindTexture2(m, z) do{ if (Options::debugGl) LOGI("glBindTexture @ %s:%d : %d\n", __FILE__, __LINE__, z); glBindTexture(m, z); GLERR(18); } while(0) + + #define glEnable2(s) do{ if (Options::debugGl) LOGI("glEnable @ %s:%d : %d\n", __FILE__, __LINE__, s); glEnable(s); GLERR(19); } while(0) + #define glDisable2(s) do{ if (Options::debugGl) LOGI("glDisable @ %s:%d : %d\n", __FILE__, __LINE__, s); glDisable(s); GLERR(20); } while(0) + + #define glColor4f2(r, g, b, a) do{ if (Options::debugGl) LOGI("glColor4f2 @ %s:%d : (%f,%f,%f,%f)\n", __FILE__, __LINE__, r,g,b,a); glColor4f(r,g,b,a); GLERR(21); } while(0) + + //#define glBlendMode2(s) do{ if (Options::debugGl) LOGI("glEnable @ %s:%d : %d\n", __FILE__, __LINE__, s); glEnable(s); GLERR(19); } while(0) + #define glBlendFunc2(src, dst) do{ if (Options::debugGl) LOGI("glBlendFunc @ %s:%d : %d - %d\n", __FILE__, __LINE__, src, dst); glBlendFunc(src, dst); GLERR(23); } while(0) + #define glShadeModel2(s) do{ if (Options::debugGl) LOGI("glShadeModel @ %s:%d : %d\n", __FILE__, __LINE__, s); glShadeModel(s); GLERR(25); } while(0) +#else + #define glTranslatef2 glTranslatef + #define glRotatef2 glRotatef + #define glScalef2 glScalef + #define glPushMatrix2 glPushMatrix + #define glPopMatrix2 glPopMatrix + #define glLoadIdentity2 glLoadIdentity + + #define glVertexPointer2 glVertexPointer + #define glColorPointer2 glColorPointer + #define glTexCoordPointer2 glTexCoordPointer + #define glEnableClientState2 glEnableClientState + #define glDisableClientState2 glDisableClientState + #define glDrawArrays2 glDrawArrays + + #define glTexParameteri2 glTexParameteri + #define glTexImage2D2 glTexImage2D + #define glTexSubImage2D2 glTexSubImage2D + #define glGenBuffers2 anGenBuffers + #define glBindBuffer2 glBindBuffer + #define glBufferData2 glBufferData + #define glBindTexture2 glBindTexture + + #define glEnable2 glEnable + #define glDisable2 glDisable + + #define glColor4f2 glColor4f + #define glBlendFunc2 glBlendFunc + #define glShadeModel2 glShadeModel +#endif + +// +// Extensions +// +#ifdef WIN32 + #define glGetProcAddress(a) wglGetProcAddress(a) +#else + #define glGetProcAddress(a) (void*(0)) +#endif + + + diff --git a/src/client/renderer/ptexture/DynamicTexture.h b/src/client/renderer/ptexture/DynamicTexture.h index c95b3d7..f121bdb 100755 --- a/src/client/renderer/ptexture/DynamicTexture.h +++ b/src/client/renderer/ptexture/DynamicTexture.h @@ -1,59 +1,57 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_PTEXTURE__DynamicTexture_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_PTEXTURE__DynamicTexture_H__ - -#include - -class Textures; - -class DynamicTexture -{ -public: - int tex; - int replicate; - unsigned char pixels[16*16*4]; - - DynamicTexture(int tex_); - virtual ~DynamicTexture() {} - - virtual void tick() = 0; - virtual void bindTexture(Textures* tex); -}; - -class WaterTexture: public DynamicTexture -{ - typedef DynamicTexture super; - int _tick; - int _frame; - - float* current; - float* next; - float* heat; - float* heata; - -public: - WaterTexture(); - ~WaterTexture(); - - void tick(); -}; - -class WaterSideTexture: public DynamicTexture -{ - typedef DynamicTexture super; - int _tick; - int _frame; - int _tickCount; - - float* current; - float* next; - float* heat; - float* heata; - -public: - WaterSideTexture(); - ~WaterSideTexture(); - - void tick(); -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_PTEXTURE__DynamicTexture_H__*/ +#pragma once + +#include + +class Textures; + +class DynamicTexture +{ +public: + int tex; + int replicate; + unsigned char pixels[16*16*4]; + + DynamicTexture(int tex_); + virtual ~DynamicTexture() {} + + virtual void tick() = 0; + virtual void bindTexture(Textures* tex); +}; + +class WaterTexture: public DynamicTexture +{ + typedef DynamicTexture super; + int _tick; + int _frame; + + float* current; + float* next; + float* heat; + float* heata; + +public: + WaterTexture(); + ~WaterTexture(); + + void tick(); +}; + +class WaterSideTexture: public DynamicTexture +{ + typedef DynamicTexture super; + int _tick; + int _frame; + int _tickCount; + + float* current; + float* next; + float* heat; + float* heata; + +public: + WaterSideTexture(); + ~WaterSideTexture(); + + void tick(); +}; + diff --git a/src/client/renderer/tileentity/ChestRenderer.h b/src/client/renderer/tileentity/ChestRenderer.h index bf4e47e..f133ef0 100755 --- a/src/client/renderer/tileentity/ChestRenderer.h +++ b/src/client/renderer/tileentity/ChestRenderer.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__ChestRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__ChestRenderer_H__ - -//package net.minecraft.client.renderer.tileentity; - -#include "TileEntityRenderer.h" -#include "../../model/ChestModel.h" - -class ChestTileEntity; - -class ChestRenderer: public TileEntityRenderer -{ - /*@Override*/ - void render(TileEntity* chest, float x, float y, float z, float a); - -private: - ChestModel chestModel; - //LargeChestModel* largeChestModel; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__ChestRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.tileentity; + +#include "TileEntityRenderer.h" +#include "../../model/ChestModel.h" + +class ChestTileEntity; + +class ChestRenderer: public TileEntityRenderer +{ + /*@Override*/ + void render(TileEntity* chest, float x, float y, float z, float a); + +private: + ChestModel chestModel; + //LargeChestModel* largeChestModel; +}; + diff --git a/src/client/renderer/tileentity/SignRenderer.h b/src/client/renderer/tileentity/SignRenderer.h index b9de6b3..ba9b136 100755 --- a/src/client/renderer/tileentity/SignRenderer.h +++ b/src/client/renderer/tileentity/SignRenderer.h @@ -1,21 +1,19 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__SignRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__SignRenderer_H__ - -//package net.minecraft.client.renderer.tileentity; - -#include "TileEntityRenderer.h" - -#include "../../gui/Font.h" -#include "../../model/SignModel.h" - -class SignRenderer: public TileEntityRenderer -{ -public: - /*@Override*/ - void render(TileEntity* te, float x, float y, float z, float a); - void onGraphicsReset(); -private: - SignModel signModel; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__SignRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.tileentity; + +#include "TileEntityRenderer.h" + +#include "../../gui/Font.h" +#include "../../model/SignModel.h" + +class SignRenderer: public TileEntityRenderer +{ +public: + /*@Override*/ + void render(TileEntity* te, float x, float y, float z, float a); + void onGraphicsReset(); +private: + SignModel signModel; +}; + diff --git a/src/client/renderer/tileentity/TileEntityRenderDispatcher.h b/src/client/renderer/tileentity/TileEntityRenderDispatcher.h index 0f7539e..b040731 100755 --- a/src/client/renderer/tileentity/TileEntityRenderDispatcher.h +++ b/src/client/renderer/tileentity/TileEntityRenderDispatcher.h @@ -1,61 +1,59 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__TileEntityRenderDispatcher_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__TileEntityRenderDispatcher_H__ - -//package net.minecraft.client.renderer.tileentity; - -#include -#include "../../../world/level/tile/entity/TileEntityRendererId.h" - -class TileEntityRenderer; -class Level; -class Textures; -class TileEntity; -class Font; -class Mob; - -class TileEntityRenderDispatcher -{ - typedef std::map RendererMap; - typedef RendererMap::iterator RendererIterator; - typedef RendererMap::const_iterator RendererCIterator; - -public: - ~TileEntityRenderDispatcher(); - - static TileEntityRenderDispatcher* getInstance(); - static void destroy(); - - void setLevel(Level* level); - void prepare(Level* level, Textures* textures, Font* font, Mob* player, float a); - - void render(TileEntity* e, float a); - void render(TileEntity* entity, float x, float y, float z, float a); - - float distanceToSqr(float x, float y, float z); - - Font* getFont(); - - TileEntityRenderer* getRenderer( TileEntity* entity ); - TileEntityRenderer* getRenderer( TileEntityRendererId rendererId ); - - void onGraphicsReset(); -private: - TileEntityRenderDispatcher(); -public: - static float xOff, yOff, zOff; - - Textures* textures; - Level* level; - Mob* cameraEntity; - float playerRotY; - float playerRotX; - - float xPlayer, yPlayer, zPlayer; -private: - static TileEntityRenderDispatcher* instance; - - Font* _font; - RendererMap _renderers; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__TileEntityRenderDispatcher_H__*/ +#pragma once + +//package net.minecraft.client.renderer.tileentity; + +#include +#include "../../../world/level/tile/entity/TileEntityRendererId.h" + +class TileEntityRenderer; +class Level; +class Textures; +class TileEntity; +class Font; +class Mob; + +class TileEntityRenderDispatcher +{ + typedef std::map RendererMap; + typedef RendererMap::iterator RendererIterator; + typedef RendererMap::const_iterator RendererCIterator; + +public: + ~TileEntityRenderDispatcher(); + + static TileEntityRenderDispatcher* getInstance(); + static void destroy(); + + void setLevel(Level* level); + void prepare(Level* level, Textures* textures, Font* font, Mob* player, float a); + + void render(TileEntity* e, float a); + void render(TileEntity* entity, float x, float y, float z, float a); + + float distanceToSqr(float x, float y, float z); + + Font* getFont(); + + TileEntityRenderer* getRenderer( TileEntity* entity ); + TileEntityRenderer* getRenderer( TileEntityRendererId rendererId ); + + void onGraphicsReset(); +private: + TileEntityRenderDispatcher(); +public: + static float xOff, yOff, zOff; + + Textures* textures; + Level* level; + Mob* cameraEntity; + float playerRotY; + float playerRotX; + + float xPlayer, yPlayer, zPlayer; +private: + static TileEntityRenderDispatcher* instance; + + Font* _font; + RendererMap _renderers; +}; + diff --git a/src/client/renderer/tileentity/TileEntityRenderer.h b/src/client/renderer/tileentity/TileEntityRenderer.h index 0234682..7b57f43 100755 --- a/src/client/renderer/tileentity/TileEntityRenderer.h +++ b/src/client/renderer/tileentity/TileEntityRenderer.h @@ -1,38 +1,36 @@ -#ifndef NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__TileEntityRenderer_H__ -#define NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__TileEntityRenderer_H__ - -//package net.minecraft.client.renderer.tileentity; - -#include - -class Level; -class TileEntity; -class TileEntityRenderDispatcher; -class Font; - -class TileEntityRenderer -{ -public: - TileEntityRenderer(); - virtual ~TileEntityRenderer(){} - - void init(TileEntityRenderDispatcher* tileEntityRenderDispatcher); - virtual void render(TileEntity* entity, float x, float y, float z, float a) = 0; - - void bindTexture(const std::string& resourceName); -// /*protected*/ void bindTexture(const std::string& urlTexture, const std::string& backupTexture) { -// Textures t = tileEntityRenderDispatcher.textures; -// if (t != NULL) t.bind(t.loadHttpTexture(urlTexture, backupTexture)); -// } - - Level* getLevel(); - Font* getFont(); - - virtual void onGraphicsReset() {} - - virtual void onNewLevel(Level* level) {} -protected: - TileEntityRenderDispatcher* tileEntityRenderDispatcher; -}; - -#endif /*NET_MINECRAFT_CLIENT_RENDERER_TILEENTITY__TileEntityRenderer_H__*/ +#pragma once + +//package net.minecraft.client.renderer.tileentity; + +#include + +class Level; +class TileEntity; +class TileEntityRenderDispatcher; +class Font; + +class TileEntityRenderer +{ +public: + TileEntityRenderer(); + virtual ~TileEntityRenderer(){} + + void init(TileEntityRenderDispatcher* tileEntityRenderDispatcher); + virtual void render(TileEntity* entity, float x, float y, float z, float a) = 0; + + void bindTexture(const std::string& resourceName); +// /*protected*/ void bindTexture(const std::string& urlTexture, const std::string& backupTexture) { +// Textures t = tileEntityRenderDispatcher.textures; +// if (t != NULL) t.bind(t.loadHttpTexture(urlTexture, backupTexture)); +// } + + Level* getLevel(); + Font* getFont(); + + virtual void onGraphicsReset() {} + + virtual void onNewLevel(Level* level) {} +protected: + TileEntityRenderDispatcher* tileEntityRenderDispatcher; +}; + diff --git a/src/client/sound/Sound.h b/src/client/sound/Sound.h index 62f3db0..0d61960 100755 --- a/src/client/sound/Sound.h +++ b/src/client/sound/Sound.h @@ -1,180 +1,178 @@ -#ifndef NET_MINECRAFT_CLIENT_SOUND__Sound_H__ -#define NET_MINECRAFT_CLIENT_SOUND__Sound_H__ - -//package net.minecraft.client.sound; - -#include - -class SoundDesc -{ -public: - SoundDesc() - : buffer(0) - {} - - SoundDesc(char* data, int size, int channels, int width, int rate) - : buffer(data), - frames(data), - size(size), - channels(channels), - byteWidth(width), - frameRate(rate) - { - numFrames = size / (channels * byteWidth); - } - - SoundDesc(char* data) - : buffer(data) - { - // header [INT][Channels, BytePerSample, FrameRate, NumFrames] - channels = *((int*)&data[0]); - byteWidth = *((int*)&data[4]); - frameRate = *((int*)&data[8]); - numFrames = *((int*)&data[12]); - - size = channels * byteWidth * numFrames; - frames = buffer + 16; - } - - bool isValid() const { return buffer != 0; } - float length() const { - return ((float)numFrames) / frameRate; - } - - void destroy() const { - if (isValid()) { - delete buffer; - buffer = 0; - } - } - - char* frames; - int size; - - int channels; - int byteWidth; - int frameRate; - int numFrames; - - std::string name; -private: - mutable char* buffer; -}; - -#if !defined(PRE_ANDROID23) && !defined(__APPLE__) && !defined(RPI) - -extern SoundDesc SA_cloth1; -extern SoundDesc SA_cloth2; -extern SoundDesc SA_cloth3; -extern SoundDesc SA_cloth4; -extern SoundDesc SA_grass1; -extern SoundDesc SA_grass2; -extern SoundDesc SA_grass3; -extern SoundDesc SA_grass4; -extern SoundDesc SA_gravel1; -extern SoundDesc SA_gravel2; -extern SoundDesc SA_gravel3; -extern SoundDesc SA_gravel4; -extern SoundDesc SA_sand1; -extern SoundDesc SA_sand2; -extern SoundDesc SA_sand3; -extern SoundDesc SA_sand4; -extern SoundDesc SA_stone1; -extern SoundDesc SA_stone2; -extern SoundDesc SA_stone3; -extern SoundDesc SA_stone4; -extern SoundDesc SA_wood1; -extern SoundDesc SA_wood2; -extern SoundDesc SA_wood3; -extern SoundDesc SA_wood4; - -extern SoundDesc SA_click; -extern SoundDesc SA_explode; -extern SoundDesc SA_splash; - -extern SoundDesc SA_door_open; -extern SoundDesc SA_door_close; -extern SoundDesc SA_pop; -extern SoundDesc SA_pop2; -extern SoundDesc SA_hurt; -extern SoundDesc SA_glass1; -extern SoundDesc SA_glass2; -extern SoundDesc SA_glass3; - -extern SoundDesc SA_sheep1; -extern SoundDesc SA_sheep2; -extern SoundDesc SA_sheep3; -extern SoundDesc SA_pig1; -extern SoundDesc SA_pig2; -extern SoundDesc SA_pig3; -extern SoundDesc SA_pigdeath; - -//extern SoundDesc SA_chicken1; -extern SoundDesc SA_chicken2; -extern SoundDesc SA_chicken3; -extern SoundDesc SA_chickenhurt1; -extern SoundDesc SA_chickenhurt2; - -extern SoundDesc SA_cow1; -extern SoundDesc SA_cow2; -extern SoundDesc SA_cow3; -extern SoundDesc SA_cow4; -extern SoundDesc SA_cowhurt1; -extern SoundDesc SA_cowhurt2; -extern SoundDesc SA_cowhurt3; - -extern SoundDesc SA_zombie1; -extern SoundDesc SA_zombie2; -extern SoundDesc SA_zombie3; -extern SoundDesc SA_zombiedeath; -extern SoundDesc SA_zombiehurt1; -extern SoundDesc SA_zombiehurt2; - -extern SoundDesc SA_zpig1; -extern SoundDesc SA_zpig2; -extern SoundDesc SA_zpig3; -extern SoundDesc SA_zpig4; -extern SoundDesc SA_zpigangry1; -extern SoundDesc SA_zpigangry2; -extern SoundDesc SA_zpigangry3; -extern SoundDesc SA_zpigangry4; -extern SoundDesc SA_zpigdeath; -extern SoundDesc SA_zpighurt1; -extern SoundDesc SA_zpighurt2; - -extern SoundDesc SA_bow; -extern SoundDesc SA_bowhit1; -extern SoundDesc SA_bowhit2; -extern SoundDesc SA_bowhit3; -extern SoundDesc SA_bowhit4; -extern SoundDesc SA_fallbig1; -extern SoundDesc SA_fallbig2; -extern SoundDesc SA_fallsmall; -extern SoundDesc SA_skeleton1; -extern SoundDesc SA_skeleton2; -extern SoundDesc SA_skeleton3; -extern SoundDesc SA_skeletondeath; -extern SoundDesc SA_skeletonhurt1; -extern SoundDesc SA_skeletonhurt2; -extern SoundDesc SA_skeletonhurt3; -extern SoundDesc SA_skeletonhurt4; -extern SoundDesc SA_spider1; -extern SoundDesc SA_spider2; -extern SoundDesc SA_spider3; -extern SoundDesc SA_spider4; -extern SoundDesc SA_spiderdeath; - -extern SoundDesc SA_creeper1; -extern SoundDesc SA_creeper2; -extern SoundDesc SA_creeper3; -extern SoundDesc SA_creeper4; -extern SoundDesc SA_creeperdeath; -extern SoundDesc SA_eat1; -extern SoundDesc SA_eat2; -extern SoundDesc SA_eat3; -extern SoundDesc SA_fuse; - -#endif /*!PRE_ANDROID23 && !__APPLE__*/ - - -#endif /*NET_MINECRAFT_CLIENT_SOUND__Sound_H__*/ +#pragma once + +//package net.minecraft.client.sound; + +#include + +class SoundDesc +{ +public: + SoundDesc() + : buffer(0) + {} + + SoundDesc(char* data, int size, int channels, int width, int rate) + : buffer(data), + frames(data), + size(size), + channels(channels), + byteWidth(width), + frameRate(rate) + { + numFrames = size / (channels * byteWidth); + } + + SoundDesc(char* data) + : buffer(data) + { + // header [INT][Channels, BytePerSample, FrameRate, NumFrames] + channels = *((int*)&data[0]); + byteWidth = *((int*)&data[4]); + frameRate = *((int*)&data[8]); + numFrames = *((int*)&data[12]); + + size = channels * byteWidth * numFrames; + frames = buffer + 16; + } + + bool isValid() const { return buffer != 0; } + float length() const { + return ((float)numFrames) / frameRate; + } + + void destroy() const { + if (isValid()) { + delete buffer; + buffer = 0; + } + } + + char* frames; + int size; + + int channels; + int byteWidth; + int frameRate; + int numFrames; + + std::string name; +private: + mutable char* buffer; +}; + +#if !defined(PRE_ANDROID23) && !defined(__APPLE__) && !defined(RPI) + +extern SoundDesc SA_cloth1; +extern SoundDesc SA_cloth2; +extern SoundDesc SA_cloth3; +extern SoundDesc SA_cloth4; +extern SoundDesc SA_grass1; +extern SoundDesc SA_grass2; +extern SoundDesc SA_grass3; +extern SoundDesc SA_grass4; +extern SoundDesc SA_gravel1; +extern SoundDesc SA_gravel2; +extern SoundDesc SA_gravel3; +extern SoundDesc SA_gravel4; +extern SoundDesc SA_sand1; +extern SoundDesc SA_sand2; +extern SoundDesc SA_sand3; +extern SoundDesc SA_sand4; +extern SoundDesc SA_stone1; +extern SoundDesc SA_stone2; +extern SoundDesc SA_stone3; +extern SoundDesc SA_stone4; +extern SoundDesc SA_wood1; +extern SoundDesc SA_wood2; +extern SoundDesc SA_wood3; +extern SoundDesc SA_wood4; + +extern SoundDesc SA_click; +extern SoundDesc SA_explode; +extern SoundDesc SA_splash; + +extern SoundDesc SA_door_open; +extern SoundDesc SA_door_close; +extern SoundDesc SA_pop; +extern SoundDesc SA_pop2; +extern SoundDesc SA_hurt; +extern SoundDesc SA_glass1; +extern SoundDesc SA_glass2; +extern SoundDesc SA_glass3; + +extern SoundDesc SA_sheep1; +extern SoundDesc SA_sheep2; +extern SoundDesc SA_sheep3; +extern SoundDesc SA_pig1; +extern SoundDesc SA_pig2; +extern SoundDesc SA_pig3; +extern SoundDesc SA_pigdeath; + +//extern SoundDesc SA_chicken1; +extern SoundDesc SA_chicken2; +extern SoundDesc SA_chicken3; +extern SoundDesc SA_chickenhurt1; +extern SoundDesc SA_chickenhurt2; + +extern SoundDesc SA_cow1; +extern SoundDesc SA_cow2; +extern SoundDesc SA_cow3; +extern SoundDesc SA_cow4; +extern SoundDesc SA_cowhurt1; +extern SoundDesc SA_cowhurt2; +extern SoundDesc SA_cowhurt3; + +extern SoundDesc SA_zombie1; +extern SoundDesc SA_zombie2; +extern SoundDesc SA_zombie3; +extern SoundDesc SA_zombiedeath; +extern SoundDesc SA_zombiehurt1; +extern SoundDesc SA_zombiehurt2; + +extern SoundDesc SA_zpig1; +extern SoundDesc SA_zpig2; +extern SoundDesc SA_zpig3; +extern SoundDesc SA_zpig4; +extern SoundDesc SA_zpigangry1; +extern SoundDesc SA_zpigangry2; +extern SoundDesc SA_zpigangry3; +extern SoundDesc SA_zpigangry4; +extern SoundDesc SA_zpigdeath; +extern SoundDesc SA_zpighurt1; +extern SoundDesc SA_zpighurt2; + +extern SoundDesc SA_bow; +extern SoundDesc SA_bowhit1; +extern SoundDesc SA_bowhit2; +extern SoundDesc SA_bowhit3; +extern SoundDesc SA_bowhit4; +extern SoundDesc SA_fallbig1; +extern SoundDesc SA_fallbig2; +extern SoundDesc SA_fallsmall; +extern SoundDesc SA_skeleton1; +extern SoundDesc SA_skeleton2; +extern SoundDesc SA_skeleton3; +extern SoundDesc SA_skeletondeath; +extern SoundDesc SA_skeletonhurt1; +extern SoundDesc SA_skeletonhurt2; +extern SoundDesc SA_skeletonhurt3; +extern SoundDesc SA_skeletonhurt4; +extern SoundDesc SA_spider1; +extern SoundDesc SA_spider2; +extern SoundDesc SA_spider3; +extern SoundDesc SA_spider4; +extern SoundDesc SA_spiderdeath; + +extern SoundDesc SA_creeper1; +extern SoundDesc SA_creeper2; +extern SoundDesc SA_creeper3; +extern SoundDesc SA_creeper4; +extern SoundDesc SA_creeperdeath; +extern SoundDesc SA_eat1; +extern SoundDesc SA_eat2; +extern SoundDesc SA_eat3; +extern SoundDesc SA_fuse; + +#endif /*!PRE_ANDROID23 && !__APPLE__*/ + + diff --git a/src/client/sound/SoundEngine.h b/src/client/sound/SoundEngine.h index bf3d131..8a0027f 100755 --- a/src/client/sound/SoundEngine.h +++ b/src/client/sound/SoundEngine.h @@ -1,5 +1,4 @@ -#ifndef NET_MINECRAFT_CLIENT_SOUND__SoundEngine_H__ -#define NET_MINECRAFT_CLIENT_SOUND__SoundEngine_H__ +#pragma once //package net.minecraft.client.sound; @@ -65,4 +64,3 @@ private: Minecraft* mc; }; -#endif /*NET_MINECRAFT_CLIENT_SOUND__SoundEngine_H__*/ diff --git a/src/client/sound/SoundRepository.h b/src/client/sound/SoundRepository.h index 6c2b382..693311e 100755 --- a/src/client/sound/SoundRepository.h +++ b/src/client/sound/SoundRepository.h @@ -1,59 +1,57 @@ -#ifndef NET_MINECRAFT_CLIENT_SOUND__SoundRepository_H__ -#define NET_MINECRAFT_CLIENT_SOUND__SoundRepository_H__ - -#include -#include -#include "Sound.h" -#include "../../util/Mth.h" -#include "../../platform/log.h" - -class SoundRepository -{ - typedef std::vector SoundList; - typedef std::map SoundMap; - -public: - ~SoundRepository() { -#ifdef __APPLE__ - SoundMap::iterator it = map.begin(); - for (; it != map.end(); ++it) { - SoundList& list = it->second; - for (unsigned int j = 0; j < list.size(); ++j) - list[j].destroy(); - } -#endif - } - - bool get(const std::string& name, SoundDesc& sound) { - SoundMap::iterator it = map.find(name); - if (it == map.end()) { - LOGI("Couldn't find a sound with id: %s\n", name.c_str()); - return false; - } - sound = it->second[Mth::random(it->second.size())]; - return true; - } - - void add(const std::string& name, const SoundDesc& sound) { - if (!sound.isValid()) return; - SoundMap::iterator it = map.find(name); - if (it == map.end()) { - SoundList list; - list.push_back( sound ); - map.insert( make_pair(name, list) ); - } else { - it->second.push_back(sound); - } - } - - void add(const std::string& name, SoundDesc& sound) { - if (!sound.isValid()) return; - add(name, const_cast(sound)); - sound.name = name; - } - -private: - SoundMap map; -}; - -#endif /*NET_MINECRAFT_CLIENT_SOUND__SoundRepository_H__*/ +#pragma once + +#include +#include +#include "Sound.h" +#include "../../util/Mth.h" +#include "../../platform/log.h" + +class SoundRepository +{ + typedef std::vector SoundList; + typedef std::map SoundMap; + +public: + ~SoundRepository() { +#ifdef __APPLE__ + SoundMap::iterator it = map.begin(); + for (; it != map.end(); ++it) { + SoundList& list = it->second; + for (unsigned int j = 0; j < list.size(); ++j) + list[j].destroy(); + } +#endif + } + + bool get(const std::string& name, SoundDesc& sound) { + SoundMap::iterator it = map.find(name); + if (it == map.end()) { + LOGI("Couldn't find a sound with id: %s\n", name.c_str()); + return false; + } + sound = it->second[Mth::random(it->second.size())]; + return true; + } + + void add(const std::string& name, const SoundDesc& sound) { + if (!sound.isValid()) return; + SoundMap::iterator it = map.find(name); + if (it == map.end()) { + SoundList list; + list.push_back( sound ); + map.insert( make_pair(name, list) ); + } else { + it->second.push_back(sound); + } + } + + void add(const std::string& name, SoundDesc& sound) { + if (!sound.isValid()) return; + add(name, const_cast(sound)); + sound.name = name; + } + +private: + SoundMap map; +}; + diff --git a/src/gamemode/CreativeMode.h b/src/gamemode/CreativeMode.h index 0c58ca0..a7caf63 100755 --- a/src/gamemode/CreativeMode.h +++ b/src/gamemode/CreativeMode.h @@ -1,5 +1,4 @@ -#ifndef NET_MINECRAFT_CLIENT_GAMEMODE__CreativeMode_H__ -#define NET_MINECRAFT_CLIENT_GAMEMODE__CreativeMode_H__ +#pragma once //package net.minecraft.client.gamemode; @@ -24,4 +23,3 @@ private: void creativeDestroyBlock(Player* player, int x, int y, int z, int face); }; -#endif /*NET_MINECRAFT_CLIENT_GAMEMODE__CreativeMode_H__*/ diff --git a/src/gamemode/CreatorMode.h b/src/gamemode/CreatorMode.h index c69009d..1cd1062 100755 --- a/src/gamemode/CreatorMode.h +++ b/src/gamemode/CreatorMode.h @@ -1,5 +1,4 @@ -#ifndef NET_MINECRAFT_CLIENT_GAMEMODE__CreatorMode_H__ -#define NET_MINECRAFT_CLIENT_GAMEMODE__CreatorMode_H__ +#pragma once //package net.minecraft.client.gamemode; @@ -125,4 +124,3 @@ private: Creator* _creator; }; -#endif /*NET_MINECRAFT_CLIENT_GAMEMODE__CreatorMode_H__*/ diff --git a/src/gamemode/GameMode.h b/src/gamemode/GameMode.h index 87c00d6..324ccba 100755 --- a/src/gamemode/GameMode.h +++ b/src/gamemode/GameMode.h @@ -1,61 +1,59 @@ -#ifndef NET_MINECRAFT_CLIENT_GAMEMODE__GameMode_H__ -#define NET_MINECRAFT_CLIENT_GAMEMODE__GameMode_H__ - -//package net.minecraft.client.gamemode; - -#include - -class ItemInstance; -class Minecraft; -class Level; -class Player; -class Abilities; - -class GameMode { -protected: - Minecraft& minecraft; - -public: - GameMode(Minecraft& minecraft) : minecraft(minecraft) {} - virtual ~GameMode() {} - - virtual void initLevel(Level* level) {} - - virtual void startDestroyBlock(Player* player, int x, int y, int z, int face); - virtual bool destroyBlock(Player* player, int x, int y, int z, int face); - virtual void continueDestroyBlock(Player* player, int x, int y, int z, int face) = 0; - virtual void stopDestroyBlock(Player* player) {} - - virtual void tick(); - - virtual float getPickRange(); - /* void postLevelGen(LevelGen levelGen, Level level) {} */ - - virtual bool useItem(Player* player, Level* level, ItemInstance* item); - virtual bool useItemOn(Player* player, Level* level, ItemInstance* item, int x, int y, int z, int face, const Vec3& hit); - - virtual void initPlayer(Player* player); - virtual void adjustPlayer(Player* player) {} - virtual bool canHurtPlayer() { return false; } - - virtual void interact(Player* player, Entity* entity); - virtual void attack(Player* player, Entity* entity); - - virtual ItemInstance* handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, Player* player); - virtual void handleCloseInventory(int containerId, Player* player); - - virtual bool isCreativeType() { return false; } - virtual bool isSurvivalType() { return false; } - - virtual void initAbilities(Abilities& abilities) {} - - virtual void releaseUsingItem(Player* player); - - float oDestroyProgress = 0; - float destroyProgress = 0; -protected: - int destroyTicks = 0; - int destroyDelay = 0; -}; - -#endif /*NET_MINECRAFT_CLIENT_GAMEMODE__GameMode_H__*/ +#pragma once + +//package net.minecraft.client.gamemode; + +#include + +class ItemInstance; +class Minecraft; +class Level; +class Player; +class Abilities; + +class GameMode { +protected: + Minecraft& minecraft; + +public: + GameMode(Minecraft& minecraft) : minecraft(minecraft) {} + virtual ~GameMode() {} + + virtual void initLevel(Level* level) {} + + virtual void startDestroyBlock(Player* player, int x, int y, int z, int face); + virtual bool destroyBlock(Player* player, int x, int y, int z, int face); + virtual void continueDestroyBlock(Player* player, int x, int y, int z, int face) = 0; + virtual void stopDestroyBlock(Player* player) {} + + virtual void tick(); + + virtual float getPickRange(); + /* void postLevelGen(LevelGen levelGen, Level level) {} */ + + virtual bool useItem(Player* player, Level* level, ItemInstance* item); + virtual bool useItemOn(Player* player, Level* level, ItemInstance* item, int x, int y, int z, int face, const Vec3& hit); + + virtual void initPlayer(Player* player); + virtual void adjustPlayer(Player* player) {} + virtual bool canHurtPlayer() { return false; } + + virtual void interact(Player* player, Entity* entity); + virtual void attack(Player* player, Entity* entity); + + virtual ItemInstance* handleInventoryMouseClick(int containerId, int slotNum, int buttonNum, Player* player); + virtual void handleCloseInventory(int containerId, Player* player); + + virtual bool isCreativeType() { return false; } + virtual bool isSurvivalType() { return false; } + + virtual void initAbilities(Abilities& abilities) {} + + virtual void releaseUsingItem(Player* player); + + float oDestroyProgress = 0; + float destroyProgress = 0; +protected: + int destroyTicks = 0; + int destroyDelay = 0; +}; + diff --git a/src/gamemode/SurvivalMode.h b/src/gamemode/SurvivalMode.h index 784f9c8..df30099 100755 --- a/src/gamemode/SurvivalMode.h +++ b/src/gamemode/SurvivalMode.h @@ -1,31 +1,29 @@ -#ifndef NET_MINECRAFT_CLIENT_GAMEMODE__SurvivalMode_H__ -#define NET_MINECRAFT_CLIENT_GAMEMODE__SurvivalMode_H__ - -#include "GameMode.h" - -class Abilities; -class Minecraft; - -class SurvivalMode: public GameMode -{ - typedef GameMode super; -public: - SurvivalMode(Minecraft& minecraft); - - bool destroyBlock(Player* player, int x, int y, int z, int face); - void startDestroyBlock(Player* player, int x, int y, int z, int face); - void continueDestroyBlock(Player* player, int x, int y, int z, int face); - void stopDestroyBlock(Player* player); - - bool canHurtPlayer() { return true; } - - bool isSurvivalType() { return true; } - - void initAbilities( Abilities& abilities ); -private: - int xDestroyBlock; - int yDestroyBlock; - int zDestroyBlock; -}; - -#endif /*NET_MINECRAFT_CLIENT_GAMEMODE__SurvivalMode_H__*/ +#pragma once + +#include "GameMode.h" + +class Abilities; +class Minecraft; + +class SurvivalMode: public GameMode +{ + typedef GameMode super; +public: + SurvivalMode(Minecraft& minecraft); + + bool destroyBlock(Player* player, int x, int y, int z, int face); + void startDestroyBlock(Player* player, int x, int y, int z, int face); + void continueDestroyBlock(Player* player, int x, int y, int z, int face); + void stopDestroyBlock(Player* player); + + bool canHurtPlayer() { return true; } + + bool isSurvivalType() { return true; } + + void initAbilities( Abilities& abilities ); +private: + int xDestroyBlock; + int yDestroyBlock; + int zDestroyBlock; +}; + diff --git a/src/locale/I18n.h b/src/locale/I18n.h index 0646f2d..a97fd9f 100755 --- a/src/locale/I18n.h +++ b/src/locale/I18n.h @@ -1,31 +1,29 @@ -#ifndef NET_MINECRAFT_LOCALE__I18n_H__ -#define NET_MINECRAFT_LOCALE__I18n_H__ - -//package net.minecraft.locale; - -#include "IPlatform.h" -#include -#include - -class AppPlatform; -class ItemInstance; - -class I18n { - typedef std::map Map; -public: - static void loadLanguage(IPlatform& platform, const std::string& languageCode); - - static bool get(const std::string& id, std::string& out); - static std::string get(const std::string& id); - - //static std::string get(const std::string& id, Object... args) { - // return lang.getElement(id, args); - //} - static std::string getDescriptionString( const ItemInstance& item ); - -private: - static void fillTranslations(IPlatform& platform, const std::string& filename, bool overwrite); - static Map _strings; -}; - -#endif /*NET_MINECRAFT_LOCALE__I18n_H__*/ +#pragma once + +//package net.minecraft.locale; + +#include "IPlatform.h" +#include +#include + +class AppPlatform; +class ItemInstance; + +class I18n { + typedef std::map Map; +public: + static void loadLanguage(IPlatform& platform, const std::string& languageCode); + + static bool get(const std::string& id, std::string& out); + static std::string get(const std::string& id); + + //static std::string get(const std::string& id, Object... args) { + // return lang.getElement(id, args); + //} + static std::string getDescriptionString( const ItemInstance& item ); + +private: + static void fillTranslations(IPlatform& platform, const std::string& filename, bool overwrite); + static Map _strings; +}; + diff --git a/src/main_glfw.h b/src/main_glfw.h index 22920c6..45770c2 100755 --- a/src/main_glfw.h +++ b/src/main_glfw.h @@ -1,77 +1,75 @@ -#ifndef MAIN_GLFW_H__ -#define MAIN_GLFW_H__ - -#include "App.h" -#include "NinecraftApp.h" -#include "client/renderer/entity/PlayerRenderer.h" -#include "client/renderer/gles.h" -#include "GLFW/glfw3.h" - -#include -#include -#include -#include "platform/input/Keyboard.h" -#include "platform/input/Mouse.h" -#include "platform/input/Multitouch.h" -#include "AppPlatform_glfw.h" -#ifdef __EMSCRIPTEN__ -#include -#endif - -// void loop() { -// using clock = std::chrono::steady_clock; -// auto frameStart = clock::now(); - -// g_app->update(); - -// glfwSwapBuffers(((AppPlatform_glfw*)g_app->platform())->window); -// glfwPollEvents(); - -// glfwSwapInterval(((MAIN_CLASS*)g_app)->options.getBooleanValue(OPTIONS_VSYNC) ? 1 : 0); -// if(((MAIN_CLASS*)g_app)->options.getBooleanValue(OPTIONS_LIMIT_FRAMERATE)) { -// auto frameEnd = clock::now(); -// auto elapsed = std::chrono::duration_cast(frameEnd - frameStart); -// auto target = std::chrono::microseconds(33333); // ~30 fps -// if(elapsed < target) -// std::this_thread::sleep_for(target - elapsed); -// } -// } - -int main(void) { - AppContext appContext; - - appContext.platform = new AppPlatformGlfw(); - - AppPlatformGlfw* platform = (AppPlatformGlfw*)appContext.platform; - - if (!platform->init()) { - return 1; - } - - App* app = (App*)new NinecraftApp(); - app->init(appContext); - app->setSize(platform->getScreenWidth(), platform->getScreenHeight()); - - auto loop = [app]() { - app->update(); - }; - -#ifdef __EMSCRIPTEN__ - emscripten_set_main_loop(loop, 0, 1); -#else - // Main event loop - while(!app->wantToQuit()) { - loop(); - } -#endif - - delete app; - - appContext.platform->finish(); - - delete appContext.platform; - - return 0; -} - -#endif /*MAIN_GLFW_H__*/ +#pragma once + +#include "App.h" +#include "NinecraftApp.h" +#include "client/renderer/entity/PlayerRenderer.h" +#include "client/renderer/gles.h" +#include "GLFW/glfw3.h" + +#include +#include +#include +#include "platform/input/Keyboard.h" +#include "platform/input/Mouse.h" +#include "platform/input/Multitouch.h" +#include "AppPlatform_glfw.h" +#ifdef __EMSCRIPTEN__ +#include +#endif + +// void loop() { +// using clock = std::chrono::steady_clock; +// auto frameStart = clock::now(); + +// g_app->update(); + +// glfwSwapBuffers(((AppPlatform_glfw*)g_app->platform())->window); +// glfwPollEvents(); + +// glfwSwapInterval(((MAIN_CLASS*)g_app)->options.getBooleanValue(OPTIONS_VSYNC) ? 1 : 0); +// if(((MAIN_CLASS*)g_app)->options.getBooleanValue(OPTIONS_LIMIT_FRAMERATE)) { +// auto frameEnd = clock::now(); +// auto elapsed = std::chrono::duration_cast(frameEnd - frameStart); +// auto target = std::chrono::microseconds(33333); // ~30 fps +// if(elapsed < target) +// std::this_thread::sleep_for(target - elapsed); +// } +// } + +int main(void) { + AppContext appContext; + + appContext.platform = new AppPlatformGlfw(); + + AppPlatformGlfw* platform = (AppPlatformGlfw*)appContext.platform; + + if (!platform->init()) { + return 1; + } + + App* app = (App*)new NinecraftApp(); + app->init(appContext); + app->setSize(platform->getScreenWidth(), platform->getScreenHeight()); + + auto loop = [app]() { + app->update(); + }; + +#ifdef __EMSCRIPTEN__ + emscripten_set_main_loop(loop, 0, 1); +#else + // Main event loop + while(!app->wantToQuit()) { + loop(); + } +#endif + + delete app; + + appContext.platform->finish(); + + delete appContext.platform; + + return 0; +} + diff --git a/src/main_rpi.h b/src/main_rpi.h index b2dea8c..b882bcb 100755 --- a/src/main_rpi.h +++ b/src/main_rpi.h @@ -1,5 +1,4 @@ -#ifndef MAIN_RPI_H__ -#define MAIN_RPI_H__ +#pragma once #include @@ -436,4 +435,3 @@ int main(int argc, char** argv) { return 0; } -#endif diff --git a/src/main_win32.h b/src/main_win32.h index 69d0165..01bd7ce 100755 --- a/src/main_win32.h +++ b/src/main_win32.h @@ -1,331 +1,329 @@ -#ifndef MAIN_WIN32_H__ -#define MAIN_WIN32_H__ - -/* -#define _CRTDBG_MAP_ALLOC -#include -#include -*/ - -#include "client/renderer/gles.h" -#include -// #include -#define WIN32_LEAN_AND_MEAN 1 -#include -#include - -#include -#include -#include "SharedConstants.h" - -#include -#include "platform/input/Mouse.h" -#include "platform/input/Multitouch.h" -#include "util/Mth.h" -#include "AppPlatform_win32.h" - -static App* g_app = 0; -static volatile bool g_running = true; - -static int getBits(int bits, int startBitInclusive, int endBitExclusive, int shiftTruncate) { - int sum = 0; - for (int i = startBitInclusive; i> startBitInclusive) : sum; -} - -void resizeWindow(HWND hWnd, int nWidth, int nHeight) { - RECT rcClient, rcWindow; - POINT ptDiff; - GetClientRect(hWnd, &rcClient); - GetWindowRect(hWnd, &rcWindow); - ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right; - ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom; - MoveWindow(hWnd,rcWindow.left, rcWindow.top, nWidth + ptDiff.x, nHeight + ptDiff.y, TRUE); -} - -void toggleResolutions(HWND hwnd, int direction) { - static int n = 0; - static int sizes[][3] = { - {854, 480, 1}, - {800, 480, 1}, - {480, 320, 1}, - {1024, 768, 1}, - {1280, 800, 1}, - {1024, 580, 1} - }; - static int count = sizeof(sizes) / sizeof(sizes[0]); - n = (count + n + direction) % count; - - int* size = sizes[n]; - int k = size[2]; - - resizeWindow(hwnd, k * size[0], k * size[1]); -} - -LRESULT WINAPI windowProc ( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { - LRESULT retval = 1; - - switch (uMsg) - { - case WM_KEYDOWN: { - if (wParam == 33) toggleResolutions(hWnd, -1); - if (wParam == 34) toggleResolutions(hWnd, +1); - - //if (wParam == 'Q') ((Minecraft*)g_app)->leaveGame(); - Keyboard::feed((unsigned char) wParam, 1); //(unsigned char) getBits(lParam, 16, 23, 1) - - //char* lParamConv = (char*) &lParam; - //int convertResult = ToUnicode(wParam, lParamConv[1], ) - - return 0; - } - case WM_KEYUP: { - Keyboard::feed((unsigned char) wParam, 0); //(unsigned char) getBits(lParam, 16, 23, 1) - return 0; - } - case WM_CHAR: { - //LOGW("WM_CHAR: %d\n", wParam); - if(wParam >= 32) - Keyboard::feedText(wParam); - return 0; - } - case WM_LBUTTONDOWN: { - Mouse::feed( MouseAction::ACTION_LEFT, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); - Multitouch::feed(1, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), 0); - break; - } - case WM_LBUTTONUP: { - Mouse::feed( MouseAction::ACTION_LEFT, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); - Multitouch::feed(1, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), 0); - break; - } - case WM_RBUTTONDOWN: { - Mouse::feed( MouseAction::ACTION_RIGHT, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); - break; - } - case WM_RBUTTONUP: { - Mouse::feed( MouseAction::ACTION_RIGHT, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); - break; - } - case WM_MOUSEMOVE: { - Mouse::feed( MouseAction::ACTION_MOVE, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); - Multitouch::feed(0, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), 0); - break; - } - case WM_MOUSEWHEEL: { - // wheel delta is multiples of WHEEL_DELTA (120); convert to +/-1 - int delta = GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA; - short x = GET_X_LPARAM(lParam); - short y = GET_Y_LPARAM(lParam); - Mouse::feed(MouseAction::ACTION_WHEEL, 0, x, y, 0, delta); - break; - } - default: - if (uMsg == WM_NCDESTROY) g_running = false; - else { - if (uMsg == WM_SIZE) { - if (g_app) g_app->setSize( GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) ); - } - } - retval = DefWindowProc (hWnd, uMsg, wParam, lParam); - break; - } - return retval; -} - -void platform(HWND *result, int width, int height) { - WNDCLASS wc; - RECT wRect; - HWND hwnd; - HINSTANCE hInstance; - - wRect.left = 0L; - wRect.right = (long)width; - wRect.top = 0L; - wRect.bottom = (long)height; - - hInstance = GetModuleHandle(NULL); - - wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; - wc.lpfnWndProc = (WNDPROC)windowProc; - wc.cbClsExtra = 0; - wc.cbWndExtra = 0; - wc.hInstance = hInstance; - wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = NULL; - wc.lpszMenuName = NULL; - wc.lpszClassName = "OGLES"; - - RegisterClass(&wc); - - AdjustWindowRectEx(&wRect, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_APPWINDOW | WS_EX_WINDOWEDGE); - - std::string windowName("Minecraft PE" + Common::getGameVersionString()); - - hwnd = CreateWindowEx(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, "OGLES", windowName.c_str(), WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, wRect.right-wRect.left, wRect.bottom-wRect.top, NULL, NULL, hInstance, NULL); - *result = hwnd; -} - -/** Thread that reads input data via UDP network datagrams - and fills Mouse and Keyboard structures accordingly. - @note: The bound local net address is unfortunately - hard coded right now (to prevent wrong Interface) */ -void inputNetworkThread(void* userdata) -{ - // set up an UDP socket for listening - WSADATA wsaData; - if (WSAStartup(0x101, &wsaData)) { - printf("Couldn't initialize winsock\n"); - return; - } - - SOCKET s = socket(AF_INET, SOCK_DGRAM, 0); - if (s == INVALID_SOCKET) { - printf("Couldn't create socket\n"); - return; - } - - sockaddr_in addr; - addr.sin_family = AF_INET; - addr.sin_port = htons(9991); - addr.sin_addr.s_addr = inet_addr("192.168.0.119"); - - if (bind(s, (sockaddr*)&addr, sizeof(addr))) { - printf("Couldn't bind socket to port 9991\n"); - return; - } - - sockaddr fromAddr; - int fromAddrLen = sizeof(fromAddr); - - char buf[1500]; - int* iptrBuf = (int*)buf; - - printf("input-server listening...\n"); - - while (1) { - int read = recvfrom(s, buf, 1500, 0, &fromAddr, &fromAddrLen); - if (read < 0) - { - printf("recvfrom failed with code: %d\n", WSAGetLastError()); - return; - } - // Keyboard - if (read == 2) { - Keyboard::feed((unsigned char) buf[0], (int)buf[1]); - } - // Mouse - else if (read == 16) { - Mouse::feed(iptrBuf[0], iptrBuf[1], iptrBuf[2], iptrBuf[2]); - } - } -} - -int main(void) { - AppContext appContext; - MSG sMessage; - -#ifndef STANDALONE_SERVER - - EGLint aEGLAttributes[] = { - EGL_RED_SIZE, 8, - EGL_GREEN_SIZE, 8, - EGL_BLUE_SIZE, 8, - EGL_ALPHA_SIZE, 8, - EGL_DEPTH_SIZE, 16, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT, - EGL_NONE - }; - EGLint aEGLContextAttributes[] = { - EGL_CONTEXT_CLIENT_VERSION, 1, - EGL_NONE - }; - - EGLConfig m_eglConfig[1]; - EGLint nConfigs; - - HWND hwnd; - g_running = true; - - // Platform init. - appContext.platform = new AppPlatform_win32(); - platform(&hwnd, appContext.platform->getScreenWidth(), appContext.platform->getScreenHeight()); - ShowWindow(hwnd, SW_SHOW); - SetForegroundWindow(hwnd); - SetFocus(hwnd); - - // EGL init. - appContext.display = eglGetDisplay(GetDC(hwnd)); - //m_eglDisplay = eglGetDisplay((EGLNativeDisplayType) EGL_DEFAULT_DISPLAY); - - eglInitialize(appContext.display, NULL, NULL); - - eglChooseConfig(appContext.display, aEGLAttributes, m_eglConfig, 1, &nConfigs); - printf("EGLConfig = %p\n", m_eglConfig[0]); - - appContext.surface = eglCreateWindowSurface(appContext.display, m_eglConfig[0], (NativeWindowType)hwnd, 0); - printf("EGLSurface = %p\n", appContext.surface); - - appContext.context = eglCreateContext(appContext.display, m_eglConfig[0], EGL_NO_CONTEXT, NULL);//aEGLContextAttributes); - printf("EGLContext = %p\n", appContext.context); - if (!appContext.context) { - printf("EGL error: %d\n", eglGetError()); - } - - eglMakeCurrent(appContext.display, appContext.surface, appContext.surface, appContext.context); - - glInit(); - -#endif - App* app = new MAIN_CLASS(); - - g_app = app; - ((MAIN_CLASS*)g_app)->externalStoragePath = "."; - ((MAIN_CLASS*)g_app)->externalCacheStoragePath = "."; - g_app->init(appContext); - g_app->setSize(appContext.platform->getScreenWidth(), appContext.platform->getScreenHeight()); - - //_beginthread(inputNetworkThread, 0, 0); - - // Main event loop - while(g_running && !app->wantToQuit()) - { - // Do Windows stuff: - while (PeekMessage (&sMessage, NULL, 0, 0, PM_REMOVE) > 0) { - if(sMessage.message == WM_QUIT) { - g_running = false; - break; - } - else { - TranslateMessage(&sMessage); - DispatchMessage(&sMessage); - } - } - app->update(); - - //Sleep(30); - } - - Sleep(50); - delete app; - Sleep(50); - appContext.platform->finish(); - Sleep(50); - delete appContext.platform; - Sleep(50); - //printf("_crtDumpMemoryLeaks: %d\n", _CrtDumpMemoryLeaks()); - -#ifndef STANDALONE_SERVER - // Exit. - eglMakeCurrent(appContext.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - eglDestroyContext(appContext.display, appContext.context); - eglDestroySurface(appContext.display, appContext.surface); - eglTerminate(appContext.display); -#endif - - return 0; -} - -#endif /*MAIN_WIN32_H__*/ +#pragma once + +/* +#define _CRTDBG_MAP_ALLOC +#include +#include +*/ + +#include "client/renderer/gles.h" +#include +// #include +#define WIN32_LEAN_AND_MEAN 1 +#include +#include + +#include +#include +#include "SharedConstants.h" + +#include +#include "platform/input/Mouse.h" +#include "platform/input/Multitouch.h" +#include "util/Mth.h" +#include "AppPlatform_win32.h" + +static App* g_app = 0; +static volatile bool g_running = true; + +static int getBits(int bits, int startBitInclusive, int endBitExclusive, int shiftTruncate) { + int sum = 0; + for (int i = startBitInclusive; i> startBitInclusive) : sum; +} + +void resizeWindow(HWND hWnd, int nWidth, int nHeight) { + RECT rcClient, rcWindow; + POINT ptDiff; + GetClientRect(hWnd, &rcClient); + GetWindowRect(hWnd, &rcWindow); + ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right; + ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom; + MoveWindow(hWnd,rcWindow.left, rcWindow.top, nWidth + ptDiff.x, nHeight + ptDiff.y, TRUE); +} + +void toggleResolutions(HWND hwnd, int direction) { + static int n = 0; + static int sizes[][3] = { + {854, 480, 1}, + {800, 480, 1}, + {480, 320, 1}, + {1024, 768, 1}, + {1280, 800, 1}, + {1024, 580, 1} + }; + static int count = sizeof(sizes) / sizeof(sizes[0]); + n = (count + n + direction) % count; + + int* size = sizes[n]; + int k = size[2]; + + resizeWindow(hwnd, k * size[0], k * size[1]); +} + +LRESULT WINAPI windowProc ( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { + LRESULT retval = 1; + + switch (uMsg) + { + case WM_KEYDOWN: { + if (wParam == 33) toggleResolutions(hWnd, -1); + if (wParam == 34) toggleResolutions(hWnd, +1); + + //if (wParam == 'Q') ((Minecraft*)g_app)->leaveGame(); + Keyboard::feed((unsigned char) wParam, 1); //(unsigned char) getBits(lParam, 16, 23, 1) + + //char* lParamConv = (char*) &lParam; + //int convertResult = ToUnicode(wParam, lParamConv[1], ) + + return 0; + } + case WM_KEYUP: { + Keyboard::feed((unsigned char) wParam, 0); //(unsigned char) getBits(lParam, 16, 23, 1) + return 0; + } + case WM_CHAR: { + //LOGW("WM_CHAR: %d\n", wParam); + if(wParam >= 32) + Keyboard::feedText(wParam); + return 0; + } + case WM_LBUTTONDOWN: { + Mouse::feed( MouseAction::ACTION_LEFT, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); + Multitouch::feed(1, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), 0); + break; + } + case WM_LBUTTONUP: { + Mouse::feed( MouseAction::ACTION_LEFT, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); + Multitouch::feed(1, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), 0); + break; + } + case WM_RBUTTONDOWN: { + Mouse::feed( MouseAction::ACTION_RIGHT, 1, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); + break; + } + case WM_RBUTTONUP: { + Mouse::feed( MouseAction::ACTION_RIGHT, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); + break; + } + case WM_MOUSEMOVE: { + Mouse::feed( MouseAction::ACTION_MOVE, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); + Multitouch::feed(0, 0, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), 0); + break; + } + case WM_MOUSEWHEEL: { + // wheel delta is multiples of WHEEL_DELTA (120); convert to +/-1 + int delta = GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA; + short x = GET_X_LPARAM(lParam); + short y = GET_Y_LPARAM(lParam); + Mouse::feed(MouseAction::ACTION_WHEEL, 0, x, y, 0, delta); + break; + } + default: + if (uMsg == WM_NCDESTROY) g_running = false; + else { + if (uMsg == WM_SIZE) { + if (g_app) g_app->setSize( GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) ); + } + } + retval = DefWindowProc (hWnd, uMsg, wParam, lParam); + break; + } + return retval; +} + +void platform(HWND *result, int width, int height) { + WNDCLASS wc; + RECT wRect; + HWND hwnd; + HINSTANCE hInstance; + + wRect.left = 0L; + wRect.right = (long)width; + wRect.top = 0L; + wRect.bottom = (long)height; + + hInstance = GetModuleHandle(NULL); + + wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; + wc.lpfnWndProc = (WNDPROC)windowProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = hInstance; + wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = NULL; + wc.lpszMenuName = NULL; + wc.lpszClassName = "OGLES"; + + RegisterClass(&wc); + + AdjustWindowRectEx(&wRect, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_APPWINDOW | WS_EX_WINDOWEDGE); + + std::string windowName("Minecraft PE" + Common::getGameVersionString()); + + hwnd = CreateWindowEx(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, "OGLES", windowName.c_str(), WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, wRect.right-wRect.left, wRect.bottom-wRect.top, NULL, NULL, hInstance, NULL); + *result = hwnd; +} + +/** Thread that reads input data via UDP network datagrams + and fills Mouse and Keyboard structures accordingly. + @note: The bound local net address is unfortunately + hard coded right now (to prevent wrong Interface) */ +void inputNetworkThread(void* userdata) +{ + // set up an UDP socket for listening + WSADATA wsaData; + if (WSAStartup(0x101, &wsaData)) { + printf("Couldn't initialize winsock\n"); + return; + } + + SOCKET s = socket(AF_INET, SOCK_DGRAM, 0); + if (s == INVALID_SOCKET) { + printf("Couldn't create socket\n"); + return; + } + + sockaddr_in addr; + addr.sin_family = AF_INET; + addr.sin_port = htons(9991); + addr.sin_addr.s_addr = inet_addr("192.168.0.119"); + + if (bind(s, (sockaddr*)&addr, sizeof(addr))) { + printf("Couldn't bind socket to port 9991\n"); + return; + } + + sockaddr fromAddr; + int fromAddrLen = sizeof(fromAddr); + + char buf[1500]; + int* iptrBuf = (int*)buf; + + printf("input-server listening...\n"); + + while (1) { + int read = recvfrom(s, buf, 1500, 0, &fromAddr, &fromAddrLen); + if (read < 0) + { + printf("recvfrom failed with code: %d\n", WSAGetLastError()); + return; + } + // Keyboard + if (read == 2) { + Keyboard::feed((unsigned char) buf[0], (int)buf[1]); + } + // Mouse + else if (read == 16) { + Mouse::feed(iptrBuf[0], iptrBuf[1], iptrBuf[2], iptrBuf[2]); + } + } +} + +int main(void) { + AppContext appContext; + MSG sMessage; + +#ifndef STANDALONE_SERVER + + EGLint aEGLAttributes[] = { + EGL_RED_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, + EGL_DEPTH_SIZE, 16, + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT, + EGL_NONE + }; + EGLint aEGLContextAttributes[] = { + EGL_CONTEXT_CLIENT_VERSION, 1, + EGL_NONE + }; + + EGLConfig m_eglConfig[1]; + EGLint nConfigs; + + HWND hwnd; + g_running = true; + + // Platform init. + appContext.platform = new AppPlatform_win32(); + platform(&hwnd, appContext.platform->getScreenWidth(), appContext.platform->getScreenHeight()); + ShowWindow(hwnd, SW_SHOW); + SetForegroundWindow(hwnd); + SetFocus(hwnd); + + // EGL init. + appContext.display = eglGetDisplay(GetDC(hwnd)); + //m_eglDisplay = eglGetDisplay((EGLNativeDisplayType) EGL_DEFAULT_DISPLAY); + + eglInitialize(appContext.display, NULL, NULL); + + eglChooseConfig(appContext.display, aEGLAttributes, m_eglConfig, 1, &nConfigs); + printf("EGLConfig = %p\n", m_eglConfig[0]); + + appContext.surface = eglCreateWindowSurface(appContext.display, m_eglConfig[0], (NativeWindowType)hwnd, 0); + printf("EGLSurface = %p\n", appContext.surface); + + appContext.context = eglCreateContext(appContext.display, m_eglConfig[0], EGL_NO_CONTEXT, NULL);//aEGLContextAttributes); + printf("EGLContext = %p\n", appContext.context); + if (!appContext.context) { + printf("EGL error: %d\n", eglGetError()); + } + + eglMakeCurrent(appContext.display, appContext.surface, appContext.surface, appContext.context); + + glInit(); + +#endif + App* app = new MAIN_CLASS(); + + g_app = app; + ((MAIN_CLASS*)g_app)->externalStoragePath = "."; + ((MAIN_CLASS*)g_app)->externalCacheStoragePath = "."; + g_app->init(appContext); + g_app->setSize(appContext.platform->getScreenWidth(), appContext.platform->getScreenHeight()); + + //_beginthread(inputNetworkThread, 0, 0); + + // Main event loop + while(g_running && !app->wantToQuit()) + { + // Do Windows stuff: + while (PeekMessage (&sMessage, NULL, 0, 0, PM_REMOVE) > 0) { + if(sMessage.message == WM_QUIT) { + g_running = false; + break; + } + else { + TranslateMessage(&sMessage); + DispatchMessage(&sMessage); + } + } + app->update(); + + //Sleep(30); + } + + Sleep(50); + delete app; + Sleep(50); + appContext.platform->finish(); + Sleep(50); + delete appContext.platform; + Sleep(50); + //printf("_crtDumpMemoryLeaks: %d\n", _CrtDumpMemoryLeaks()); + +#ifndef STANDALONE_SERVER + // Exit. + eglMakeCurrent(appContext.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + eglDestroyContext(appContext.display, appContext.context); + eglDestroySurface(appContext.display, appContext.surface); + eglTerminate(appContext.display); +#endif + + return 0; +} + diff --git a/src/nbt/ByteArrayTag.h b/src/nbt/ByteArrayTag.h index 6f32f40..a609850 100755 --- a/src/nbt/ByteArrayTag.h +++ b/src/nbt/ByteArrayTag.h @@ -1,79 +1,77 @@ -#ifndef COM_MOJANG_NBT__ByteArrayTag_H__ -#define COM_MOJANG_NBT__ByteArrayTag_H__ - -//package com.mojang.nbt; - -/* import java.io.* */ - -#include "Tag.h" -#include - -typedef struct TagMemoryChunk { - TagMemoryChunk() - : data(NULL), - len(0) - {} - void* data; - int len; -} TagMemoryChunk; - -class ByteArrayTag: public Tag -{ - typedef Tag super; -public: - TagMemoryChunk data; - - ByteArrayTag(const std::string& name) - : super(name) - { - } - - ByteArrayTag(const std::string& name, TagMemoryChunk data) - : super(name), - data(data) - { - } - - char getId() const { - return TAG_Byte_Array; - } - - std::string toString() const { - std::stringstream ss; - ss << "[" << data.len << " bytes]"; - return ss.str(); - } - - //@Override - bool equals(const Tag& rhs) const { - if (super::equals(rhs)) { - ByteArrayTag& o = (ByteArrayTag&) rhs; - if (data.len != o.data.len) - return false; - - return memcmp(data.data, o.data.data, data.len) == 0; - } - return false; - } - - //@Override - Tag* copy() const { - TagMemoryChunk chunk; - chunk.data = new char[data.len]; - memcpy(chunk.data, data.data, data.len); - return new ByteArrayTag(getName(), chunk); - } - - void write(IDataOutput* dos) /*throws IOException*/ { - dos->writeInt(data.len); - dos->writeBytes(data.data, data.len); - } - - void load(IDataInput* dis) /*throws IOException*/ { - int length = dis->readInt(); - data.data = new char[length]; - dis->readBytes(data.data, length); - } -}; - -#endif /*COM_MOJANG_NBT__ByteArrayTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +/* import java.io.* */ + +#include "Tag.h" +#include + +typedef struct TagMemoryChunk { + TagMemoryChunk() + : data(NULL), + len(0) + {} + void* data; + int len; +} TagMemoryChunk; + +class ByteArrayTag: public Tag +{ + typedef Tag super; +public: + TagMemoryChunk data; + + ByteArrayTag(const std::string& name) + : super(name) + { + } + + ByteArrayTag(const std::string& name, TagMemoryChunk data) + : super(name), + data(data) + { + } + + char getId() const { + return TAG_Byte_Array; + } + + std::string toString() const { + std::stringstream ss; + ss << "[" << data.len << " bytes]"; + return ss.str(); + } + + //@Override + bool equals(const Tag& rhs) const { + if (super::equals(rhs)) { + ByteArrayTag& o = (ByteArrayTag&) rhs; + if (data.len != o.data.len) + return false; + + return memcmp(data.data, o.data.data, data.len) == 0; + } + return false; + } + + //@Override + Tag* copy() const { + TagMemoryChunk chunk; + chunk.data = new char[data.len]; + memcpy(chunk.data, data.data, data.len); + return new ByteArrayTag(getName(), chunk); + } + + void write(IDataOutput* dos) /*throws IOException*/ { + dos->writeInt(data.len); + dos->writeBytes(data.data, data.len); + } + + void load(IDataInput* dis) /*throws IOException*/ { + int length = dis->readInt(); + data.data = new char[length]; + dis->readBytes(data.data, length); + } +}; + diff --git a/src/nbt/ByteTag.h b/src/nbt/ByteTag.h index de3f648..0ec0da2 100755 --- a/src/nbt/ByteTag.h +++ b/src/nbt/ByteTag.h @@ -1,57 +1,55 @@ -#ifndef COM_MOJANG_NBT__ByteTag_H__ -#define COM_MOJANG_NBT__ByteTag_H__ - -//package com.mojang.nbt; - -/* import java.io.* */ - -#include "Tag.h" -#include - -class ByteTag: public Tag -{ - typedef Tag super; -public: - char data; - - ByteTag(const std::string& name) - : super(name) - {} - - ByteTag(const std::string& name, char data) - : super(name), - data(data) - { - } - - void write(IDataOutput* dos) /*throws IOException*/ { - dos->writeByte(data); - } - - void load(IDataInput* dis) /*throws IOException*/ { - data = dis->readByte(); - } - - char getId() const { - return TAG_Byte; - } - - std::string toString() const { - return std::string(data, 1); - } - - //@Override - bool equals(const Tag& rhs) const { - if (super::equals(rhs)) { - return data == ((ByteTag&)rhs).data; - } - return false; - } - - //@Override - Tag* copy() const { - return new ByteTag(getName(), data); - } -}; - -#endif /*COM_MOJANG_NBT__ByteTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +/* import java.io.* */ + +#include "Tag.h" +#include + +class ByteTag: public Tag +{ + typedef Tag super; +public: + char data; + + ByteTag(const std::string& name) + : super(name) + {} + + ByteTag(const std::string& name, char data) + : super(name), + data(data) + { + } + + void write(IDataOutput* dos) /*throws IOException*/ { + dos->writeByte(data); + } + + void load(IDataInput* dis) /*throws IOException*/ { + data = dis->readByte(); + } + + char getId() const { + return TAG_Byte; + } + + std::string toString() const { + return std::string(data, 1); + } + + //@Override + bool equals(const Tag& rhs) const { + if (super::equals(rhs)) { + return data == ((ByteTag&)rhs).data; + } + return false; + } + + //@Override + Tag* copy() const { + return new ByteTag(getName(), data); + } +}; + diff --git a/src/nbt/CompoundTag.h b/src/nbt/CompoundTag.h index c91bd69..ab83a78 100755 --- a/src/nbt/CompoundTag.h +++ b/src/nbt/CompoundTag.h @@ -1,242 +1,240 @@ -#ifndef COM_MOJANG_NBT__CompoundTag_H__ -#define COM_MOJANG_NBT__CompoundTag_H__ - -//package com.mojang.nbt; - -#include "Tag.h" -#include -#include -#include -#include -#include "../util/CollectionUtils.h" - -#include "ByteTag.h" -#include "ShortTag.h" -#include "IntTag.h" -#include "LongTag.h" -#include "FloatTag.h" -#include "DoubleTag.h" -#include "ListTag.h" -#include "StringTag.h" -#include "ByteArrayTag.h" - -class CompoundTag: public Tag -{ - typedef Tag super; - typedef std::map TagMap; -public: - CompoundTag() - : super("") - { - } - - CompoundTag(const std::string& name) - : super(name) - { - } - - void write(IDataOutput* dos) /*throws IOException*/ { - for (TagMap::iterator it = tags.begin(); it != tags.end(); ++it) { - Tag::writeNamedTag(it->second, dos); - } - dos->writeByte(Tag::TAG_End); - } - - void load(IDataInput* dis) /*throws IOException*/ { - tags.clear(); - Tag* tag = NULL; - - while ((tag = Tag::readNamedTag(dis)) && tag->getId() != Tag::TAG_End) { - tags.insert(std::make_pair(tag->getName(), tag)); - } - // is now of type TAG_End (that's new'ed). Delete it. - delete tag; - } - - void getAllTags(std::vector& tags_) const { - //std::transform(tags.begin(), tags.end(), std::back_inserter(tags_), PairValueFunctor()); - for (TagMap::const_iterator it = tags.begin(); it != tags.end(); ++it) { - tags_.push_back(it->second); - } - } - - char getId() const { - return TAG_Compound; - } - - void put(const std::string& name, Tag* tag) { - tags.insert(std::make_pair(name, tag->setName(name))); - } - - void putByte(const std::string& name, char value) { - tags.insert(std::make_pair(name, new ByteTag(name, value))); - } - - void putShort(const std::string& name, short value) { - tags.insert(std::make_pair(name, new ShortTag(name, value))); - } - - void putInt(const std::string& name, int value) { - tags.insert(std::make_pair(name, new IntTag(name, value))); - } - - void putLong(const std::string& name, long value) { - tags.insert(std::make_pair(name, new LongTag(name, value))); - } - - void putFloat(const std::string& name, float value) { - tags.insert(std::make_pair(name, new FloatTag(name, value))); - } - - void putDouble(const std::string& name, float value) { - tags.insert(std::make_pair(name, new DoubleTag(name, value))); - } - - void putString(const std::string& name, const std::string& value) { - tags.insert(std::make_pair(name, new StringTag(name, value))); - } - - void putByteArray(const std::string& name, TagMemoryChunk mem) { - tags.insert(std::make_pair(name, new ByteArrayTag(name, mem))); - } - - void putCompound(const std::string& name, CompoundTag* value) { - tags.insert(std::make_pair(name, value->setName(name))); - } - - void putBoolean(const std::string& string, bool val) { - putByte(string, val ? (char) 1 : 0); - } - - Tag* get(const std::string& name) const { - TagMap::const_iterator it = tags.find(name); - if (it == tags.end()) - return NULL; - return it->second; - } - - inline bool contains(const std::string& name) const { - return tags.find(name) != tags.end(); - } - bool contains(const std::string& name, int type) const { - Tag* tag = get(name); - return tag && tag->getId() == type; - } - - char getByte(const std::string& name) const { - if (!contains(name, TAG_Byte)) return (char) 0; - return ((ByteTag*) get(name))->data; - } - - short getShort(const std::string& name) const { - if (!contains(name, TAG_Short)) return (short) 0; - return ((ShortTag*) get(name))->data; - } - - int getInt(const std::string& name) const { - if (!contains(name, TAG_Int)) return (int) 0; - return ((IntTag*) get(name))->data; - } - - long long getLong(const std::string& name) const { - if (!contains(name, TAG_Long)) return (long long) 0; - return ((LongTag*) get(name))->data; - } - - float getFloat(const std::string& name) const { - if (!contains(name, TAG_Float)) return (float) 0; - return ((FloatTag*) get(name))->data; - } - - double getDouble(const std::string& name) const { - if (!contains(name, TAG_Double)) return (double) 0; - return ((DoubleTag*) get(name))->data; - } - - std::string getString(const std::string& name) const { - if (!contains(name, TAG_String)) return ""; - return ((StringTag*) get(name))->data; - } - - TagMemoryChunk getByteArray(const std::string& name) const { - if (!contains(name, TAG_Byte_Array)) return TagMemoryChunk(); - return ((ByteArrayTag*) get(name))->data; - } - - CompoundTag* getCompound(const std::string& name) const { - if (!contains(name, TAG_Compound)) return new CompoundTag(name); - return (CompoundTag*) get(name); - } - - ListTag* getList(const std::string& name) const { - if (!contains(name, TAG_List)) return new ListTag(name); - return (ListTag*) get(name); - } - - bool getBoolean(const std::string& string) const { - return getByte(string) != 0; - } - - std::string toString() const { - std::stringstream ss; - ss << tags.size() << " entries"; - return ss.str(); - } - - void print(const std::string& prefix_, PrintStream& out) const { - super::print(prefix_, out); - std::string prefix = prefix_; - out.print(prefix); out.println("{"); - prefix += " "; - for (TagMap::const_iterator it = tags.begin(); it != tags.end(); ++it) { - (it->second)->print(prefix, out); - } - out.print(prefix_); - out.println("}"); - } - - bool isEmpty() const { - return tags.empty(); - } - - Tag* copy() const { - CompoundTag* tag = new CompoundTag(getName()); - for (TagMap::const_iterator it = tags.begin(); it != tags.end(); ++it) { - //tag->put(it->first, get(it->first)->copy()); - tag->put(it->first, it->second->copy()); - } - return tag; - } - - //@Override - bool equals(const Tag& obj) const { - if (super::equals(obj)) { - CompoundTag& o = (CompoundTag&) obj; - - if (tags.size() != o.tags.size()) - return false; - - for (TagMap::const_iterator it = tags.begin(), jt = o.tags.begin(); it != tags.end(); ++it, ++jt) { - if (it->first != jt->first) return false; - if (!it->second->equals(*jt->second)) return false; - } - - return true; - } - return false; - } - - void deleteChildren() { - TagMap::iterator it = tags.begin(); - for (; it != tags.end(); ++it) { - if (!it->second) - continue; - it->second->deleteChildren(); - delete it->second; - } - } -private: - TagMap tags; -}; - -#endif /*COM_MOJANG_NBT__CompoundTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +#include "Tag.h" +#include +#include +#include +#include +#include "../util/CollectionUtils.h" + +#include "ByteTag.h" +#include "ShortTag.h" +#include "IntTag.h" +#include "LongTag.h" +#include "FloatTag.h" +#include "DoubleTag.h" +#include "ListTag.h" +#include "StringTag.h" +#include "ByteArrayTag.h" + +class CompoundTag: public Tag +{ + typedef Tag super; + typedef std::map TagMap; +public: + CompoundTag() + : super("") + { + } + + CompoundTag(const std::string& name) + : super(name) + { + } + + void write(IDataOutput* dos) /*throws IOException*/ { + for (TagMap::iterator it = tags.begin(); it != tags.end(); ++it) { + Tag::writeNamedTag(it->second, dos); + } + dos->writeByte(Tag::TAG_End); + } + + void load(IDataInput* dis) /*throws IOException*/ { + tags.clear(); + Tag* tag = NULL; + + while ((tag = Tag::readNamedTag(dis)) && tag->getId() != Tag::TAG_End) { + tags.insert(std::make_pair(tag->getName(), tag)); + } + // is now of type TAG_End (that's new'ed). Delete it. + delete tag; + } + + void getAllTags(std::vector& tags_) const { + //std::transform(tags.begin(), tags.end(), std::back_inserter(tags_), PairValueFunctor()); + for (TagMap::const_iterator it = tags.begin(); it != tags.end(); ++it) { + tags_.push_back(it->second); + } + } + + char getId() const { + return TAG_Compound; + } + + void put(const std::string& name, Tag* tag) { + tags.insert(std::make_pair(name, tag->setName(name))); + } + + void putByte(const std::string& name, char value) { + tags.insert(std::make_pair(name, new ByteTag(name, value))); + } + + void putShort(const std::string& name, short value) { + tags.insert(std::make_pair(name, new ShortTag(name, value))); + } + + void putInt(const std::string& name, int value) { + tags.insert(std::make_pair(name, new IntTag(name, value))); + } + + void putLong(const std::string& name, long value) { + tags.insert(std::make_pair(name, new LongTag(name, value))); + } + + void putFloat(const std::string& name, float value) { + tags.insert(std::make_pair(name, new FloatTag(name, value))); + } + + void putDouble(const std::string& name, float value) { + tags.insert(std::make_pair(name, new DoubleTag(name, value))); + } + + void putString(const std::string& name, const std::string& value) { + tags.insert(std::make_pair(name, new StringTag(name, value))); + } + + void putByteArray(const std::string& name, TagMemoryChunk mem) { + tags.insert(std::make_pair(name, new ByteArrayTag(name, mem))); + } + + void putCompound(const std::string& name, CompoundTag* value) { + tags.insert(std::make_pair(name, value->setName(name))); + } + + void putBoolean(const std::string& string, bool val) { + putByte(string, val ? (char) 1 : 0); + } + + Tag* get(const std::string& name) const { + TagMap::const_iterator it = tags.find(name); + if (it == tags.end()) + return NULL; + return it->second; + } + + inline bool contains(const std::string& name) const { + return tags.find(name) != tags.end(); + } + bool contains(const std::string& name, int type) const { + Tag* tag = get(name); + return tag && tag->getId() == type; + } + + char getByte(const std::string& name) const { + if (!contains(name, TAG_Byte)) return (char) 0; + return ((ByteTag*) get(name))->data; + } + + short getShort(const std::string& name) const { + if (!contains(name, TAG_Short)) return (short) 0; + return ((ShortTag*) get(name))->data; + } + + int getInt(const std::string& name) const { + if (!contains(name, TAG_Int)) return (int) 0; + return ((IntTag*) get(name))->data; + } + + long long getLong(const std::string& name) const { + if (!contains(name, TAG_Long)) return (long long) 0; + return ((LongTag*) get(name))->data; + } + + float getFloat(const std::string& name) const { + if (!contains(name, TAG_Float)) return (float) 0; + return ((FloatTag*) get(name))->data; + } + + double getDouble(const std::string& name) const { + if (!contains(name, TAG_Double)) return (double) 0; + return ((DoubleTag*) get(name))->data; + } + + std::string getString(const std::string& name) const { + if (!contains(name, TAG_String)) return ""; + return ((StringTag*) get(name))->data; + } + + TagMemoryChunk getByteArray(const std::string& name) const { + if (!contains(name, TAG_Byte_Array)) return TagMemoryChunk(); + return ((ByteArrayTag*) get(name))->data; + } + + CompoundTag* getCompound(const std::string& name) const { + if (!contains(name, TAG_Compound)) return new CompoundTag(name); + return (CompoundTag*) get(name); + } + + ListTag* getList(const std::string& name) const { + if (!contains(name, TAG_List)) return new ListTag(name); + return (ListTag*) get(name); + } + + bool getBoolean(const std::string& string) const { + return getByte(string) != 0; + } + + std::string toString() const { + std::stringstream ss; + ss << tags.size() << " entries"; + return ss.str(); + } + + void print(const std::string& prefix_, PrintStream& out) const { + super::print(prefix_, out); + std::string prefix = prefix_; + out.print(prefix); out.println("{"); + prefix += " "; + for (TagMap::const_iterator it = tags.begin(); it != tags.end(); ++it) { + (it->second)->print(prefix, out); + } + out.print(prefix_); + out.println("}"); + } + + bool isEmpty() const { + return tags.empty(); + } + + Tag* copy() const { + CompoundTag* tag = new CompoundTag(getName()); + for (TagMap::const_iterator it = tags.begin(); it != tags.end(); ++it) { + //tag->put(it->first, get(it->first)->copy()); + tag->put(it->first, it->second->copy()); + } + return tag; + } + + //@Override + bool equals(const Tag& obj) const { + if (super::equals(obj)) { + CompoundTag& o = (CompoundTag&) obj; + + if (tags.size() != o.tags.size()) + return false; + + for (TagMap::const_iterator it = tags.begin(), jt = o.tags.begin(); it != tags.end(); ++it, ++jt) { + if (it->first != jt->first) return false; + if (!it->second->equals(*jt->second)) return false; + } + + return true; + } + return false; + } + + void deleteChildren() { + TagMap::iterator it = tags.begin(); + for (; it != tags.end(); ++it) { + if (!it->second) + continue; + it->second->deleteChildren(); + delete it->second; + } + } +private: + TagMap tags; +}; + diff --git a/src/nbt/DoubleTag.h b/src/nbt/DoubleTag.h index 6d1a639..ea6b8a8 100755 --- a/src/nbt/DoubleTag.h +++ b/src/nbt/DoubleTag.h @@ -1,57 +1,55 @@ -#ifndef COM_MOJANG_NBT__DoubleTag_H__ -#define COM_MOJANG_NBT__DoubleTag_H__ - -//package com.mojang.nbt; - -/* import java.io.* */ - -#include "Tag.h" -#include - -class DoubleTag: public Tag { - typedef Tag super; -public: - double data; - - DoubleTag(const std::string& name) - : super(name) - {} - - DoubleTag(const std::string& name, double data) - : super(name), - data(data) - {} - - void write(IDataOutput* dos) /*throws IOException*/ { - dos->writeDouble(data); - } - - void load(IDataInput* dis) /*throws IOException*/ { - data = dis->readDouble(); - } - - char getId() const { - return TAG_Double; - } - - std::string toString() const { - std::stringstream ss; - ss << data; - return ss.str(); - } - - //@Override - Tag* copy() const { - return new DoubleTag(getName(), data); - } - - //@Override - bool equals(const Tag& rhs) const { - if (super::equals(rhs)) { - return data == ((DoubleTag&)rhs).data; - } - return false; - } -}; - -#endif /*COM_MOJANG_NBT__DoubleTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +/* import java.io.* */ + +#include "Tag.h" +#include + +class DoubleTag: public Tag { + typedef Tag super; +public: + double data; + + DoubleTag(const std::string& name) + : super(name) + {} + + DoubleTag(const std::string& name, double data) + : super(name), + data(data) + {} + + void write(IDataOutput* dos) /*throws IOException*/ { + dos->writeDouble(data); + } + + void load(IDataInput* dis) /*throws IOException*/ { + data = dis->readDouble(); + } + + char getId() const { + return TAG_Double; + } + + std::string toString() const { + std::stringstream ss; + ss << data; + return ss.str(); + } + + //@Override + Tag* copy() const { + return new DoubleTag(getName(), data); + } + + //@Override + bool equals(const Tag& rhs) const { + if (super::equals(rhs)) { + return data == ((DoubleTag&)rhs).data; + } + return false; + } +}; + diff --git a/src/nbt/EndTag.h b/src/nbt/EndTag.h index 6b85442..bf1406e 100755 --- a/src/nbt/EndTag.h +++ b/src/nbt/EndTag.h @@ -1,41 +1,39 @@ -#ifndef COM_MOJANG_NBT__EndTag_H__ -#define COM_MOJANG_NBT__EndTag_H__ - -//package com.mojang.nbt; - -/* import java.io.* */ - -class EndTag: public Tag { - typedef Tag super; -public: - EndTag() - : super("") - { - } - - void load(IDataInput* dis) /*throws IOException*/ { - } - - void write(IDataOutput* dos) /*throws IOException*/ { - } - - char getId() const { - return TAG_End; - } - - std::string toString() const { - return "END"; - } - - //@Override - Tag* copy() const { - return new EndTag(); - } - - //@Override - bool equals(const Tag& rhs) const { - return super::equals(rhs); - } -}; - -#endif /*COM_MOJANG_NBT__EndTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +/* import java.io.* */ + +class EndTag: public Tag { + typedef Tag super; +public: + EndTag() + : super("") + { + } + + void load(IDataInput* dis) /*throws IOException*/ { + } + + void write(IDataOutput* dos) /*throws IOException*/ { + } + + char getId() const { + return TAG_End; + } + + std::string toString() const { + return "END"; + } + + //@Override + Tag* copy() const { + return new EndTag(); + } + + //@Override + bool equals(const Tag& rhs) const { + return super::equals(rhs); + } +}; + diff --git a/src/nbt/FloatTag.h b/src/nbt/FloatTag.h index 884f65d..d8576de 100755 --- a/src/nbt/FloatTag.h +++ b/src/nbt/FloatTag.h @@ -1,59 +1,57 @@ -#ifndef COM_MOJANG_NBT__FloatTag_H__ -#define COM_MOJANG_NBT__FloatTag_H__ - -//package com.mojang.nbt; - -/* import java.io.* */ - -#include "Tag.h" -#include - -class FloatTag: public Tag { - typedef Tag super; -public: - float data; - - FloatTag(const std::string& name) - : super(name) - { - } - - FloatTag(const std::string& name, float data) - : super(name), - data(data) - { - } - - void write(IDataOutput* dos) /*throws IOException*/ { - dos->writeFloat(data); - } - - void load(IDataInput* dis) /*throws IOException*/ { - data = dis->readFloat(); - } - - char getId() const { - return TAG_Float; - } - - std::string toString() const { - std::stringstream ss; - ss << data; - return ss.str(); - } - - //@Override - Tag* copy() const { - return new FloatTag(getName(), data); - } - - //@Override - bool equals(const Tag& rhs) const { - if (super::equals(rhs)) { - return data == ((FloatTag&)rhs).data; - } - return false; - } -}; - -#endif /*COM_MOJANG_NBT__FloatTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +/* import java.io.* */ + +#include "Tag.h" +#include + +class FloatTag: public Tag { + typedef Tag super; +public: + float data; + + FloatTag(const std::string& name) + : super(name) + { + } + + FloatTag(const std::string& name, float data) + : super(name), + data(data) + { + } + + void write(IDataOutput* dos) /*throws IOException*/ { + dos->writeFloat(data); + } + + void load(IDataInput* dis) /*throws IOException*/ { + data = dis->readFloat(); + } + + char getId() const { + return TAG_Float; + } + + std::string toString() const { + std::stringstream ss; + ss << data; + return ss.str(); + } + + //@Override + Tag* copy() const { + return new FloatTag(getName(), data); + } + + //@Override + bool equals(const Tag& rhs) const { + if (super::equals(rhs)) { + return data == ((FloatTag&)rhs).data; + } + return false; + } +}; + diff --git a/src/nbt/IntTag.h b/src/nbt/IntTag.h index 5a803af..ca288d5 100755 --- a/src/nbt/IntTag.h +++ b/src/nbt/IntTag.h @@ -1,58 +1,56 @@ -#ifndef COM_MOJANG_NBT__IntTag_H__ -#define COM_MOJANG_NBT__IntTag_H__ - -//package com.mojang.nbt; - -#include "Tag.h" -#include -/* import java.io.* */ - -class IntTag: public Tag { - typedef Tag super; -public: - int data; - - IntTag(const std::string& name) - : super(name) - { - } - - IntTag(const std::string& name, int data) - : super(name), - data(data) - { - } - - void write(IDataOutput* dos) /*throws IOException*/ { - dos->writeInt(data); - } - - void load(IDataInput* dis) /*throws IOException*/ { - data = dis->readInt(); - } - - char getId() const { - return TAG_Int; - } - - std::string toString() const { - std::stringstream ss; - ss << data; - return ss.str(); - } - - //@Override - Tag* copy() const { - return new IntTag(getName(), data); - } - - //@Override - bool equals(const Tag& rhs) const { - if (super::equals(rhs)) { - return data == ((IntTag&)rhs).data; - } - return false; - } -}; - -#endif /*COM_MOJANG_NBT__IntTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +#include "Tag.h" +#include +/* import java.io.* */ + +class IntTag: public Tag { + typedef Tag super; +public: + int data; + + IntTag(const std::string& name) + : super(name) + { + } + + IntTag(const std::string& name, int data) + : super(name), + data(data) + { + } + + void write(IDataOutput* dos) /*throws IOException*/ { + dos->writeInt(data); + } + + void load(IDataInput* dis) /*throws IOException*/ { + data = dis->readInt(); + } + + char getId() const { + return TAG_Int; + } + + std::string toString() const { + std::stringstream ss; + ss << data; + return ss.str(); + } + + //@Override + Tag* copy() const { + return new IntTag(getName(), data); + } + + //@Override + bool equals(const Tag& rhs) const { + if (super::equals(rhs)) { + return data == ((IntTag&)rhs).data; + } + return false; + } +}; + diff --git a/src/nbt/ListTag.h b/src/nbt/ListTag.h index 5f1c913..868c48b 100755 --- a/src/nbt/ListTag.h +++ b/src/nbt/ListTag.h @@ -1,171 +1,169 @@ -#ifndef COM_MOJANG_NBT__ListTag_H__ -#define COM_MOJANG_NBT__ListTag_H__ - -//package com.mojang.nbt; - -#include "Tag.h" -#include - -//template -class ListTag: public Tag -{ - typedef Tag super; - typedef Tag* T; - typedef std::vector List; - -public: - ListTag() - : super("") - { - } - - ListTag(const std::string& name) - : super(name) - { - } - - void write(IDataOutput* dos) /*throws IOException*/ { - if (list.size() > 0) type = list.front()->getId(); - else type = TAG_Byte; - - dos->writeByte(type); - dos->writeInt(list.size()); - - for (List::iterator it = list.begin(); it != list.end(); ++it) { - (*it)->write(dos); - } - } - - //@SuppressWarnings("unchecked") - void load(IDataInput* dis) /*throws IOException*/ { - type = dis->readByte(); - int size = dis->readInt(); - - list.clear();// = List(); - for (int i = 0; i < size; i++) { - Tag* tag = Tag::newTag(type, NullString); - tag->load(dis); - list.insert(list.end(), tag); - } - } - - char getId() const { - return TAG_List; - } - - std::string toString() const { - std::stringstream ss; - ss << list.size() << " entries of type " << Tag::getTagName(type); - return ss.str(); - } - - void print(const std::string& prefix_, PrintStream& out) const { - super::print(prefix_, out); - - std::string prefix = prefix_; - out.print(prefix); out.println("{"); - prefix += " "; - - for (List::const_iterator it = list.begin(); it != list.end(); ++it) { - (*it)->print(prefix, out); - } - out.print(prefix_); out.println("}"); - } - - void add(T tag) { - type = tag->getId(); - list.insert(list.end(), tag); - } - - T get(int index) const { - if (index >= size()) { - errorState |= TAGERR_OUT_OF_BOUNDS; - return NULL; - } - return *(list.begin() + index); - } - float getFloat(int index) { - T tag = get(index); - if (!tag) - return 0; - if (tag->getId() != TAG_Float) { - errorState |= TAGERR_BAD_TYPE; - return 0; - } - return ((FloatTag*)tag)->data; - } - - int size() const { - return list.size(); - } - - //@Override - Tag* copy() const { - ListTag* res = new ListTag(getName()); - res->type = type; - - for (List::const_iterator it = list.begin(); it != list.end(); ++it) { - T copy = (*it)->copy(); - res->list.insert(res->list.end(), copy); - } - return res; - } - - //@SuppressWarnings("rawtypes") - //@Override - bool equals(const Tag& rhs) const { - if (super::equals(rhs)) { - ListTag& o = (ListTag&) rhs; - if (type == o.type && list.size() == o.list.size()) { - for (List::const_iterator it = list.begin(), jt = o.list.begin(); it != list.end(); ++it, ++jt) { - if ((*it)->equals(**jt)) - return false; - } - return true; - } - } - return false; - } - - void deleteChildren() { - for (List::iterator it = list.begin(); it != list.end(); ++it) { - if (*it) { - (*it)->deleteChildren(); - delete (*it); - } - } - } - -private: - List list; - char type; -}; - - -class ListTagFloatAdder { -public: - ListTagFloatAdder() - : tag(NULL) - {} - ListTagFloatAdder(float f) - : tag(NULL) - { - operator() (f); - } - ListTagFloatAdder(ListTag* tag) - : tag(tag) - {} - - ListTagFloatAdder& operator() (const std::string& name, float f) { - if (!tag) tag = new ListTag(); - tag->add( new FloatTag(name, f) ); - return *this; - } - ListTagFloatAdder& operator() (float f) { - return operator() ("", f); - } - - ListTag* tag; -}; - -#endif /*COM_MOJANG_NBT__ListTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +#include "Tag.h" +#include + +//template +class ListTag: public Tag +{ + typedef Tag super; + typedef Tag* T; + typedef std::vector List; + +public: + ListTag() + : super("") + { + } + + ListTag(const std::string& name) + : super(name) + { + } + + void write(IDataOutput* dos) /*throws IOException*/ { + if (list.size() > 0) type = list.front()->getId(); + else type = TAG_Byte; + + dos->writeByte(type); + dos->writeInt(list.size()); + + for (List::iterator it = list.begin(); it != list.end(); ++it) { + (*it)->write(dos); + } + } + + //@SuppressWarnings("unchecked") + void load(IDataInput* dis) /*throws IOException*/ { + type = dis->readByte(); + int size = dis->readInt(); + + list.clear();// = List(); + for (int i = 0; i < size; i++) { + Tag* tag = Tag::newTag(type, NullString); + tag->load(dis); + list.insert(list.end(), tag); + } + } + + char getId() const { + return TAG_List; + } + + std::string toString() const { + std::stringstream ss; + ss << list.size() << " entries of type " << Tag::getTagName(type); + return ss.str(); + } + + void print(const std::string& prefix_, PrintStream& out) const { + super::print(prefix_, out); + + std::string prefix = prefix_; + out.print(prefix); out.println("{"); + prefix += " "; + + for (List::const_iterator it = list.begin(); it != list.end(); ++it) { + (*it)->print(prefix, out); + } + out.print(prefix_); out.println("}"); + } + + void add(T tag) { + type = tag->getId(); + list.insert(list.end(), tag); + } + + T get(int index) const { + if (index >= size()) { + errorState |= TAGERR_OUT_OF_BOUNDS; + return NULL; + } + return *(list.begin() + index); + } + float getFloat(int index) { + T tag = get(index); + if (!tag) + return 0; + if (tag->getId() != TAG_Float) { + errorState |= TAGERR_BAD_TYPE; + return 0; + } + return ((FloatTag*)tag)->data; + } + + int size() const { + return list.size(); + } + + //@Override + Tag* copy() const { + ListTag* res = new ListTag(getName()); + res->type = type; + + for (List::const_iterator it = list.begin(); it != list.end(); ++it) { + T copy = (*it)->copy(); + res->list.insert(res->list.end(), copy); + } + return res; + } + + //@SuppressWarnings("rawtypes") + //@Override + bool equals(const Tag& rhs) const { + if (super::equals(rhs)) { + ListTag& o = (ListTag&) rhs; + if (type == o.type && list.size() == o.list.size()) { + for (List::const_iterator it = list.begin(), jt = o.list.begin(); it != list.end(); ++it, ++jt) { + if ((*it)->equals(**jt)) + return false; + } + return true; + } + } + return false; + } + + void deleteChildren() { + for (List::iterator it = list.begin(); it != list.end(); ++it) { + if (*it) { + (*it)->deleteChildren(); + delete (*it); + } + } + } + +private: + List list; + char type; +}; + + +class ListTagFloatAdder { +public: + ListTagFloatAdder() + : tag(NULL) + {} + ListTagFloatAdder(float f) + : tag(NULL) + { + operator() (f); + } + ListTagFloatAdder(ListTag* tag) + : tag(tag) + {} + + ListTagFloatAdder& operator() (const std::string& name, float f) { + if (!tag) tag = new ListTag(); + tag->add( new FloatTag(name, f) ); + return *this; + } + ListTagFloatAdder& operator() (float f) { + return operator() ("", f); + } + + ListTag* tag; +}; + diff --git a/src/nbt/LongTag.h b/src/nbt/LongTag.h index d620545..f4e0029 100755 --- a/src/nbt/LongTag.h +++ b/src/nbt/LongTag.h @@ -1,56 +1,54 @@ -#ifndef COM_MOJANG_NBT__LongTag_H__ -#define COM_MOJANG_NBT__LongTag_H__ - -//package com.mojang.nbt; -#include "Tag.h" -#include - -class LongTag: public Tag { - typedef Tag super; -public: - long long data; - - LongTag(const std::string& name) - : super(name) - { - } - - LongTag(const std::string& name, long long data) - : super(name), - data(data) - { - } - - void write(IDataOutput* dos) /*throws IOException*/ { - dos->writeLongLong(data); - } - - void load(IDataInput* dis) /*throws IOException*/ { - data = dis->readLongLong(); - } - - char getId() const { - return TAG_Long; - } - - std::string toString() const { - std::stringstream ss; - ss << data; - return ss.str(); - } - - //@Override - Tag* copy() const { - return new LongTag(getName(), data); - } - - //@Override - bool equals(const Tag& rhs) const { - if (super::equals(rhs)) { - return data == ((LongTag&)rhs).data; - } - return false; - } -}; - -#endif /*COM_MOJANG_NBT__LongTag_H__*/ +#pragma once + +//package com.mojang.nbt; +#include "Tag.h" +#include + +class LongTag: public Tag { + typedef Tag super; +public: + long long data; + + LongTag(const std::string& name) + : super(name) + { + } + + LongTag(const std::string& name, long long data) + : super(name), + data(data) + { + } + + void write(IDataOutput* dos) /*throws IOException*/ { + dos->writeLongLong(data); + } + + void load(IDataInput* dis) /*throws IOException*/ { + data = dis->readLongLong(); + } + + char getId() const { + return TAG_Long; + } + + std::string toString() const { + std::stringstream ss; + ss << data; + return ss.str(); + } + + //@Override + Tag* copy() const { + return new LongTag(getName(), data); + } + + //@Override + bool equals(const Tag& rhs) const { + if (super::equals(rhs)) { + return data == ((LongTag&)rhs).data; + } + return false; + } +}; + diff --git a/src/nbt/NbtIo.h b/src/nbt/NbtIo.h index ee9bed3..50db256 100755 --- a/src/nbt/NbtIo.h +++ b/src/nbt/NbtIo.h @@ -1,26 +1,24 @@ -#ifndef COM_MOJANG_NBT__NbtIo_H__ -#define COM_MOJANG_NBT__NbtIo_H__ - -//package com.mojang.nbt; - -#include "CompoundTag.h" -#include "../util/DataIO.h" - -class NbtIo -{ -public: - static CompoundTag* read(IDataInput* dis) { - Tag *tag = Tag::readNamedTag(dis); - if (tag && tag->getId() == Tag::TAG_Compound) - return (CompoundTag*) tag; - return NULL; - } - - static bool write(CompoundTag* tag, IDataOutput* dos) { - if (!tag) return false; - Tag::writeNamedTag(tag, dos); - return false; - } -}; - -#endif /*COM_MOJANG_NBT__NbtIo_H__*/ +#pragma once + +//package com.mojang.nbt; + +#include "CompoundTag.h" +#include "../util/DataIO.h" + +class NbtIo +{ +public: + static CompoundTag* read(IDataInput* dis) { + Tag *tag = Tag::readNamedTag(dis); + if (tag && tag->getId() == Tag::TAG_Compound) + return (CompoundTag*) tag; + return NULL; + } + + static bool write(CompoundTag* tag, IDataOutput* dos) { + if (!tag) return false; + Tag::writeNamedTag(tag, dos); + return false; + } +}; + diff --git a/src/nbt/ShortTag.h b/src/nbt/ShortTag.h index c2e0caf..fcdf195 100755 --- a/src/nbt/ShortTag.h +++ b/src/nbt/ShortTag.h @@ -1,59 +1,57 @@ -#ifndef COM_MOJANG_NBT__ShortTag_H__ -#define COM_MOJANG_NBT__ShortTag_H__ - -//package com.mojang.nbt; - -/* import java.io.* */ - -#include "Tag.h" -#include - -class ShortTag: public Tag { - typedef Tag super; -public: - short data; - - ShortTag(const std::string& name) - : super(name) - { - } - - ShortTag(const std::string& name, short data) - : super(name), - data(data) - { - } - - void write(IDataOutput* dos) /*throws IOException*/ { - dos->writeShort(data); - } - - void load(IDataInput* dis) /*throws IOException*/ { - data = dis->readShort(); - } - - char getId() const { - return TAG_Short; - } - - std::string toString() const { - std::stringstream ss; - ss << data; - return ss.str(); - } - - //@Override - Tag* copy() const { - return new ShortTag(getName(), data); - } - - //@Override - bool equals(const Tag& rhs) const { - if (super::equals(rhs)) { - return data == ((ShortTag&)rhs).data; - } - return false; - } -}; - -#endif /*COM_MOJANG_NBT__ShortTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +/* import java.io.* */ + +#include "Tag.h" +#include + +class ShortTag: public Tag { + typedef Tag super; +public: + short data; + + ShortTag(const std::string& name) + : super(name) + { + } + + ShortTag(const std::string& name, short data) + : super(name), + data(data) + { + } + + void write(IDataOutput* dos) /*throws IOException*/ { + dos->writeShort(data); + } + + void load(IDataInput* dis) /*throws IOException*/ { + data = dis->readShort(); + } + + char getId() const { + return TAG_Short; + } + + std::string toString() const { + std::stringstream ss; + ss << data; + return ss.str(); + } + + //@Override + Tag* copy() const { + return new ShortTag(getName(), data); + } + + //@Override + bool equals(const Tag& rhs) const { + if (super::equals(rhs)) { + return data == ((ShortTag&)rhs).data; + } + return false; + } +}; + diff --git a/src/nbt/StringTag.h b/src/nbt/StringTag.h index 8967e58..a151201 100755 --- a/src/nbt/StringTag.h +++ b/src/nbt/StringTag.h @@ -1,62 +1,60 @@ -#ifndef COM_MOJANG_NBT__StringTag_H__ -#define COM_MOJANG_NBT__StringTag_H__ - -//package com.mojang.nbt; - -#include "Tag.h" -#include - -class StringTag: public Tag -{ - typedef Tag super; -public: - std::string data; - int len; - - StringTag(const std::string& name) - : super(name), - len(name.length()) - { - } - - StringTag(const std::string& name, const std::string& data) - : super(name), - data(data), - len(name.length()) - { - } - - void write(IDataOutput* dos) /*throws IOException*/ { - dos->writeString(data); - } - - void load(IDataInput* dis) /*throws IOException*/ { - data = dis->readString(); // just a tiny bit slower, but safer - } - - char getId() const { - return TAG_String; - } - - std::string toString() const { - std::stringstream ss; - ss << data; - return ss.str(); - } - - //@Override - Tag* copy() const { - return new StringTag(getName(), data); - } - - //@Override - bool equals(const Tag& rhs) const { - if (super::equals(rhs)) { - StringTag& o = (StringTag&) rhs; - return data == o.data; - } - return false; - } -}; - -#endif /*COM_MOJANG_NBT__StringTag_H__*/ +#pragma once + +//package com.mojang.nbt; + +#include "Tag.h" +#include + +class StringTag: public Tag +{ + typedef Tag super; +public: + std::string data; + int len; + + StringTag(const std::string& name) + : super(name), + len(name.length()) + { + } + + StringTag(const std::string& name, const std::string& data) + : super(name), + data(data), + len(name.length()) + { + } + + void write(IDataOutput* dos) /*throws IOException*/ { + dos->writeString(data); + } + + void load(IDataInput* dis) /*throws IOException*/ { + data = dis->readString(); // just a tiny bit slower, but safer + } + + char getId() const { + return TAG_String; + } + + std::string toString() const { + std::stringstream ss; + ss << data; + return ss.str(); + } + + //@Override + Tag* copy() const { + return new StringTag(getName(), data); + } + + //@Override + bool equals(const Tag& rhs) const { + if (super::equals(rhs)) { + StringTag& o = (StringTag&) rhs; + return data == o.data; + } + return false; + } +}; + diff --git a/src/nbt/Tag.h b/src/nbt/Tag.h index 5cfc3ff..052421f 100755 --- a/src/nbt/Tag.h +++ b/src/nbt/Tag.h @@ -1,65 +1,63 @@ -#ifndef COM_MOJANG_NBT__Tag_H__ -#define COM_MOJANG_NBT__Tag_H__ - -//package com.mojang.nbt; - -/* import java.io.* */ - -#include "../util/DataIO.h" - -#include - - -class Tag -{ -public: - virtual ~Tag() {} - virtual void deleteChildren() {} - - static const char TAG_End = 0; - static const char TAG_Byte = 1; - static const char TAG_Short = 2; - static const char TAG_Int = 3; - static const char TAG_Long = 4; - static const char TAG_Float = 5; - static const char TAG_Double = 6; - static const char TAG_Byte_Array= 7; - static const char TAG_String = 8; - static const char TAG_List = 9; - static const char TAG_Compound = 10; - - static const std::string NullString; - - virtual void write(IDataOutput* dos) = 0; ///*throws IOException*/; - virtual void load(IDataInput* dis) = 0; ///*throws IOException*/; - - virtual std::string toString() const = 0; - virtual char getId() const = 0; - - virtual bool equals(const Tag& rhs) const; - - virtual void print(PrintStream& out) const; - virtual void print(const std::string& prefix, PrintStream& out) const; - - virtual Tag* setName(const std::string& name); - virtual std::string getName() const; - - static Tag* readNamedTag(IDataInput* dis); - static void writeNamedTag(Tag* tag, IDataOutput* dos); - - static Tag* newTag(char type, const std::string& name); - - static std::string getTagName(char type); - - virtual Tag* copy() const = 0; - - mutable int errorState; - static const int TAGERR_OUT_OF_BOUNDS = 1; - static const int TAGERR_BAD_TYPE = 2; -protected: - Tag(const std::string& name); -private: - std::string name; -}; - -#endif /*COM_MOJANG_NBT__Tag_H__*/ +#pragma once + +//package com.mojang.nbt; + +/* import java.io.* */ + +#include "../util/DataIO.h" + +#include + + +class Tag +{ +public: + virtual ~Tag() {} + virtual void deleteChildren() {} + + static const char TAG_End = 0; + static const char TAG_Byte = 1; + static const char TAG_Short = 2; + static const char TAG_Int = 3; + static const char TAG_Long = 4; + static const char TAG_Float = 5; + static const char TAG_Double = 6; + static const char TAG_Byte_Array= 7; + static const char TAG_String = 8; + static const char TAG_List = 9; + static const char TAG_Compound = 10; + + static const std::string NullString; + + virtual void write(IDataOutput* dos) = 0; ///*throws IOException*/; + virtual void load(IDataInput* dis) = 0; ///*throws IOException*/; + + virtual std::string toString() const = 0; + virtual char getId() const = 0; + + virtual bool equals(const Tag& rhs) const; + + virtual void print(PrintStream& out) const; + virtual void print(const std::string& prefix, PrintStream& out) const; + + virtual Tag* setName(const std::string& name); + virtual std::string getName() const; + + static Tag* readNamedTag(IDataInput* dis); + static void writeNamedTag(Tag* tag, IDataOutput* dos); + + static Tag* newTag(char type, const std::string& name); + + static std::string getTagName(char type); + + virtual Tag* copy() const = 0; + + mutable int errorState; + static const int TAGERR_OUT_OF_BOUNDS = 1; + static const int TAGERR_BAD_TYPE = 2; +protected: + Tag(const std::string& name); +private: + std::string name; +}; + diff --git a/src/network/ClientSideNetworkHandler.h b/src/network/ClientSideNetworkHandler.h index 94dde78..8843aec 100755 --- a/src/network/ClientSideNetworkHandler.h +++ b/src/network/ClientSideNetworkHandler.h @@ -1,107 +1,105 @@ -#ifndef _MINECRAFT_NETWORK_CLIENTSIDENETWORKHANDLER_H_ -#define _MINECRAFT_NETWORK_CLIENTSIDENETWORKHANDLER_H_ - - -#include "NetEventCallback.h" -#include "../raknet/RakNetTypes.h" -#include "../world/level/LevelConstants.h" - -#include - -class MinecraftClient; -class Level; -class IRakNetInstance; - -struct SBufferedBlockUpdate -{ - int x, z; - unsigned char y; - unsigned char blockId; - unsigned char blockData; - bool setData; -}; -typedef std::vector BlockUpdateList; - -typedef struct IntPair { - int x, y; -} IntPair; - -class ClientSideNetworkHandler : public NetEventCallback -{ -public: - ClientSideNetworkHandler(MinecraftClient& minecraft, IRakNetInstance* raknetInstance); - virtual ~ClientSideNetworkHandler(); - - virtual void levelGenerated(Level* level); - - virtual void onConnect(const RakNet::RakNetGUID& hostGuid); - virtual void onUnableToConnect(); - virtual void onDisconnect(const RakNet::RakNetGUID& guid); - - virtual void handle(const RakNet::RakNetGUID& source, LoginStatusPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, StartGamePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, MessagePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, SetTimePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, AddItemEntityPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, AddPaintingPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, TakeItemEntityPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, AddEntityPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, AddMobPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, AddPlayerPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, RemoveEntityPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, RemovePlayerPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, MovePlayerPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, MoveEntityPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, UpdateBlockPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ExplodePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, LevelEventPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, TileEventPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ChunkDataPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, PlayerArmorEquipmentPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, InteractPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, SetEntityDataPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, SetEntityMotionPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, SetHealthPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, SetSpawnPositionPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, UseItemPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, HurtArmorPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, RespawnPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ContainerOpenPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ContainerClosePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ContainerSetContentPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ContainerSetDataPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, AdventureSettingsPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet); -private: - - void requestNextChunk(); - void arrangeRequestChunkOrder(); - - bool isChunkLoaded(int x, int z); - bool areAllChunksLoaded(); - void clearChunksLoaded(); -private: - - MinecraftClient& minecraft; - Level* level = nullptr; - IRakNetInstance* raknetInstance; - RakNet::RakPeerInterface* rakPeer; - - RakNet::RakNetGUID serverGuid; - - BlockUpdateList bufferedBlockUpdates; - int requestNextChunkPosition = 0; - - static const int NumRequestChunks = CHUNK_CACHE_WIDTH * CHUNK_CACHE_WIDTH; - - int requestNextChunkIndex = 0; - IntPair requestNextChunkIndexList[NumRequestChunks]; - bool chunksLoaded[NumRequestChunks]; -}; - -#endif +#pragma once + + +#include "NetEventCallback.h" +#include "../raknet/RakNetTypes.h" +#include "../world/level/LevelConstants.h" + +#include + +class MinecraftClient; +class Level; +class IRakNetInstance; + +struct SBufferedBlockUpdate +{ + int x, z; + unsigned char y; + unsigned char blockId; + unsigned char blockData; + bool setData; +}; +typedef std::vector BlockUpdateList; + +typedef struct IntPair { + int x, y; +} IntPair; + +class ClientSideNetworkHandler : public NetEventCallback +{ +public: + ClientSideNetworkHandler(MinecraftClient& minecraft, IRakNetInstance* raknetInstance); + virtual ~ClientSideNetworkHandler(); + + virtual void levelGenerated(Level* level); + + virtual void onConnect(const RakNet::RakNetGUID& hostGuid); + virtual void onUnableToConnect(); + virtual void onDisconnect(const RakNet::RakNetGUID& guid); + + virtual void handle(const RakNet::RakNetGUID& source, LoginStatusPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, StartGamePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, MessagePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SetTimePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, AddItemEntityPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, AddPaintingPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, TakeItemEntityPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, AddEntityPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, AddMobPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, AddPlayerPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, RemoveEntityPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, RemovePlayerPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, MovePlayerPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, MoveEntityPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, UpdateBlockPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ExplodePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, LevelEventPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, TileEventPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ChunkDataPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, PlayerArmorEquipmentPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, InteractPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SetEntityDataPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SetEntityMotionPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SetHealthPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SetSpawnPositionPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, UseItemPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, HurtArmorPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, RespawnPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ContainerOpenPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ContainerClosePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ContainerSetContentPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ContainerSetDataPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, AdventureSettingsPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet); +private: + + void requestNextChunk(); + void arrangeRequestChunkOrder(); + + bool isChunkLoaded(int x, int z); + bool areAllChunksLoaded(); + void clearChunksLoaded(); +private: + + MinecraftClient& minecraft; + Level* level = nullptr; + IRakNetInstance* raknetInstance; + RakNet::RakPeerInterface* rakPeer; + + RakNet::RakNetGUID serverGuid; + + BlockUpdateList bufferedBlockUpdates; + int requestNextChunkPosition = 0; + + static const int NumRequestChunks = CHUNK_CACHE_WIDTH * CHUNK_CACHE_WIDTH; + + int requestNextChunkIndex = 0; + IntPair requestNextChunkIndexList[NumRequestChunks]; + bool chunksLoaded[NumRequestChunks]; +}; + diff --git a/src/network/NATPunchHandler.h b/src/network/NATPunchHandler.h index 0246c0d..4f2ff05 100755 --- a/src/network/NATPunchHandler.h +++ b/src/network/NATPunchHandler.h @@ -1,24 +1,22 @@ -#ifndef _MINECRAFT_NETWORK_NATPUNCHHANDLER_H_ -#define _MINECRAFT_NETWORK_NATPUNCHHANDLER_H_ -#include "../raknet/TCPInterface.h" -#include "../raknet/RakString.h" -class NATPuchHandler { -public: - enum NATPuchHandlerStatus { - NATPuchInitilized = 0, - NATPuchFetchingServerList = 1, - NATPuchConnecting = 2, - NATPuchConnected = 3, - NATPuchDissconnected = 4 - }; - NATPuchHandler(); - ~NATPuchHandler(); - void initialize(); - void registerToGameList(const RakNet::RakString& serverName, int port); - void removeFromGameList(); - void close(); -private: - RakNet::TCPInterface *tcpInterface; -}; - -#endif /* _MINECRAFT_NETWORK_NATPUNCHHANDLER_H_ */ +#pragma once +#include "../raknet/TCPInterface.h" +#include "../raknet/RakString.h" +class NATPuchHandler { +public: + enum NATPuchHandlerStatus { + NATPuchInitilized = 0, + NATPuchFetchingServerList = 1, + NATPuchConnecting = 2, + NATPuchConnected = 3, + NATPuchDissconnected = 4 + }; + NATPuchHandler(); + ~NATPuchHandler(); + void initialize(); + void registerToGameList(const RakNet::RakString& serverName, int port); + void removeFromGameList(); + void close(); +private: + RakNet::TCPInterface *tcpInterface; +}; + diff --git a/src/network/NetEventCallback.h b/src/network/NetEventCallback.h index 53e5fa4..da9c5a5 100755 --- a/src/network/NetEventCallback.h +++ b/src/network/NetEventCallback.h @@ -1,134 +1,132 @@ -#ifndef _MINECRAFT_NETWORK_NETEVENTCALLBACK_H_ -#define _MINECRAFT_NETWORK_NETEVENTCALLBACK_H_ - -class AddItemEntityPacket; -class AddPaintingPacket; -class AdventureSettingsPacket; -class TakeItemEntityPacket; -class LoginPacket; -class ReadyPacket; -class LoginStatusPacket; -class MessagePacket; -class SetTimePacket; -class StartGamePacket; -class AddEntityPacket; -class AddMobPacket; -class AddPlayerPacket; -class RemovePlayerPacket; -class RemoveEntityPacket; -class MoveEntityPacket; -//class TeleportEntityPacket; -class MovePlayerPacket; -class PlaceBlockPacket; -class RemoveBlockPacket; -class UpdateBlockPacket; -class ExplodePacket; -class LevelEventPacket; -class TileEventPacket; -class EntityEventPacket; -class RequestChunkPacket; -class ChunkDataPacket; -class PlayerEquipmentPacket; -class PlayerArmorEquipmentPacket; -class InteractPacket; -class SetEntityDataPacket; -class SetEntityMotionPacket; -class SetHealthPacket; -class SetSpawnPositionPacket; -class SendInventoryPacket; -class DropItemPacket; -class AnimatePacket; -class UseItemPacket; -class PlayerActionPacket; -class HurtArmorPacket; -class RespawnPacket; -class ContainerAckPacket; -class ContainerOpenPacket; -class ContainerClosePacket; -class ContainerSetSlotPacket; -class ContainerSetDataPacket; -class ContainerSetContentPacket; -class ChatPacket; -class SignUpdatePacket; -class Minecraft; -class Level; - -#include "../world/level/tile/Tile.h" - -namespace RakNet -{ - struct RakNetGUID; -} - -class NetEventCallback -{ -public: - virtual void levelGenerated(Level* level) {} - virtual ~NetEventCallback() {} - - virtual void onConnect(const RakNet::RakNetGUID& hostGuid) {}; - virtual void onUnableToConnect() {}; - virtual void onNewClient(const RakNet::RakNetGUID& clientGuid) {}; - virtual void onDisconnect(const RakNet::RakNetGUID& guid) {}; - - virtual void handle(const RakNet::RakNetGUID& source, LoginPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ReadyPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, LoginStatusPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, SetTimePacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, MessagePacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, StartGamePacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, AddItemEntityPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, AddPaintingPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, TakeItemEntityPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, AddEntityPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, AddMobPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, AddPlayerPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, RemovePlayerPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, RemoveEntityPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, MoveEntityPacket* packet) {} - //virtual void handle(const RakNet::RakNetGUID& source, TeleportEntityPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, MovePlayerPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, PlaceBlockPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, RemoveBlockPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, UpdateBlockPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ExplodePacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, LevelEventPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, TileEventPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, RequestChunkPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ChunkDataPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, PlayerArmorEquipmentPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, SetEntityDataPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, SetEntityMotionPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, SetHealthPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, SetSpawnPositionPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, InteractPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, UseItemPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, PlayerActionPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, HurtArmorPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, SendInventoryPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, DropItemPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ContainerOpenPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ContainerClosePacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ContainerAckPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ContainerSetDataPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ContainerSetContentPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, AdventureSettingsPacket* packet) {} - virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet) {} - - // - // Common implementation for Client and Server - // - virtual void handle(const RakNet::RakNetGUID& source, RespawnPacket* packet) {} - virtual void handle(Level* level, const RakNet::RakNetGUID& source, RespawnPacket* packet); - - Player* findPlayer(Level* level, int entityId); - Player* findPlayer(Level* level, const RakNet::RakNetGUID* source); - Player* findPlayer(Level* level, int entityId, const RakNet::RakNetGUID* source); -}; - -#endif +#pragma once + +class AddItemEntityPacket; +class AddPaintingPacket; +class AdventureSettingsPacket; +class TakeItemEntityPacket; +class LoginPacket; +class ReadyPacket; +class LoginStatusPacket; +class MessagePacket; +class SetTimePacket; +class StartGamePacket; +class AddEntityPacket; +class AddMobPacket; +class AddPlayerPacket; +class RemovePlayerPacket; +class RemoveEntityPacket; +class MoveEntityPacket; +//class TeleportEntityPacket; +class MovePlayerPacket; +class PlaceBlockPacket; +class RemoveBlockPacket; +class UpdateBlockPacket; +class ExplodePacket; +class LevelEventPacket; +class TileEventPacket; +class EntityEventPacket; +class RequestChunkPacket; +class ChunkDataPacket; +class PlayerEquipmentPacket; +class PlayerArmorEquipmentPacket; +class InteractPacket; +class SetEntityDataPacket; +class SetEntityMotionPacket; +class SetHealthPacket; +class SetSpawnPositionPacket; +class SendInventoryPacket; +class DropItemPacket; +class AnimatePacket; +class UseItemPacket; +class PlayerActionPacket; +class HurtArmorPacket; +class RespawnPacket; +class ContainerAckPacket; +class ContainerOpenPacket; +class ContainerClosePacket; +class ContainerSetSlotPacket; +class ContainerSetDataPacket; +class ContainerSetContentPacket; +class ChatPacket; +class SignUpdatePacket; +class Minecraft; +class Level; + +#include "../world/level/tile/Tile.h" + +namespace RakNet +{ + struct RakNetGUID; +} + +class NetEventCallback +{ +public: + virtual void levelGenerated(Level* level) {} + virtual ~NetEventCallback() {} + + virtual void onConnect(const RakNet::RakNetGUID& hostGuid) {}; + virtual void onUnableToConnect() {}; + virtual void onNewClient(const RakNet::RakNetGUID& clientGuid) {}; + virtual void onDisconnect(const RakNet::RakNetGUID& guid) {}; + + virtual void handle(const RakNet::RakNetGUID& source, LoginPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ReadyPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, LoginStatusPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, SetTimePacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, MessagePacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, StartGamePacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, AddItemEntityPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, AddPaintingPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, TakeItemEntityPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, AddEntityPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, AddMobPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, AddPlayerPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, RemovePlayerPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, RemoveEntityPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, MoveEntityPacket* packet) {} + //virtual void handle(const RakNet::RakNetGUID& source, TeleportEntityPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, MovePlayerPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, PlaceBlockPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, RemoveBlockPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, UpdateBlockPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ExplodePacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, LevelEventPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, TileEventPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, RequestChunkPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ChunkDataPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, PlayerArmorEquipmentPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, SetEntityDataPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, SetEntityMotionPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, SetHealthPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, SetSpawnPositionPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, InteractPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, UseItemPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, PlayerActionPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, HurtArmorPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, SendInventoryPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, DropItemPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ContainerOpenPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ContainerClosePacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ContainerAckPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ContainerSetDataPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ContainerSetContentPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, AdventureSettingsPacket* packet) {} + virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet) {} + + // + // Common implementation for Client and Server + // + virtual void handle(const RakNet::RakNetGUID& source, RespawnPacket* packet) {} + virtual void handle(Level* level, const RakNet::RakNetGUID& source, RespawnPacket* packet); + + Player* findPlayer(Level* level, int entityId); + Player* findPlayer(Level* level, const RakNet::RakNetGUID* source); + Player* findPlayer(Level* level, int entityId, const RakNet::RakNetGUID* source); +}; + diff --git a/src/network/Packet.h b/src/network/Packet.h index e872219..5d417e2 100755 --- a/src/network/Packet.h +++ b/src/network/Packet.h @@ -1,173 +1,171 @@ -#ifndef _MINECRAFT_NETWORK_PACKET_H_ -#define _MINECRAFT_NETWORK_PACKET_H_ - -#include "NetEventCallback.h" - -#include "../raknet/MessageIdentifiers.h" -#include "../raknet/RakNetTypes.h" -#include "../raknet/BitStream.h" -#include "../raknet/PacketPriority.h" - -class LevelChunk; - - -enum MinecraftPacketIds -{ - PACKET_KEEPALIVE = 0, - - PACKET_LOGIN, - PACKET_LOGINSTATUS, - PACKET_READY, - - PACKET_MESSAGE, - PACKET_SETTIME, - - PACKET_STARTGAME, - - PACKET_ADDMOB, - PACKET_ADDPLAYER, - PACKET_REMOVEPLAYER, - PACKET_TELEPORTENTITY, - - PACKET_ADDENTITY, - PACKET_REMOVEENTITY, - PACKET_ADDITEMENTITY, - PACKET_TAKEITEMENTITY, - - PACKET_MOVEENTITY, - PACKET_MOVEENTITY_POS, - PACKET_MOVEENTITY_ROT, - PACKET_MOVEENTITY_POSROT, - PACKET_MOVEPLAYER, - - PACKET_PLACEBLOCK, - PACKET_REMOVEBLOCK, - PACKET_UPDATEBLOCK, - - PACKET_ADDPAINTING, - - PACKET_EXPLODE, - - PACKET_LEVELEVENT, - PACKET_TILEEVENT, - PACKET_ENTITYEVENT, - - PACKET_REQUESTCHUNK, - PACKET_CHUNKDATA, - - PACKET_PLAYEREQUIPMENT, - PACKET_PLAYERARMOREQUIPMENT, - PACKET_INTERACT, - PACKET_USEITEM, - PACKET_PLAYERACTION, - PACKET_UPDATEARMOR, - PACKET_HURTARMOR, - - PACKET_SETENTITYDATA, - PACKET_SETENTITYMOTION, - PACKET_SETHEALTH, - PACKET_SETSPAWNPOSITION, - - PACKET_ANIMATE, - PACKET_RESPAWN, - - PACKET_SENDINVENTORY, - PACKET_DROPITEM, - - PACKET_CONTAINEROPEN, - PACKET_CONTAINERCLOSE, - PACKET_CONTAINERSETSLOT, - PACKET_CONTAINERSETDATA, - PACKET_CONTAINERSETCONTENT, - PACKET_CONTAINERACK, - - PACKET_CHAT, - PACKET_SIGNUPDATE, - - PACKET_ADVENTURESETTINGS, -/* - PACKET_PRELOGIN, - PACKET_CHAT, - PACKET_SETEQUIPPEDITEM, - PACKET_SETSPAWNPOSITION, - - PACKET_PLAYERACTION, - PACKET_SETCARRIEDITEM, - PACKET_ENTITYACTIONATPOSITION, - PACKET_PLAYERCOMMAND, - - PACKET_ADDENTITY, - PACKET_ADDMOB, - PACKET_ADDPAINTING, - PACKET_PLAYERINPUT, - PACKET_SETENTITYMOTION, - PACKET_REMOVEENTITY, - - PACKET_MOVEENTITY, - PACKET_SETRIDING, - PACKET_ENTITYDATA, - - PACKET_CHUNKVISIBILITY, - PACKET_BLOCKREGIONUPDATE, - PACKET_CHUNKBLOCKUPDATE, - PACKET_BLOCKUPDATE, - PACKET_BLOCKEVENT, - - PACKET_GAMEEVENT, - PACKET_ADDGLOBALENTITY, - - PACKET_CONTAINEROPEN, - PACKET_CONTAINERCLOSE, - PACKET_CONTAINERCLICK, - PACKET_CONTAINERSETSLOT, - PACKET_CONTAINERSETCONTENT, - PACKET_CONTAINERSETDATA, - PACKET_CONTAINERACK, - - PACKET_SIGNUPDATE, - PACKET_AWARDSTAT, - - PACKET_DISCONNECT, - */ - - PACKET_END_ID -}; - - -const int NUM_PACKETS = PACKET_END_ID; - -class Packet -{ -public: - Packet(); - virtual ~Packet() {} - - virtual void write(RakNet::BitStream* bitStream) = 0; - virtual void read(RakNet::BitStream* bitStream) = 0; - - virtual void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) = 0; - - PacketPriority priority; - PacketReliability reliability; -}; - - -class MinecraftPackets -{ -public: - - static Packet* createPacket(int id); - -}; - -namespace PacketUtil { - signed char Rot_degreesToChar(float rot); - float Rot_charToDegrees(signed char rot); - void Rot_entityToChar(const Entity* e, signed char& yRot, signed char& xRot); - void Rot_charToEntity(Entity* e, signed char yRot, signed char xRot); - - void writeItemInstance(const ItemInstance& item, RakNet::BitStream* stream); - ItemInstance readItemInstance(RakNet::BitStream* stream); -} - -#endif +#pragma once + +#include "NetEventCallback.h" + +#include "../raknet/MessageIdentifiers.h" +#include "../raknet/RakNetTypes.h" +#include "../raknet/BitStream.h" +#include "../raknet/PacketPriority.h" + +class LevelChunk; + + +enum MinecraftPacketIds +{ + PACKET_KEEPALIVE = 0, + + PACKET_LOGIN, + PACKET_LOGINSTATUS, + PACKET_READY, + + PACKET_MESSAGE, + PACKET_SETTIME, + + PACKET_STARTGAME, + + PACKET_ADDMOB, + PACKET_ADDPLAYER, + PACKET_REMOVEPLAYER, + PACKET_TELEPORTENTITY, + + PACKET_ADDENTITY, + PACKET_REMOVEENTITY, + PACKET_ADDITEMENTITY, + PACKET_TAKEITEMENTITY, + + PACKET_MOVEENTITY, + PACKET_MOVEENTITY_POS, + PACKET_MOVEENTITY_ROT, + PACKET_MOVEENTITY_POSROT, + PACKET_MOVEPLAYER, + + PACKET_PLACEBLOCK, + PACKET_REMOVEBLOCK, + PACKET_UPDATEBLOCK, + + PACKET_ADDPAINTING, + + PACKET_EXPLODE, + + PACKET_LEVELEVENT, + PACKET_TILEEVENT, + PACKET_ENTITYEVENT, + + PACKET_REQUESTCHUNK, + PACKET_CHUNKDATA, + + PACKET_PLAYEREQUIPMENT, + PACKET_PLAYERARMOREQUIPMENT, + PACKET_INTERACT, + PACKET_USEITEM, + PACKET_PLAYERACTION, + PACKET_UPDATEARMOR, + PACKET_HURTARMOR, + + PACKET_SETENTITYDATA, + PACKET_SETENTITYMOTION, + PACKET_SETHEALTH, + PACKET_SETSPAWNPOSITION, + + PACKET_ANIMATE, + PACKET_RESPAWN, + + PACKET_SENDINVENTORY, + PACKET_DROPITEM, + + PACKET_CONTAINEROPEN, + PACKET_CONTAINERCLOSE, + PACKET_CONTAINERSETSLOT, + PACKET_CONTAINERSETDATA, + PACKET_CONTAINERSETCONTENT, + PACKET_CONTAINERACK, + + PACKET_CHAT, + PACKET_SIGNUPDATE, + + PACKET_ADVENTURESETTINGS, +/* + PACKET_PRELOGIN, + PACKET_CHAT, + PACKET_SETEQUIPPEDITEM, + PACKET_SETSPAWNPOSITION, + + PACKET_PLAYERACTION, + PACKET_SETCARRIEDITEM, + PACKET_ENTITYACTIONATPOSITION, + PACKET_PLAYERCOMMAND, + + PACKET_ADDENTITY, + PACKET_ADDMOB, + PACKET_ADDPAINTING, + PACKET_PLAYERINPUT, + PACKET_SETENTITYMOTION, + PACKET_REMOVEENTITY, + + PACKET_MOVEENTITY, + PACKET_SETRIDING, + PACKET_ENTITYDATA, + + PACKET_CHUNKVISIBILITY, + PACKET_BLOCKREGIONUPDATE, + PACKET_CHUNKBLOCKUPDATE, + PACKET_BLOCKUPDATE, + PACKET_BLOCKEVENT, + + PACKET_GAMEEVENT, + PACKET_ADDGLOBALENTITY, + + PACKET_CONTAINEROPEN, + PACKET_CONTAINERCLOSE, + PACKET_CONTAINERCLICK, + PACKET_CONTAINERSETSLOT, + PACKET_CONTAINERSETCONTENT, + PACKET_CONTAINERSETDATA, + PACKET_CONTAINERACK, + + PACKET_SIGNUPDATE, + PACKET_AWARDSTAT, + + PACKET_DISCONNECT, + */ + + PACKET_END_ID +}; + + +const int NUM_PACKETS = PACKET_END_ID; + +class Packet +{ +public: + Packet(); + virtual ~Packet() {} + + virtual void write(RakNet::BitStream* bitStream) = 0; + virtual void read(RakNet::BitStream* bitStream) = 0; + + virtual void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) = 0; + + PacketPriority priority; + PacketReliability reliability; +}; + + +class MinecraftPackets +{ +public: + + static Packet* createPacket(int id); + +}; + +namespace PacketUtil { + signed char Rot_degreesToChar(float rot); + float Rot_charToDegrees(signed char rot); + void Rot_entityToChar(const Entity* e, signed char& yRot, signed char& xRot); + void Rot_charToEntity(Entity* e, signed char yRot, signed char xRot); + + void writeItemInstance(const ItemInstance& item, RakNet::BitStream* stream); + ItemInstance readItemInstance(RakNet::BitStream* stream); +} + diff --git a/src/network/RakNetInstance.h b/src/network/RakNetInstance.h index d3e8571..bdacb3c 100755 --- a/src/network/RakNetInstance.h +++ b/src/network/RakNetInstance.h @@ -1,118 +1,116 @@ -#ifndef _MINECRAFT_NETWORK_RAKNETINSTANCE_H_ -#define _MINECRAFT_NETWORK_RAKNETINSTANCE_H_ - -#include -#include -#include "../raknet/RakNetTypes.h" -#include "../raknet/RakString.h" - -namespace RakNet -{ - class RakPeerInterface; -} - -class Packet; -class NetEventCallback; - -typedef struct PingedCompatibleServer -{ - RakNet::RakString name; - RakNet::SystemAddress address; - RakNet::TimeMS pingTime; - bool isSpecial; -} PingedCompatibleServer; -typedef std::vector ServerList; - -class IRakNetInstance -{ -public: - virtual ~IRakNetInstance() {} - - virtual bool host(const std::string& localName, int port, int maxConnections = 4) { return false; } - virtual bool connect(const char* host, int port) { return false; } - virtual void setIsLoggedIn(bool status) {} - - virtual void pingForHosts(int port) {} - virtual void stopPingForHosts() {} - virtual const ServerList& getServerList() { static ServerList l; return l; } - virtual void clearServerList() {} - - virtual void disconnect() {} - - virtual void announceServer(const std::string& localName) {} - - virtual RakNet::RakPeerInterface* getPeer() { return NULL; } - virtual bool isMyLocalGuid(const RakNet::RakNetGUID& guid) { return true; } - - virtual void runEvents(NetEventCallback* callback) {} - - virtual void send(Packet& packet) {} - virtual void send(const RakNet::RakNetGUID& guid, Packet& packet) {} - - // @attn: Those delete the packet - virtual void send(Packet* packet) {} - virtual void send(const RakNet::RakNetGUID& guid, Packet* packet) {} - - virtual bool isServer() { return true; } - virtual bool isProbablyBroken() { return false; } - virtual void resetIsBroken() {} -}; - -class RakNetInstance: public IRakNetInstance -{ -public: - - RakNetInstance(); - virtual ~RakNetInstance(); - - bool host(const std::string& localName, int port, int maxConnections = 4); - bool connect(const char* host, int port); - void setIsLoggedIn(bool status); - - void pingForHosts(int basePort); - void stopPingForHosts(); - const ServerList& getServerList(); - void clearServerList(); - - void disconnect(); - - void announceServer(const std::string& localName); - - RakNet::RakPeerInterface* getPeer(); - bool isMyLocalGuid(const RakNet::RakNetGUID& guid); - - void runEvents(NetEventCallback* callback); - - void send(Packet& packet); - void send(const RakNet::RakNetGUID& guid, Packet& packet); - - // @attn: Those delete the packet - void send(Packet* packet); - void send(const RakNet::RakNetGUID& guid, Packet* packet); - - bool isServer() { return _isServer; } - bool isProbablyBroken(); - void resetIsBroken(); - -#ifdef _DEBUG - const char* getPacketName(int packetId); -#else - const char* getPacketName(int packetId) { return ""; } -#endif - -private: - int handleUnconnectedPong(const RakNet::RakString& data, const RakNet::Packet*, const char* appid, bool insertAtBeginning); - - RakNet::RakPeerInterface* rakPeer; - RakNet::RakNetGUID serverGuid; - - ServerList availableServers; - bool isPingingForServers; - int pingPort; - RakNet::TimeMS lastPingTime; - - bool _isServer; - bool _isLoggedIn; -}; - -#endif /*_MINECRAFT_NETWORK_RAKNETINSTANCE_H_*/ +#pragma once + +#include +#include +#include "../raknet/RakNetTypes.h" +#include "../raknet/RakString.h" + +namespace RakNet +{ + class RakPeerInterface; +} + +class Packet; +class NetEventCallback; + +typedef struct PingedCompatibleServer +{ + RakNet::RakString name; + RakNet::SystemAddress address; + RakNet::TimeMS pingTime; + bool isSpecial; +} PingedCompatibleServer; +typedef std::vector ServerList; + +class IRakNetInstance +{ +public: + virtual ~IRakNetInstance() {} + + virtual bool host(const std::string& localName, int port, int maxConnections = 4) { return false; } + virtual bool connect(const char* host, int port) { return false; } + virtual void setIsLoggedIn(bool status) {} + + virtual void pingForHosts(int port) {} + virtual void stopPingForHosts() {} + virtual const ServerList& getServerList() { static ServerList l; return l; } + virtual void clearServerList() {} + + virtual void disconnect() {} + + virtual void announceServer(const std::string& localName) {} + + virtual RakNet::RakPeerInterface* getPeer() { return NULL; } + virtual bool isMyLocalGuid(const RakNet::RakNetGUID& guid) { return true; } + + virtual void runEvents(NetEventCallback* callback) {} + + virtual void send(Packet& packet) {} + virtual void send(const RakNet::RakNetGUID& guid, Packet& packet) {} + + // @attn: Those delete the packet + virtual void send(Packet* packet) {} + virtual void send(const RakNet::RakNetGUID& guid, Packet* packet) {} + + virtual bool isServer() { return true; } + virtual bool isProbablyBroken() { return false; } + virtual void resetIsBroken() {} +}; + +class RakNetInstance: public IRakNetInstance +{ +public: + + RakNetInstance(); + virtual ~RakNetInstance(); + + bool host(const std::string& localName, int port, int maxConnections = 4); + bool connect(const char* host, int port); + void setIsLoggedIn(bool status); + + void pingForHosts(int basePort); + void stopPingForHosts(); + const ServerList& getServerList(); + void clearServerList(); + + void disconnect(); + + void announceServer(const std::string& localName); + + RakNet::RakPeerInterface* getPeer(); + bool isMyLocalGuid(const RakNet::RakNetGUID& guid); + + void runEvents(NetEventCallback* callback); + + void send(Packet& packet); + void send(const RakNet::RakNetGUID& guid, Packet& packet); + + // @attn: Those delete the packet + void send(Packet* packet); + void send(const RakNet::RakNetGUID& guid, Packet* packet); + + bool isServer() { return _isServer; } + bool isProbablyBroken(); + void resetIsBroken(); + +#ifdef _DEBUG + const char* getPacketName(int packetId); +#else + const char* getPacketName(int packetId) { return ""; } +#endif + +private: + int handleUnconnectedPong(const RakNet::RakString& data, const RakNet::Packet*, const char* appid, bool insertAtBeginning); + + RakNet::RakPeerInterface* rakPeer; + RakNet::RakNetGUID serverGuid; + + ServerList availableServers; + bool isPingingForServers; + int pingPort; + RakNet::TimeMS lastPingTime; + + bool _isServer; + bool _isLoggedIn; +}; + diff --git a/src/network/ServerSideNetworkHandler.h b/src/network/ServerSideNetworkHandler.h index 51531cf..c098e2f 100755 --- a/src/network/ServerSideNetworkHandler.h +++ b/src/network/ServerSideNetworkHandler.h @@ -1,84 +1,82 @@ -#ifndef _MINECRAFT_NETWORK_SERVERSIDENETWORKHANDLER_H_ -#define _MINECRAFT_NETWORK_SERVERSIDENETWORKHANDLER_H_ - - -#include "NetEventCallback.h" -#include "../raknet/RakNetTypes.h" -#include "../world/level/LevelListener.h" -#include - -class Minecraft; -class Level; -class IRakNetInstance; -class Packet; -class Player; - -class ServerSideNetworkHandler : public NetEventCallback, public LevelListener -{ -public: - ServerSideNetworkHandler(Minecraft* minecraft, IRakNetInstance* raknetInstance); - virtual ~ServerSideNetworkHandler(); - - virtual void levelGenerated(Level* level); - - virtual void tileChanged(int x, int y, int z); - virtual void tileBrightnessChanged(int x, int y, int z) { /* do nothing */ } - virtual Packet* getAddPacketFromEntity(Entity* entity); - virtual void entityAdded(Entity* e); - virtual void entityRemoved(Entity* e); - virtual void levelEvent(Player* source, int type, int x, int y, int z, int data); - virtual void tileEvent(int x, int y, int z, int b0, int b1); - - virtual void onNewClient(const RakNet::RakNetGUID& clientGuid); - virtual void onDisconnect(const RakNet::RakNetGUID& guid); - - void onReady_ClientGeneration(const RakNet::RakNetGUID& source); - void onReady_RequestedChunks(const RakNet::RakNetGUID& source); - - virtual void handle(const RakNet::RakNetGUID& source, LoginPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ReadyPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, MovePlayerPacket* packet); - //virtual void handle(const RakNet::RakNetGUID& source, PlaceBlockPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, RemoveBlockPacket* packet); - //virtual void handle(const RakNet::RakNetGUID& source, ExplodePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, RequestChunkPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, PlayerArmorEquipmentPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, SetHealthPacket* packet); - //virtual void handle(const RakNet::RakNetGUID& source, TeleportEntityPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, InteractPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, UseItemPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, PlayerActionPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, RespawnPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, SendInventoryPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, DropItemPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ContainerClosePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet); - virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet); - - bool allowsIncomingConnections() { return _allowIncoming; } - void allowIncomingConnections(bool doAllow); - - Player* popPendingPlayer(const RakNet::RakNetGUID& source); - - void displayGameMessage(const std::string& message); -private: - /** - * @brief Send packet to all players - */ - void redistributePacket(Packet* packet, const RakNet::RakNetGUID& fromPlayer); - Player* getPlayer(const RakNet::RakNetGUID& source); - - Minecraft* minecraft; - Level* level; - IRakNetInstance* raknetInstance; - RakNet::RakPeerInterface* rakPeer; - - std::vector _pendingPlayers; - bool _allowIncoming; -}; - -#endif +#pragma once + + +#include "NetEventCallback.h" +#include "../raknet/RakNetTypes.h" +#include "../world/level/LevelListener.h" +#include + +class Minecraft; +class Level; +class IRakNetInstance; +class Packet; +class Player; + +class ServerSideNetworkHandler : public NetEventCallback, public LevelListener +{ +public: + ServerSideNetworkHandler(Minecraft* minecraft, IRakNetInstance* raknetInstance); + virtual ~ServerSideNetworkHandler(); + + virtual void levelGenerated(Level* level); + + virtual void tileChanged(int x, int y, int z); + virtual void tileBrightnessChanged(int x, int y, int z) { /* do nothing */ } + virtual Packet* getAddPacketFromEntity(Entity* entity); + virtual void entityAdded(Entity* e); + virtual void entityRemoved(Entity* e); + virtual void levelEvent(Player* source, int type, int x, int y, int z, int data); + virtual void tileEvent(int x, int y, int z, int b0, int b1); + + virtual void onNewClient(const RakNet::RakNetGUID& clientGuid); + virtual void onDisconnect(const RakNet::RakNetGUID& guid); + + void onReady_ClientGeneration(const RakNet::RakNetGUID& source); + void onReady_RequestedChunks(const RakNet::RakNetGUID& source); + + virtual void handle(const RakNet::RakNetGUID& source, LoginPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ReadyPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, MovePlayerPacket* packet); + //virtual void handle(const RakNet::RakNetGUID& source, PlaceBlockPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, RemoveBlockPacket* packet); + //virtual void handle(const RakNet::RakNetGUID& source, ExplodePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, RequestChunkPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, PlayerEquipmentPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, PlayerArmorEquipmentPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SetHealthPacket* packet); + //virtual void handle(const RakNet::RakNetGUID& source, TeleportEntityPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, InteractPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, AnimatePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, UseItemPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, EntityEventPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, PlayerActionPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, RespawnPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SendInventoryPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, DropItemPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ContainerSetSlotPacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ContainerClosePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, SignUpdatePacket* packet); + virtual void handle(const RakNet::RakNetGUID& source, ChatPacket* packet); + + bool allowsIncomingConnections() { return _allowIncoming; } + void allowIncomingConnections(bool doAllow); + + Player* popPendingPlayer(const RakNet::RakNetGUID& source); + + void displayGameMessage(const std::string& message); +private: + /** + * @brief Send packet to all players + */ + void redistributePacket(Packet* packet, const RakNet::RakNetGUID& fromPlayer); + Player* getPlayer(const RakNet::RakNetGUID& source); + + Minecraft* minecraft; + Level* level; + IRakNetInstance* raknetInstance; + RakNet::RakPeerInterface* rakPeer; + + std::vector _pendingPlayers; + bool _allowIncoming; +}; + diff --git a/src/network/command/CommandServer.h b/src/network/command/CommandServer.h index e2aa4bb..78e0517 100755 --- a/src/network/command/CommandServer.h +++ b/src/network/command/CommandServer.h @@ -1,5 +1,4 @@ -#ifndef COMMANDSERVER_H__ -#define COMMANDSERVER_H__ +#pragma once #include #include @@ -74,4 +73,3 @@ private: static const std::string Fail; }; -#endif /*COMMANDSERVER_H__*/ diff --git a/src/network/packet/AddEntityPacket.h b/src/network/packet/AddEntityPacket.h index 9c31089..6ce436f 100755 --- a/src/network/packet/AddEntityPacket.h +++ b/src/network/packet/AddEntityPacket.h @@ -1,93 +1,91 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__AddEntityPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__AddEntityPacket_H__ - -#include "../Packet.h" -#include "../../world/entity/Entity.h" - -class AddEntityPacket : public Packet -{ -public: - AddEntityPacket() {} - - AddEntityPacket(const Entity* e, int data = 0) - : entityId(e->entityId), - type(e->getEntityTypeId()), - x(e->x), - y(e->y), - z(e->z), - _data(data) - { - if (hasMovementData()) { - xd = e->xd; - yd = e->yd; - zd = e->zd; - } - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDENTITY)); - bitStream->Write(entityId); - unsigned char bType = (unsigned char)type; - bitStream->Write(bType); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(_data); - - if (hasMovementData()) { - const float M = 3.9f; - short xa = (short)(8000.0f * Mth::clamp(xd, -M, M)); - short ya = (short)(8000.0f * Mth::clamp(yd, -M, M)); - short za = (short)(8000.0f * Mth::clamp(zd, -M, M)); - - bitStream->Write(xa); - bitStream->Write(ya); - bitStream->Write(za); - } - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - unsigned char bType; - bitStream->Read(bType); - type = bType; - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - bitStream->Read(_data); - - if (hasMovementData()) { - short xa, ya, za; - bitStream->Read(xa); - bitStream->Read(ya); - bitStream->Read(za); - xd = xa / 8000.0f; - yd = ya / 8000.0f; - zd = za / 8000.0f; - } - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (AddEntityPacket*)this); - } - - bool hasMovementData() { - return _data > 0; - } - int data() { - return _data; - } - -public: - int entityId; - float x, y, z; - float xd, yd, zd; - int type; -private: - int _data; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__AddEntityPacket_H__*/ +#pragma once + +#include "../Packet.h" +#include "../../world/entity/Entity.h" + +class AddEntityPacket : public Packet +{ +public: + AddEntityPacket() {} + + AddEntityPacket(const Entity* e, int data = 0) + : entityId(e->entityId), + type(e->getEntityTypeId()), + x(e->x), + y(e->y), + z(e->z), + _data(data) + { + if (hasMovementData()) { + xd = e->xd; + yd = e->yd; + zd = e->zd; + } + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDENTITY)); + bitStream->Write(entityId); + unsigned char bType = (unsigned char)type; + bitStream->Write(bType); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(_data); + + if (hasMovementData()) { + const float M = 3.9f; + short xa = (short)(8000.0f * Mth::clamp(xd, -M, M)); + short ya = (short)(8000.0f * Mth::clamp(yd, -M, M)); + short za = (short)(8000.0f * Mth::clamp(zd, -M, M)); + + bitStream->Write(xa); + bitStream->Write(ya); + bitStream->Write(za); + } + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + unsigned char bType; + bitStream->Read(bType); + type = bType; + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + bitStream->Read(_data); + + if (hasMovementData()) { + short xa, ya, za; + bitStream->Read(xa); + bitStream->Read(ya); + bitStream->Read(za); + xd = xa / 8000.0f; + yd = ya / 8000.0f; + zd = za / 8000.0f; + } + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (AddEntityPacket*)this); + } + + bool hasMovementData() { + return _data > 0; + } + int data() { + return _data; + } + +public: + int entityId; + float x, y, z; + float xd, yd, zd; + int type; +private: + int _data; +}; + diff --git a/src/network/packet/AddItemEntityPacket.h b/src/network/packet/AddItemEntityPacket.h index 5e2564a..eb2a0b9 100755 --- a/src/network/packet/AddItemEntityPacket.h +++ b/src/network/packet/AddItemEntityPacket.h @@ -1,78 +1,76 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__AddItemEntityPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__AddItemEntityPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" -#include "../../world/entity/item/ItemEntity.h" -#include "../../world/item/ItemInstance.h" -#include "../../util/Mth.h" - -class AddItemEntityPacket: public Packet { -public: - AddItemEntityPacket() { - } - - AddItemEntityPacket(const ItemEntity* itemEntity) - : id(itemEntity->entityId), - itemId(itemEntity->item.id), - itemCount(itemEntity->item.count), - auxValue(itemEntity->item.getAuxValue()), - x(itemEntity->x), - y(itemEntity->y), - z(itemEntity->z), - _xa((signed char) (itemEntity->xd * 128.0)), - _ya((signed char) (itemEntity->yd * 128.0)), - _za((signed char) (itemEntity->zd * 128.0)) - { - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(id); - bitStream->Read(itemId); - bitStream->Read(itemCount); - bitStream->Read(auxValue); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - bitStream->Read(_xa); - bitStream->Read(_ya); - bitStream->Read(_za); - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDITEMENTITY)); - bitStream->Write(id); - bitStream->Write(itemId); - bitStream->Write(itemCount); - bitStream->Write(auxValue); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(_xa); - bitStream->Write(_ya); - bitStream->Write(_za); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (AddItemEntityPacket*)this); - } - - float xa() { return (float)(_xa) / 128.0f; } - float ya() { return (float)(_ya) / 128.0f; } - float za() { return (float)(_za) / 128.0f; } - - int id; - float x, y, z; - - short itemId; - short auxValue; - unsigned char itemCount; -private: - signed char _xa, _ya, _za; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__AddItemEntityPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" +#include "../../world/entity/item/ItemEntity.h" +#include "../../world/item/ItemInstance.h" +#include "../../util/Mth.h" + +class AddItemEntityPacket: public Packet { +public: + AddItemEntityPacket() { + } + + AddItemEntityPacket(const ItemEntity* itemEntity) + : id(itemEntity->entityId), + itemId(itemEntity->item.id), + itemCount(itemEntity->item.count), + auxValue(itemEntity->item.getAuxValue()), + x(itemEntity->x), + y(itemEntity->y), + z(itemEntity->z), + _xa((signed char) (itemEntity->xd * 128.0)), + _ya((signed char) (itemEntity->yd * 128.0)), + _za((signed char) (itemEntity->zd * 128.0)) + { + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(id); + bitStream->Read(itemId); + bitStream->Read(itemCount); + bitStream->Read(auxValue); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + bitStream->Read(_xa); + bitStream->Read(_ya); + bitStream->Read(_za); + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDITEMENTITY)); + bitStream->Write(id); + bitStream->Write(itemId); + bitStream->Write(itemCount); + bitStream->Write(auxValue); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(_xa); + bitStream->Write(_ya); + bitStream->Write(_za); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (AddItemEntityPacket*)this); + } + + float xa() { return (float)(_xa) / 128.0f; } + float ya() { return (float)(_ya) / 128.0f; } + float za() { return (float)(_za) / 128.0f; } + + int id; + float x, y, z; + + short itemId; + short auxValue; + unsigned char itemCount; +private: + signed char _xa, _ya, _za; +}; + diff --git a/src/network/packet/AddMobPacket.h b/src/network/packet/AddMobPacket.h index 6ca63be..ceb3157 100755 --- a/src/network/packet/AddMobPacket.h +++ b/src/network/packet/AddMobPacket.h @@ -1,78 +1,76 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__AddMobPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__AddMobPacket_H__ - -#include "../Packet.h" -#include "../../world/entity/Mob.h" -#include "../../util/RakDataIO.h" - -class AddMobPacket : public Packet -{ -public: - AddMobPacket() - : _entityData(NULL) - { - } - - ~AddMobPacket() { - for (unsigned int i = 0; i < unpack.size(); ++i) - delete unpack[i]; - } - - AddMobPacket(const Mob* mob) - : entityId(mob->entityId), - type(mob->getEntityTypeId()), - x(mob->x), - y(mob->y), - z(mob->z), - xRot(mob->xRot), - yRot(mob->yRot), - _entityData(mob->getEntityData()) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDMOB)); - bitStream->Write(entityId); - bitStream->Write(type); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(PacketUtil::Rot_degreesToChar(yRot)); - bitStream->Write(PacketUtil::Rot_degreesToChar(xRot)); - RakDataOutput dos(*bitStream); - _entityData->packAll(&dos); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(type); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - char rx, ry; - bitStream->Read(ry); - bitStream->Read(rx); - RakDataInput dis(*bitStream); - unpack = SynchedEntityData::unpack(&dis); - yRot = PacketUtil::Rot_degreesToChar(ry); - xRot = PacketUtil::Rot_charToDegrees(rx); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (AddMobPacket*)this); - } - -public: - int entityId; - int type; - float x, y, z; - float xRot, yRot; - SynchedEntityData::DataList unpack; -private: - const SynchedEntityData* _entityData; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__AddMobPacket_H__*/ +#pragma once + +#include "../Packet.h" +#include "../../world/entity/Mob.h" +#include "../../util/RakDataIO.h" + +class AddMobPacket : public Packet +{ +public: + AddMobPacket() + : _entityData(NULL) + { + } + + ~AddMobPacket() { + for (unsigned int i = 0; i < unpack.size(); ++i) + delete unpack[i]; + } + + AddMobPacket(const Mob* mob) + : entityId(mob->entityId), + type(mob->getEntityTypeId()), + x(mob->x), + y(mob->y), + z(mob->z), + xRot(mob->xRot), + yRot(mob->yRot), + _entityData(mob->getEntityData()) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDMOB)); + bitStream->Write(entityId); + bitStream->Write(type); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(PacketUtil::Rot_degreesToChar(yRot)); + bitStream->Write(PacketUtil::Rot_degreesToChar(xRot)); + RakDataOutput dos(*bitStream); + _entityData->packAll(&dos); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(type); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + char rx, ry; + bitStream->Read(ry); + bitStream->Read(rx); + RakDataInput dis(*bitStream); + unpack = SynchedEntityData::unpack(&dis); + yRot = PacketUtil::Rot_degreesToChar(ry); + xRot = PacketUtil::Rot_charToDegrees(rx); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (AddMobPacket*)this); + } + +public: + int entityId; + int type; + float x, y, z; + float xRot, yRot; + SynchedEntityData::DataList unpack; +private: + const SynchedEntityData* _entityData; +}; + diff --git a/src/network/packet/AddPaintingPacket.h b/src/network/packet/AddPaintingPacket.h index c842c8d..aaf9c9f 100755 --- a/src/network/packet/AddPaintingPacket.h +++ b/src/network/packet/AddPaintingPacket.h @@ -1,48 +1,46 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__AddPaintingPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__AddPaintingPacket_H__ -#include "../Packet.h" -#include "../../world/entity/Painting.h" -class AddPaintingPacket : public Packet { -public: - AddPaintingPacket() : entityId(0), xTile(0), yTile(0), zTile(0), dir(-1) { - - } - AddPaintingPacket(Painting* painting) { - entityId = painting->entityId; - xTile = painting->xTile; - yTile = painting->yTile; - zTile = painting->zTile; - dir = painting->dir; - motive = painting->motive->name; - } - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDPAINTING)); - bitStream->Write(entityId); - bitStream->Write(xTile); - bitStream->Write(yTile); - bitStream->Write(zTile); - bitStream->Write(dir); - RakNet::RakString rakMotive(motive.c_str()); - bitStream->Write(rakMotive); - } - void read(RakNet::BitStream* bitStream) { - bitStream->Read(entityId); - bitStream->Read(xTile); - bitStream->Read(yTile); - bitStream->Read(zTile); - bitStream->Read(dir); - RakNet::RakString rakMotive; - bitStream->Read(rakMotive); - motive = std::string(rakMotive.C_String()); - } - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (AddPaintingPacket*)this); - } -public: - int entityId; - int xTile, yTile, zTile; - int dir; - std::string motive; -}; - -#endif /* NET_MINECRAFT_NETWORK_PACKET__AddPaintingPacket_H__ */ \ No newline at end of file +#pragma once +#include "../Packet.h" +#include "../../world/entity/Painting.h" +class AddPaintingPacket : public Packet { +public: + AddPaintingPacket() : entityId(0), xTile(0), yTile(0), zTile(0), dir(-1) { + + } + AddPaintingPacket(Painting* painting) { + entityId = painting->entityId; + xTile = painting->xTile; + yTile = painting->yTile; + zTile = painting->zTile; + dir = painting->dir; + motive = painting->motive->name; + } + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDPAINTING)); + bitStream->Write(entityId); + bitStream->Write(xTile); + bitStream->Write(yTile); + bitStream->Write(zTile); + bitStream->Write(dir); + RakNet::RakString rakMotive(motive.c_str()); + bitStream->Write(rakMotive); + } + void read(RakNet::BitStream* bitStream) { + bitStream->Read(entityId); + bitStream->Read(xTile); + bitStream->Read(yTile); + bitStream->Read(zTile); + bitStream->Read(dir); + RakNet::RakString rakMotive; + bitStream->Read(rakMotive); + motive = std::string(rakMotive.C_String()); + } + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (AddPaintingPacket*)this); + } +public: + int entityId; + int xTile, yTile, zTile; + int dir; + std::string motive; +}; + diff --git a/src/network/packet/AddPlayerPacket.h b/src/network/packet/AddPlayerPacket.h index c7ec3aa..5d432ec 100755 --- a/src/network/packet/AddPlayerPacket.h +++ b/src/network/packet/AddPlayerPacket.h @@ -1,93 +1,91 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__AddPlayerPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__AddPlayerPacket_H__ - -#include "../Packet.h" -#include "../../world/entity/player/Player.h" -#include "../../world/entity/player/Inventory.h" - -class AddPlayerPacket : public Packet -{ -public: - AddPlayerPacket() - : _entityData(NULL) - {} - - AddPlayerPacket(const Player* p) - : owner(p->owner), - name(p->name.c_str()), - entityId(p->entityId), - x(p->x), - y(p->y - p->heightOffset), - z(p->z), - xRot(p->xRot), - yRot(p->yRot), - carriedItemId(0), - carriedItemAuxValue(0), - _entityData(p->getEntityData()) - { - if (ItemInstance* item = p->inventory->getSelected()) { - carriedItemId = item->id; - carriedItemAuxValue = item->getAuxValue(); - } - } - - ~AddPlayerPacket() { - for (unsigned int i = 0; i < unpack.size(); ++i) - delete unpack[i]; - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDPLAYER)); - - bitStream->Write(owner); - bitStream->Write(name); - bitStream->Write(entityId); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(PacketUtil::Rot_degreesToChar(yRot)); - bitStream->Write(PacketUtil::Rot_degreesToChar(xRot)); - bitStream->Write(carriedItemId); - bitStream->Write(carriedItemAuxValue); - RakDataOutput dos(*bitStream); - _entityData->packAll(&dos); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(owner); - bitStream->Read(name); - bitStream->Read(entityId); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - char rx, ry; - bitStream->Read(ry); - bitStream->Read(rx); - bitStream->Read(carriedItemId); - bitStream->Read(carriedItemAuxValue); - RakDataInput dis(*bitStream); - unpack = SynchedEntityData::unpack(&dis); - yRot = PacketUtil::Rot_degreesToChar(ry); - xRot = PacketUtil::Rot_charToDegrees(rx); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (AddPlayerPacket*)this); - } - - RakNet::RakNetGUID owner; - RakNet::RakString name; - int entityId; - float x, y, z; - float xRot, yRot; - short carriedItemId; - short carriedItemAuxValue; - SynchedEntityData::DataList unpack; -private: - const SynchedEntityData* _entityData; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__AddPlayerPacket_H__*/ +#pragma once + +#include "../Packet.h" +#include "../../world/entity/player/Player.h" +#include "../../world/entity/player/Inventory.h" + +class AddPlayerPacket : public Packet +{ +public: + AddPlayerPacket() + : _entityData(NULL) + {} + + AddPlayerPacket(const Player* p) + : owner(p->owner), + name(p->name.c_str()), + entityId(p->entityId), + x(p->x), + y(p->y - p->heightOffset), + z(p->z), + xRot(p->xRot), + yRot(p->yRot), + carriedItemId(0), + carriedItemAuxValue(0), + _entityData(p->getEntityData()) + { + if (ItemInstance* item = p->inventory->getSelected()) { + carriedItemId = item->id; + carriedItemAuxValue = item->getAuxValue(); + } + } + + ~AddPlayerPacket() { + for (unsigned int i = 0; i < unpack.size(); ++i) + delete unpack[i]; + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADDPLAYER)); + + bitStream->Write(owner); + bitStream->Write(name); + bitStream->Write(entityId); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(PacketUtil::Rot_degreesToChar(yRot)); + bitStream->Write(PacketUtil::Rot_degreesToChar(xRot)); + bitStream->Write(carriedItemId); + bitStream->Write(carriedItemAuxValue); + RakDataOutput dos(*bitStream); + _entityData->packAll(&dos); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(owner); + bitStream->Read(name); + bitStream->Read(entityId); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + char rx, ry; + bitStream->Read(ry); + bitStream->Read(rx); + bitStream->Read(carriedItemId); + bitStream->Read(carriedItemAuxValue); + RakDataInput dis(*bitStream); + unpack = SynchedEntityData::unpack(&dis); + yRot = PacketUtil::Rot_degreesToChar(ry); + xRot = PacketUtil::Rot_charToDegrees(rx); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (AddPlayerPacket*)this); + } + + RakNet::RakNetGUID owner; + RakNet::RakString name; + int entityId; + float x, y, z; + float xRot, yRot; + short carriedItemId; + short carriedItemAuxValue; + SynchedEntityData::DataList unpack; +private: + const SynchedEntityData* _entityData; +}; + diff --git a/src/network/packet/AdventureSettingsPacket.h b/src/network/packet/AdventureSettingsPacket.h index 3ad0865..bf78b11 100755 --- a/src/network/packet/AdventureSettingsPacket.h +++ b/src/network/packet/AdventureSettingsPacket.h @@ -1,67 +1,65 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__AdventureSettingsPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__AdventureSettingsPacket_H__ - -#include "../Packet.h" -#include "../../world/level/Level.h" - -class AdventureSettingsPacket: public Packet -{ -public: - enum Flags { - WorldImmutable = 1, - NoPvP = 2, - NoPvM = 4, - NoMvP = 8, - StaticTime = 16, - ShowNameTags = 32, - }; - - AdventureSettingsPacket() {} - - AdventureSettingsPacket(const AdventureSettings& settings) - : flags(0) - { - set(WorldImmutable, settings.immutableWorld); - set(NoPvP, settings.noPvP); - set(NoPvM, settings.noPvM); - set(NoMvP, settings.noMvP); - set(StaticTime, !settings.doTickTime); - set(ShowNameTags, settings.showNameTags); - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADVENTURESETTINGS)); - bitStream->Write(flags); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(flags); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (AdventureSettingsPacket*)this); - } - - void fillIn( AdventureSettings& adventureSettings ) const - { - adventureSettings.immutableWorld= isSet(WorldImmutable); - adventureSettings.noPvP = isSet(NoPvP); - adventureSettings.noPvM = isSet(NoPvM); - adventureSettings.noMvP = isSet(NoMvP); - adventureSettings.doTickTime = !isSet(StaticTime); - adventureSettings.showNameTags = isSet(ShowNameTags); - } - - unsigned int flags; - - void set(Flags flag, bool status) { status? set(flag) : clear(flag); } - void set(Flags flag) { flags |= flag; } - void toggle(Flags flag){ flags ^= flag; } - void clear(Flags flag) { flags &= ~flag; } - bool isSet(Flags flag) const { return (flags & flag) != 0; } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__AdventureSettingsPacket_H__*/ +#pragma once + +#include "../Packet.h" +#include "../../world/level/Level.h" + +class AdventureSettingsPacket: public Packet +{ +public: + enum Flags { + WorldImmutable = 1, + NoPvP = 2, + NoPvM = 4, + NoMvP = 8, + StaticTime = 16, + ShowNameTags = 32, + }; + + AdventureSettingsPacket() {} + + AdventureSettingsPacket(const AdventureSettings& settings) + : flags(0) + { + set(WorldImmutable, settings.immutableWorld); + set(NoPvP, settings.noPvP); + set(NoPvM, settings.noPvM); + set(NoMvP, settings.noMvP); + set(StaticTime, !settings.doTickTime); + set(ShowNameTags, settings.showNameTags); + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ADVENTURESETTINGS)); + bitStream->Write(flags); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(flags); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (AdventureSettingsPacket*)this); + } + + void fillIn( AdventureSettings& adventureSettings ) const + { + adventureSettings.immutableWorld= isSet(WorldImmutable); + adventureSettings.noPvP = isSet(NoPvP); + adventureSettings.noPvM = isSet(NoPvM); + adventureSettings.noMvP = isSet(NoMvP); + adventureSettings.doTickTime = !isSet(StaticTime); + adventureSettings.showNameTags = isSet(ShowNameTags); + } + + unsigned int flags; + + void set(Flags flag, bool status) { status? set(flag) : clear(flag); } + void set(Flags flag) { flags |= flag; } + void toggle(Flags flag){ flags ^= flag; } + void clear(Flags flag) { flags &= ~flag; } + bool isSet(Flags flag) const { return (flags & flag) != 0; } +}; + diff --git a/src/network/packet/AnimatePacket.h b/src/network/packet/AnimatePacket.h index 81d3bfc..61f974f 100755 --- a/src/network/packet/AnimatePacket.h +++ b/src/network/packet/AnimatePacket.h @@ -1,46 +1,44 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__AnimatePacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__AnimatePacket_H__ - -#include "../Packet.h" - -class AnimatePacket: public Packet -{ -public: - static const int Swing = 1; - static const int WAKE_UP = 3; - - int entityId; - char action; - - AnimatePacket() {} - - AnimatePacket(int action, int entityId) - : action(action), - entityId(entityId) - {} - AnimatePacket(int action, Entity* e) - : action(action), - entityId(e->entityId) - {} - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ANIMATE)); - - bitStream->Write(action); - bitStream->Write(entityId); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(action); - bitStream->Read(entityId); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (AnimatePacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__AnimatePacket_H__*/ +#pragma once + +#include "../Packet.h" + +class AnimatePacket: public Packet +{ +public: + static const int Swing = 1; + static const int WAKE_UP = 3; + + int entityId; + char action; + + AnimatePacket() {} + + AnimatePacket(int action, int entityId) + : action(action), + entityId(entityId) + {} + AnimatePacket(int action, Entity* e) + : action(action), + entityId(e->entityId) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ANIMATE)); + + bitStream->Write(action); + bitStream->Write(entityId); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(action); + bitStream->Read(entityId); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (AnimatePacket*)this); + } +}; + diff --git a/src/network/packet/ChatPacket.h b/src/network/packet/ChatPacket.h index 5d992a8..0e4b2a7 100755 --- a/src/network/packet/ChatPacket.h +++ b/src/network/packet/ChatPacket.h @@ -1,41 +1,39 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ChatPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ChatPacket_H__ -#include "../Packet.h" -#include "../..//world/entity/player/Player.h" - -class ChatPacket: public Packet -{ -public: - static const int MAX_CHAT_LENGTH = 100; - static const int MAX_LENGTH = MAX_CHAT_LENGTH + Player::MAX_NAME_LENGTH; - ChatPacket() { - } - - ChatPacket(std::string message, bool isSystem = true) { - if(message.length() > MAX_LENGTH) { - message = message.substr(0, MAX_LENGTH); - } - this->message = message; - this->isSystem = isSystem; - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CHAT)); - bitStream->Write(message.c_str()); - } - - void read(RakNet::BitStream* bitStream) { - char buff[MAX_LENGTH + 30]; - bitStream->Read(buff); - message = buff; - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (ChatPacket*)this); - } - - std::string message; - bool isSystem; -}; - -#endif /* NET_MINECRAFT_NETWORK_PACKET__ChatPacket_H__ */ \ No newline at end of file +#pragma once +#include "../Packet.h" +#include "../..//world/entity/player/Player.h" + +class ChatPacket: public Packet +{ +public: + static const int MAX_CHAT_LENGTH = 100; + static const int MAX_LENGTH = MAX_CHAT_LENGTH + Player::MAX_NAME_LENGTH; + ChatPacket() { + } + + ChatPacket(std::string message, bool isSystem = true) { + if(message.length() > MAX_LENGTH) { + message = message.substr(0, MAX_LENGTH); + } + this->message = message; + this->isSystem = isSystem; + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CHAT)); + bitStream->Write(message.c_str()); + } + + void read(RakNet::BitStream* bitStream) { + char buff[MAX_LENGTH + 30]; + bitStream->Read(buff); + message = buff; + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (ChatPacket*)this); + } + + std::string message; + bool isSystem; +}; + diff --git a/src/network/packet/ChunkDataPacket.h b/src/network/packet/ChunkDataPacket.h index 51f1719..af4cdef 100755 --- a/src/network/packet/ChunkDataPacket.h +++ b/src/network/packet/ChunkDataPacket.h @@ -1,77 +1,75 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ChunkDataPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ChunkDataPacket_H__ - -#include "../Packet.h" -#include "../../world/level/chunk/LevelChunk.h" - -class ChunkDataPacket : public Packet -{ -public: - - int x, z; - RakNet::BitStream chunkData; - LevelChunk* chunk; - - ChunkDataPacket() - { - } - - ChunkDataPacket(int x, int z, LevelChunk* chunk) - : x(x), - z(z), - chunk(chunk) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CHUNKDATA)); - - bitStream->Write(x); - bitStream->Write(z); - - unsigned char* blockIds = chunk->getBlockData(); - DataLayer& blockData = chunk->data; - - const int setSize = LEVEL_HEIGHT / 8; - const int setShift = 4; // power of LEVEL_HEIGHT / 8 - - chunkData.Reset(); - for (int i = 0; i < CHUNK_COLUMNS; i++) - { - unsigned char updateBits = chunk->updateMap[i]; - chunkData.Write(updateBits); - - if (updateBits > 0) - { - int colDataPosition = (i % CHUNK_WIDTH) << 11 | (i / CHUNK_WIDTH) << 7; - - for (int set = 0; set < 8; set++) - { - if ((updateBits & (1 << set)) != 0) - { - chunkData.Write((const char*)(&blockIds[colDataPosition + (set << setShift)]), setSize); - // block data is only 4 bits per block - chunkData.Write((const char*)(&blockData.data[(colDataPosition + (set << setShift)) >> 1]), setSize >> 1); - } - } - } - } - - bitStream->Write(chunkData); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(x); - bitStream->Read(z); - bitStream->Read(chunkData); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (ChunkDataPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__ChunkDataPacket_H__*/ +#pragma once + +#include "../Packet.h" +#include "../../world/level/chunk/LevelChunk.h" + +class ChunkDataPacket : public Packet +{ +public: + + int x, z; + RakNet::BitStream chunkData; + LevelChunk* chunk; + + ChunkDataPacket() + { + } + + ChunkDataPacket(int x, int z, LevelChunk* chunk) + : x(x), + z(z), + chunk(chunk) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CHUNKDATA)); + + bitStream->Write(x); + bitStream->Write(z); + + unsigned char* blockIds = chunk->getBlockData(); + DataLayer& blockData = chunk->data; + + const int setSize = LEVEL_HEIGHT / 8; + const int setShift = 4; // power of LEVEL_HEIGHT / 8 + + chunkData.Reset(); + for (int i = 0; i < CHUNK_COLUMNS; i++) + { + unsigned char updateBits = chunk->updateMap[i]; + chunkData.Write(updateBits); + + if (updateBits > 0) + { + int colDataPosition = (i % CHUNK_WIDTH) << 11 | (i / CHUNK_WIDTH) << 7; + + for (int set = 0; set < 8; set++) + { + if ((updateBits & (1 << set)) != 0) + { + chunkData.Write((const char*)(&blockIds[colDataPosition + (set << setShift)]), setSize); + // block data is only 4 bits per block + chunkData.Write((const char*)(&blockData.data[(colDataPosition + (set << setShift)) >> 1]), setSize >> 1); + } + } + } + } + + bitStream->Write(chunkData); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(x); + bitStream->Read(z); + bitStream->Read(chunkData); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (ChunkDataPacket*)this); + } +}; + diff --git a/src/network/packet/ContainerAckPacket.h b/src/network/packet/ContainerAckPacket.h index 7d60de6..317ac8f 100755 --- a/src/network/packet/ContainerAckPacket.h +++ b/src/network/packet/ContainerAckPacket.h @@ -1,43 +1,41 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ContainerAckPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ContainerAckPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -class ContainerAckPacket: public Packet -{ -public: - ContainerAckPacket() { - } - - ContainerAckPacket(int containerId, short uid, bool accepted) - : containerId(containerId), - uid(uid), - accepted(accepted) - { - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERACK)); - bitStream->Write(containerId); - bitStream->Write(uid); - bitStream->Write(accepted); - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(containerId); - bitStream->Read(uid); - bitStream->Read(accepted); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (ContainerAckPacket*)this); - } - - short uid; - unsigned char containerId; - bool accepted; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__ContainerAckPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +class ContainerAckPacket: public Packet +{ +public: + ContainerAckPacket() { + } + + ContainerAckPacket(int containerId, short uid, bool accepted) + : containerId(containerId), + uid(uid), + accepted(accepted) + { + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERACK)); + bitStream->Write(containerId); + bitStream->Write(uid); + bitStream->Write(accepted); + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(containerId); + bitStream->Read(uid); + bitStream->Read(accepted); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (ContainerAckPacket*)this); + } + + short uid; + unsigned char containerId; + bool accepted; +}; + diff --git a/src/network/packet/ContainerClosePacket.h b/src/network/packet/ContainerClosePacket.h index cdfe865..3a77f88 100755 --- a/src/network/packet/ContainerClosePacket.h +++ b/src/network/packet/ContainerClosePacket.h @@ -1,35 +1,33 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ContainerClosePacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ContainerClosePacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -class ContainerClosePacket: public Packet -{ -public: - ContainerClosePacket() { - } - - ContainerClosePacket(int containerId) - : containerId(containerId) - { - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(containerId); - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERCLOSE)); - bitStream->Write(containerId); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (ContainerClosePacket*)this); - } - - unsigned char containerId; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__ContainerClosePacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +class ContainerClosePacket: public Packet +{ +public: + ContainerClosePacket() { + } + + ContainerClosePacket(int containerId) + : containerId(containerId) + { + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(containerId); + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERCLOSE)); + bitStream->Write(containerId); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (ContainerClosePacket*)this); + } + + unsigned char containerId; +}; + diff --git a/src/network/packet/ContainerOpenPacket.h b/src/network/packet/ContainerOpenPacket.h index 1009a37..de1dc26 100755 --- a/src/network/packet/ContainerOpenPacket.h +++ b/src/network/packet/ContainerOpenPacket.h @@ -1,47 +1,45 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ContainerOpenPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ContainerOpenPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -class ContainerOpenPacket: public Packet -{ -public: - ContainerOpenPacket() { - } - - ContainerOpenPacket(int containerId, int type, const std::string& title, int size) - : containerId(containerId), - type(type), - title(title.c_str()), - size(size) - { - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINEROPEN)); - bitStream->Write(containerId); - bitStream->Write(type); - bitStream->Write(size); - bitStream->Write(title); - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(containerId); - bitStream->Read(type); - bitStream->Read(size); - bitStream->Read(title); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (ContainerOpenPacket*)this); - } - - RakNet::RakString title; - unsigned char containerId; - unsigned char type; - unsigned char size; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__ContainerOpenPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +class ContainerOpenPacket: public Packet +{ +public: + ContainerOpenPacket() { + } + + ContainerOpenPacket(int containerId, int type, const std::string& title, int size) + : containerId(containerId), + type(type), + title(title.c_str()), + size(size) + { + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINEROPEN)); + bitStream->Write(containerId); + bitStream->Write(type); + bitStream->Write(size); + bitStream->Write(title); + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(containerId); + bitStream->Read(type); + bitStream->Read(size); + bitStream->Read(title); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (ContainerOpenPacket*)this); + } + + RakNet::RakString title; + unsigned char containerId; + unsigned char type; + unsigned char size; +}; + diff --git a/src/network/packet/ContainerSetContentPacket.h b/src/network/packet/ContainerSetContentPacket.h index 76dd26b..a5b3c78 100755 --- a/src/network/packet/ContainerSetContentPacket.h +++ b/src/network/packet/ContainerSetContentPacket.h @@ -1,44 +1,42 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ContainerSetContentPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ContainerSetContentPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -class ContainerSetContentPacket: public Packet -{ -public: - ContainerSetContentPacket() { - } - - ContainerSetContentPacket(int containerId, const std::vector& newItems) - : containerId(containerId), - items(newItems.begin(), newItems.end()) - { - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERSETCONTENT)); - bitStream->Write(containerId); - bitStream->Write((short)items.size()); - for (unsigned int i = 0; i < items.size(); ++i) - PacketUtil::writeItemInstance(items[i], bitStream); - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(containerId); - short numItems; - bitStream->Read(numItems); - for (int i = 0; i < numItems; ++i) - items.push_back( PacketUtil::readItemInstance(bitStream) ); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (ContainerSetContentPacket*)this); - } - - unsigned char containerId; - std::vector items; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__ContainerSetContentPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +class ContainerSetContentPacket: public Packet +{ +public: + ContainerSetContentPacket() { + } + + ContainerSetContentPacket(int containerId, const std::vector& newItems) + : containerId(containerId), + items(newItems.begin(), newItems.end()) + { + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERSETCONTENT)); + bitStream->Write(containerId); + bitStream->Write((short)items.size()); + for (unsigned int i = 0; i < items.size(); ++i) + PacketUtil::writeItemInstance(items[i], bitStream); + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(containerId); + short numItems; + bitStream->Read(numItems); + for (int i = 0; i < numItems; ++i) + items.push_back( PacketUtil::readItemInstance(bitStream) ); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (ContainerSetContentPacket*)this); + } + + unsigned char containerId; + std::vector items; +}; + diff --git a/src/network/packet/ContainerSetDataPacket.h b/src/network/packet/ContainerSetDataPacket.h index d85b28d..1f7803a 100755 --- a/src/network/packet/ContainerSetDataPacket.h +++ b/src/network/packet/ContainerSetDataPacket.h @@ -1,43 +1,41 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ContainerSetDataPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ContainerSetDataPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -class ContainerSetDataPacket: public Packet -{ -public: - ContainerSetDataPacket() { - } - - ContainerSetDataPacket(int containerId, int id, int value) - : containerId(containerId), - id(id), - value(value) - { - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERSETDATA)); - bitStream->Write(containerId); - bitStream->Write(id); - bitStream->Write(value); - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(containerId); - bitStream->Read(id); - bitStream->Read(value); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (ContainerSetDataPacket*)this); - } - - short id; - short value; - unsigned char containerId; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__ContainerSetDataPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +class ContainerSetDataPacket: public Packet +{ +public: + ContainerSetDataPacket() { + } + + ContainerSetDataPacket(int containerId, int id, int value) + : containerId(containerId), + id(id), + value(value) + { + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERSETDATA)); + bitStream->Write(containerId); + bitStream->Write(id); + bitStream->Write(value); + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(containerId); + bitStream->Read(id); + bitStream->Read(value); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (ContainerSetDataPacket*)this); + } + + short id; + short value; + unsigned char containerId; +}; + diff --git a/src/network/packet/ContainerSetSlotPacket.h b/src/network/packet/ContainerSetSlotPacket.h index fd4c73e..419eccb 100755 --- a/src/network/packet/ContainerSetSlotPacket.h +++ b/src/network/packet/ContainerSetSlotPacket.h @@ -1,64 +1,62 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ContainerSetSlotPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ContainerSetSlotPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" -#include "../../world/item/ItemInstance.h" - -// Note: This can be seen as "ContainerWantSetSlotPacket" when sent from -// client to server. Currently, the client handles side-effects relating -// to it's own inventory, regardless of the success of the operation. -class ContainerSetSlotPacket: public Packet -{ -public: - static const char SETTYPE_SET = 0; - static const char SETTYPE_ADD = 1; - //static const int SETTYPE_SUB = 2; - static const char SETTYPE_TAKE = 5; - - ContainerSetSlotPacket() { - } - - //@todo: pointer parameter? - ContainerSetSlotPacket(int containerId, int slot, const ItemInstance& item) - : containerId(containerId), - slot(slot), - item(item), - setType(SETTYPE_SET) - //item(item? *item : ItemInstance()) - { - } - ContainerSetSlotPacket(char setType, int containerId, int slot, const ItemInstance& item) - : setType(setType), - containerId(containerId), - slot(slot), - item(item) - //item(item? *item : ItemInstance()) - { - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERSETSLOT)); - bitStream->Write(containerId); - bitStream->Write(slot); - PacketUtil::writeItemInstance(item, bitStream); - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(containerId); - bitStream->Read(slot); - item = PacketUtil::readItemInstance(bitStream); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (ContainerSetSlotPacket*)this); - } - - unsigned char setType; - unsigned char containerId; - short slot; - ItemInstance item; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__ContainerSetSlotPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" +#include "../../world/item/ItemInstance.h" + +// Note: This can be seen as "ContainerWantSetSlotPacket" when sent from +// client to server. Currently, the client handles side-effects relating +// to it's own inventory, regardless of the success of the operation. +class ContainerSetSlotPacket: public Packet +{ +public: + static const char SETTYPE_SET = 0; + static const char SETTYPE_ADD = 1; + //static const int SETTYPE_SUB = 2; + static const char SETTYPE_TAKE = 5; + + ContainerSetSlotPacket() { + } + + //@todo: pointer parameter? + ContainerSetSlotPacket(int containerId, int slot, const ItemInstance& item) + : containerId(containerId), + slot(slot), + item(item), + setType(SETTYPE_SET) + //item(item? *item : ItemInstance()) + { + } + ContainerSetSlotPacket(char setType, int containerId, int slot, const ItemInstance& item) + : setType(setType), + containerId(containerId), + slot(slot), + item(item) + //item(item? *item : ItemInstance()) + { + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_CONTAINERSETSLOT)); + bitStream->Write(containerId); + bitStream->Write(slot); + PacketUtil::writeItemInstance(item, bitStream); + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(containerId); + bitStream->Read(slot); + item = PacketUtil::readItemInstance(bitStream); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (ContainerSetSlotPacket*)this); + } + + unsigned char setType; + unsigned char containerId; + short slot; + ItemInstance item; +}; + diff --git a/src/network/packet/DropItemPacket.h b/src/network/packet/DropItemPacket.h index 9084efa..893c938 100755 --- a/src/network/packet/DropItemPacket.h +++ b/src/network/packet/DropItemPacket.h @@ -1,45 +1,43 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__DropItemPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__DropItemPacket_H__ - -#include "../Packet.h" - -class DropItemPacket: public Packet -{ -public: - DropItemPacket() - { - } - - DropItemPacket(int entityId, const ItemInstance& item) - : entityId(entityId), - item(item), - dropType(0) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_DROPITEM)); - bitStream->Write(entityId); - bitStream->Write(dropType); - PacketUtil::writeItemInstance(item, bitStream); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(dropType); - item = PacketUtil::readItemInstance(bitStream); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (DropItemPacket*)this); - } - - int entityId; - unsigned char dropType; - ItemInstance item; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__DropItemPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class DropItemPacket: public Packet +{ +public: + DropItemPacket() + { + } + + DropItemPacket(int entityId, const ItemInstance& item) + : entityId(entityId), + item(item), + dropType(0) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_DROPITEM)); + bitStream->Write(entityId); + bitStream->Write(dropType); + PacketUtil::writeItemInstance(item, bitStream); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(dropType); + item = PacketUtil::readItemInstance(bitStream); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (DropItemPacket*)this); + } + + int entityId; + unsigned char dropType; + ItemInstance item; +}; + diff --git a/src/network/packet/EntityEventPacket.h b/src/network/packet/EntityEventPacket.h index bc2759c..97a9042 100755 --- a/src/network/packet/EntityEventPacket.h +++ b/src/network/packet/EntityEventPacket.h @@ -1,40 +1,38 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__EntityEventPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__EntityEventPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -class EntityEventPacket: public Packet { -public: - EntityEventPacket() {} - - EntityEventPacket(int entityId, char eventId) - : entityId(entityId), - eventId(eventId) - {} - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ENTITYEVENT)); - bitStream->Write(entityId); - bitStream->Write(eventId); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(eventId); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (EntityEventPacket*)this); - } - - int entityId; - unsigned char eventId; - -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__EntityEventPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +class EntityEventPacket: public Packet { +public: + EntityEventPacket() {} + + EntityEventPacket(int entityId, char eventId) + : entityId(entityId), + eventId(eventId) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_ENTITYEVENT)); + bitStream->Write(entityId); + bitStream->Write(eventId); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(eventId); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (EntityEventPacket*)this); + } + + int entityId; + unsigned char eventId; + +}; + diff --git a/src/network/packet/ExplodePacket.h b/src/network/packet/ExplodePacket.h index 9cd9adc..94c9427 100755 --- a/src/network/packet/ExplodePacket.h +++ b/src/network/packet/ExplodePacket.h @@ -1,76 +1,74 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ExplodePacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ExplodePacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" -#include "../../world/level/Explosion.h" - -class ExplodePacket: public Packet -{ -public: - float x, y, z; - float r; - std::vector toBlow; - - ExplodePacket() {} - - ExplodePacket(float x, float y, float z, float r, const TilePosSet& tiles) - : x(x), - y(y), - z(z), - r(r), - toBlow(tiles.begin(), tiles.end()) - {} - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_EXPLODE)); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(r); - int xp = (int)x; - int yp = (int)y; - int zp = (int)z; - - int count = (int)toBlow.size(); - bitStream->Write(count); - for (int i = 0; i < count; ++i) { - const TilePos& tp = toBlow[i]; - bitStream->Write((signed char)(tp.x - xp)); - bitStream->Write((signed char)(tp.y - yp)); - bitStream->Write((signed char)(tp.z - zp)); - } - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - bitStream->Read(r); - int xp = (int)x; - int yp = (int)y; - int zp = (int)z; - - // Write the tileset for the exploded tiles - int count; - bitStream->Read(count); - toBlow.reserve(count); - for (int i = 0; i < count; ++i) { - signed char xx,yy,zz; - bitStream->Read(xx); - bitStream->Read(yy); - bitStream->Read(zz); - toBlow.push_back( TilePos(xp + xx, yp + yy, zp + zz) ); - } - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (ExplodePacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__ExplodePacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" +#include "../../world/level/Explosion.h" + +class ExplodePacket: public Packet +{ +public: + float x, y, z; + float r; + std::vector toBlow; + + ExplodePacket() {} + + ExplodePacket(float x, float y, float z, float r, const TilePosSet& tiles) + : x(x), + y(y), + z(z), + r(r), + toBlow(tiles.begin(), tiles.end()) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_EXPLODE)); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(r); + int xp = (int)x; + int yp = (int)y; + int zp = (int)z; + + int count = (int)toBlow.size(); + bitStream->Write(count); + for (int i = 0; i < count; ++i) { + const TilePos& tp = toBlow[i]; + bitStream->Write((signed char)(tp.x - xp)); + bitStream->Write((signed char)(tp.y - yp)); + bitStream->Write((signed char)(tp.z - zp)); + } + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + bitStream->Read(r); + int xp = (int)x; + int yp = (int)y; + int zp = (int)z; + + // Write the tileset for the exploded tiles + int count; + bitStream->Read(count); + toBlow.reserve(count); + for (int i = 0; i < count; ++i) { + signed char xx,yy,zz; + bitStream->Read(xx); + bitStream->Read(yy); + bitStream->Read(zz); + toBlow.push_back( TilePos(xp + xx, yp + yy, zp + zz) ); + } + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (ExplodePacket*)this); + } +}; + diff --git a/src/network/packet/HurtArmorPacket.h b/src/network/packet/HurtArmorPacket.h index 5088905..3ae1c67 100755 --- a/src/network/packet/HurtArmorPacket.h +++ b/src/network/packet/HurtArmorPacket.h @@ -1,32 +1,30 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__HurtArmorPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__HurtArmorPacket_H__ - -#include "../Packet.h" - -class HurtArmorPacket: public Packet -{ -public: - HurtArmorPacket() {} - - HurtArmorPacket(int dmg) - : dmg(dmg) - {} - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_HURTARMOR)); - - bitStream->Write(dmg); - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(dmg); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (HurtArmorPacket*)this); - } - - signed char dmg; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__HurtArmorPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class HurtArmorPacket: public Packet +{ +public: + HurtArmorPacket() {} + + HurtArmorPacket(int dmg) + : dmg(dmg) + {} + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_HURTARMOR)); + + bitStream->Write(dmg); + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(dmg); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (HurtArmorPacket*)this); + } + + signed char dmg; +}; + diff --git a/src/network/packet/InteractPacket.h b/src/network/packet/InteractPacket.h index 9daf160..bd73959 100755 --- a/src/network/packet/InteractPacket.h +++ b/src/network/packet/InteractPacket.h @@ -1,47 +1,45 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__InteractPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__InteractPacket_H__ - -#include "../Packet.h" - -class InteractPacket : public Packet -{ -public: - static const int Interact = 1; - static const int Attack = 2; - - char action; - int sourceId; - int targetId; - - InteractPacket() { - } - - InteractPacket(char action, int sourceId, int targetId) - : action(action), - sourceId(sourceId), - targetId(targetId) - {} - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_INTERACT)); - - bitStream->Write(action); - bitStream->Write(sourceId); - bitStream->Write(targetId); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(action); - bitStream->Read(sourceId); - bitStream->Read(targetId); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (InteractPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__InteractPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class InteractPacket : public Packet +{ +public: + static const int Interact = 1; + static const int Attack = 2; + + char action; + int sourceId; + int targetId; + + InteractPacket() { + } + + InteractPacket(char action, int sourceId, int targetId) + : action(action), + sourceId(sourceId), + targetId(targetId) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_INTERACT)); + + bitStream->Write(action); + bitStream->Write(sourceId); + bitStream->Write(targetId); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(action); + bitStream->Read(sourceId); + bitStream->Read(targetId); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (InteractPacket*)this); + } +}; + diff --git a/src/network/packet/LevelEventPacket.h b/src/network/packet/LevelEventPacket.h index 2cb5741..e9516f7 100755 --- a/src/network/packet/LevelEventPacket.h +++ b/src/network/packet/LevelEventPacket.h @@ -1,49 +1,47 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__LevelEventPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__LevelEventPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -class LevelEventPacket: public Packet { -public: - LevelEventPacket() {} - - LevelEventPacket(int eventId, int x, int y, int z, int data) - : eventId(eventId), - x(x), - y(y), - z(z), - data(data) - {} - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_LEVELEVENT)); - bitStream->Write(eventId); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(data); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(eventId); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - bitStream->Read(data); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (LevelEventPacket*)this); - } - - short eventId; - short x, y, z; - int data; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__LevelEventPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +class LevelEventPacket: public Packet { +public: + LevelEventPacket() {} + + LevelEventPacket(int eventId, int x, int y, int z, int data) + : eventId(eventId), + x(x), + y(y), + z(z), + data(data) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_LEVELEVENT)); + bitStream->Write(eventId); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(data); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(eventId); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + bitStream->Read(data); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (LevelEventPacket*)this); + } + + short eventId; + short x, y, z; + int data; +}; + diff --git a/src/network/packet/LoginPacket.h b/src/network/packet/LoginPacket.h index b44a44a..0f25bc5 100755 --- a/src/network/packet/LoginPacket.h +++ b/src/network/packet/LoginPacket.h @@ -1,51 +1,49 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__LoginPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__LoginPacket_H__ - -#include "../Packet.h" - -class LoginPacket : public Packet -{ -public: - RakNet::RakString clientName; - int clientNetworkVersion; - int clientNetworkLowestSupportedVersion; - - LoginPacket() - : clientNetworkVersion(-1), - clientNetworkLowestSupportedVersion(-1) - { - } - - LoginPacket(const RakNet::RakString& clientName, int clientVersion) - : clientName(clientName), - clientNetworkVersion(clientVersion), - clientNetworkLowestSupportedVersion(clientVersion) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_LOGIN)); - bitStream->Write(clientName); - bitStream->Write(clientNetworkVersion); - bitStream->Write(clientNetworkLowestSupportedVersion); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(clientName); - // First versions didn't send the client version - //LOGI("unread: %d\n", bitStream->GetNumberOfUnreadBits()); - if (bitStream->GetNumberOfUnreadBits() > 0) { - bitStream->Read(clientNetworkVersion); - bitStream->Read(clientNetworkLowestSupportedVersion); - } - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (LoginPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__LoginPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class LoginPacket : public Packet +{ +public: + RakNet::RakString clientName; + int clientNetworkVersion; + int clientNetworkLowestSupportedVersion; + + LoginPacket() + : clientNetworkVersion(-1), + clientNetworkLowestSupportedVersion(-1) + { + } + + LoginPacket(const RakNet::RakString& clientName, int clientVersion) + : clientName(clientName), + clientNetworkVersion(clientVersion), + clientNetworkLowestSupportedVersion(clientVersion) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_LOGIN)); + bitStream->Write(clientName); + bitStream->Write(clientNetworkVersion); + bitStream->Write(clientNetworkLowestSupportedVersion); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(clientName); + // First versions didn't send the client version + //LOGI("unread: %d\n", bitStream->GetNumberOfUnreadBits()); + if (bitStream->GetNumberOfUnreadBits() > 0) { + bitStream->Read(clientNetworkVersion); + bitStream->Read(clientNetworkLowestSupportedVersion); + } + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (LoginPacket*)this); + } +}; + diff --git a/src/network/packet/LoginStatusPacket.h b/src/network/packet/LoginStatusPacket.h index b194f8f..070b38c 100755 --- a/src/network/packet/LoginStatusPacket.h +++ b/src/network/packet/LoginStatusPacket.h @@ -1,40 +1,38 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__LoginStatusPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__LoginStatusPacket_H__ - -#include "../Packet.h" - -namespace LoginStatus { - const int Success = 0; - const int Failed_ClientOld = 1; - const int Failed_ServerOld = 2; -} - -class LoginStatusPacket : public Packet { -public: - LoginStatusPacket() - { - } - LoginStatusPacket(int status) - : status(status) - {} - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_LOGINSTATUS)); - bitStream->Write(status); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(status); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (LoginStatusPacket*)this); - } - - int status; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__LoginStatusPacket_H__*/ +#pragma once + +#include "../Packet.h" + +namespace LoginStatus { + const int Success = 0; + const int Failed_ClientOld = 1; + const int Failed_ServerOld = 2; +} + +class LoginStatusPacket : public Packet { +public: + LoginStatusPacket() + { + } + LoginStatusPacket(int status) + : status(status) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_LOGINSTATUS)); + bitStream->Write(status); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(status); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (LoginStatusPacket*)this); + } + + int status; +}; + diff --git a/src/network/packet/MessagePacket.h b/src/network/packet/MessagePacket.h index 49a274e..7a4eeb4 100755 --- a/src/network/packet/MessagePacket.h +++ b/src/network/packet/MessagePacket.h @@ -1,39 +1,37 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__MessagePacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__MessagePacket_H__ - -#include "../Packet.h" - -class MessagePacket : public Packet -{ -public: - - RakNet::RakString message; - - MessagePacket() - { - } - - MessagePacket(const RakNet::RakString& message) - : message(message) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_MESSAGE)); - - bitStream->Write(message); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(message); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (MessagePacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__MessagePacket_H__*/ +#pragma once + +#include "../Packet.h" + +class MessagePacket : public Packet +{ +public: + + RakNet::RakString message; + + MessagePacket() + { + } + + MessagePacket(const RakNet::RakString& message) + : message(message) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_MESSAGE)); + + bitStream->Write(message); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(message); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (MessagePacket*)this); + } +}; + diff --git a/src/network/packet/MoveEntityPacket.h b/src/network/packet/MoveEntityPacket.h index 7a619f2..11cf706 100755 --- a/src/network/packet/MoveEntityPacket.h +++ b/src/network/packet/MoveEntityPacket.h @@ -1,78 +1,76 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__MoveEntityPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__MoveEntityPacket_H__ - -#include "../Packet.h" - -class MoveEntityPacket: public Packet -{ -public: - MoveEntityPacket() - : hasRot(false) - {} - - // PACKET_MOVEENTITY is unknown and undefined (and not used) - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_MOVEENTITY)); - } - - void read(RakNet::BitStream* bitStream) {}; - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (MoveEntityPacket*)this); - } - - int entityId; - float x, y, z; - float xRot; - float yRot; - bool hasRot; -}; - -class MoveEntityPacket_PosRot: public MoveEntityPacket -{ - typedef MoveEntityPacket super; -public: - MoveEntityPacket_PosRot() { - hasRot = true; - } - - //MoveEntityPacket_PosRot(int entityId, float x, float y, float z, float yRot, float xRot) { - // set(entityId, x, y, z, yRot, xRot); - //} - - MoveEntityPacket_PosRot(const Entity* e) { - set(e->entityId, e->x, e->y - e->heightOffset, e->z, e->yRot, e->xRot); - } - - void set(int entityId, float x, float y, float z, float yRot, float xRot) { - this->entityId = entityId; - this->x = x; - this->y = y; - this->z = z; - this->xRot = xRot; - this->yRot = yRot; - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_MOVEENTITY_POSROT)); - - bitStream->Write(entityId); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(yRot); - bitStream->Write(xRot); - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(entityId); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - bitStream->Read(yRot); - bitStream->Read(xRot); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__MoveEntityPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class MoveEntityPacket: public Packet +{ +public: + MoveEntityPacket() + : hasRot(false) + {} + + // PACKET_MOVEENTITY is unknown and undefined (and not used) + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_MOVEENTITY)); + } + + void read(RakNet::BitStream* bitStream) {}; + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (MoveEntityPacket*)this); + } + + int entityId; + float x, y, z; + float xRot; + float yRot; + bool hasRot; +}; + +class MoveEntityPacket_PosRot: public MoveEntityPacket +{ + typedef MoveEntityPacket super; +public: + MoveEntityPacket_PosRot() { + hasRot = true; + } + + //MoveEntityPacket_PosRot(int entityId, float x, float y, float z, float yRot, float xRot) { + // set(entityId, x, y, z, yRot, xRot); + //} + + MoveEntityPacket_PosRot(const Entity* e) { + set(e->entityId, e->x, e->y - e->heightOffset, e->z, e->yRot, e->xRot); + } + + void set(int entityId, float x, float y, float z, float yRot, float xRot) { + this->entityId = entityId; + this->x = x; + this->y = y; + this->z = z; + this->xRot = xRot; + this->yRot = yRot; + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_MOVEENTITY_POSROT)); + + bitStream->Write(entityId); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(yRot); + bitStream->Write(xRot); + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(entityId); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + bitStream->Read(yRot); + bitStream->Read(xRot); + } +}; + diff --git a/src/network/packet/MovePlayerPacket.h b/src/network/packet/MovePlayerPacket.h index 8555432..0252cbc 100755 --- a/src/network/packet/MovePlayerPacket.h +++ b/src/network/packet/MovePlayerPacket.h @@ -1,54 +1,52 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__MovePlayerPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__MovePlayerPacket_H__ - -#include "../Packet.h" - -class MovePlayerPacket : public Packet -{ -public: - - int entityId; - float x, y, z, xRot, yRot; - - MovePlayerPacket() - { - } - - MovePlayerPacket(int entityId, float x, float y, float z, float xRot, float yRot) - : entityId(entityId), - x(x), - y(y), - z(z), - xRot(xRot), - yRot(yRot) - {} - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_MOVEPLAYER)); - - bitStream->Write(entityId); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(yRot); - bitStream->Write(xRot); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - bitStream->Read(yRot); - bitStream->Read(xRot); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (MovePlayerPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__MovePlayerPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class MovePlayerPacket : public Packet +{ +public: + + int entityId; + float x, y, z, xRot, yRot; + + MovePlayerPacket() + { + } + + MovePlayerPacket(int entityId, float x, float y, float z, float xRot, float yRot) + : entityId(entityId), + x(x), + y(y), + z(z), + xRot(xRot), + yRot(yRot) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_MOVEPLAYER)); + + bitStream->Write(entityId); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(yRot); + bitStream->Write(xRot); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + bitStream->Read(yRot); + bitStream->Read(xRot); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (MovePlayerPacket*)this); + } +}; + diff --git a/src/network/packet/PacketInclude.h b/src/network/packet/PacketInclude.h index 09aeae8..0d67d42 100755 --- a/src/network/packet/PacketInclude.h +++ b/src/network/packet/PacketInclude.h @@ -1,54 +1,52 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__PacketInclude_H__ -#define NET_MINECRAFT_NETWORK_PACKET__PacketInclude_H__ - -#include "AddEntityPacket.h" -#include "AddItemEntityPacket.h" -#include "AddMobPacket.h" -#include "AddPaintingPacket.h" -#include "AddPlayerPacket.h" -#include "AnimatePacket.h" -#include "AdventureSettingsPacket.h" -#include "ChatPacket.h" -#include "ContainerAckPacket.h" -#include "ContainerOpenPacket.h" -#include "ContainerClosePacket.h" -#include "ContainerSetDataPacket.h" -#include "ContainerSetSlotPacket.h" -#include "ContainerSetContentPacket.h" -#include "ChunkDataPacket.h" -#include "DropItemPacket.h" -#include "EntityEventPacket.h" -#include "ExplodePacket.h" -#include "HurtArmorPacket.h" -#include "InteractPacket.h" -#include "LevelEventPacket.h" -#include "LoginPacket.h" -#include "LoginStatusPacket.h" -#include "MessagePacket.h" -#include "MoveEntityPacket.h" -#include "MovePlayerPacket.h" -#include "PlaceBlockPacket.h" -#include "PlayerActionPacket.h" -#include "PlayerEquipmentPacket.h" -#include "PlayerArmorEquipmentPacket.h" -#include "ReadyPacket.h" -#include "RemoveBlockPacket.h" -#include "RemoveEntityPacket.h" -#include "RemovePlayerPacket.h" -#include "RespawnPacket.h" -#include "RequestChunkPacket.h" -#include "SendInventoryPacket.h" -#include "SetEntityDataPacket.h" -#include "SetEntityMotionPacket.h" -#include "SetHealthPacket.h" -#include "SetSpawnPositionPacket.h" -#include "SetTimePacket.h" -#include "SignUpdatePacket.h" -#include "StartGamePacket.h" -#include "TakeItemEntityPacket.h" -//#include "TeleportEntityPacket.h" -#include "TileEventPacket.h" -#include "UpdateBlockPacket.h" -#include "UseItemPacket.h" - -#endif /*NET_MINECRAFT_NETWORK_PACKET__PacketInclude_H__*/ +#pragma once + +#include "AddEntityPacket.h" +#include "AddItemEntityPacket.h" +#include "AddMobPacket.h" +#include "AddPaintingPacket.h" +#include "AddPlayerPacket.h" +#include "AnimatePacket.h" +#include "AdventureSettingsPacket.h" +#include "ChatPacket.h" +#include "ContainerAckPacket.h" +#include "ContainerOpenPacket.h" +#include "ContainerClosePacket.h" +#include "ContainerSetDataPacket.h" +#include "ContainerSetSlotPacket.h" +#include "ContainerSetContentPacket.h" +#include "ChunkDataPacket.h" +#include "DropItemPacket.h" +#include "EntityEventPacket.h" +#include "ExplodePacket.h" +#include "HurtArmorPacket.h" +#include "InteractPacket.h" +#include "LevelEventPacket.h" +#include "LoginPacket.h" +#include "LoginStatusPacket.h" +#include "MessagePacket.h" +#include "MoveEntityPacket.h" +#include "MovePlayerPacket.h" +#include "PlaceBlockPacket.h" +#include "PlayerActionPacket.h" +#include "PlayerEquipmentPacket.h" +#include "PlayerArmorEquipmentPacket.h" +#include "ReadyPacket.h" +#include "RemoveBlockPacket.h" +#include "RemoveEntityPacket.h" +#include "RemovePlayerPacket.h" +#include "RespawnPacket.h" +#include "RequestChunkPacket.h" +#include "SendInventoryPacket.h" +#include "SetEntityDataPacket.h" +#include "SetEntityMotionPacket.h" +#include "SetHealthPacket.h" +#include "SetSpawnPositionPacket.h" +#include "SetTimePacket.h" +#include "SignUpdatePacket.h" +#include "StartGamePacket.h" +#include "TakeItemEntityPacket.h" +//#include "TeleportEntityPacket.h" +#include "TileEventPacket.h" +#include "UpdateBlockPacket.h" +#include "UseItemPacket.h" + diff --git a/src/network/packet/PlaceBlockPacket.h b/src/network/packet/PlaceBlockPacket.h index c5a8484..12da5d1 100755 --- a/src/network/packet/PlaceBlockPacket.h +++ b/src/network/packet/PlaceBlockPacket.h @@ -1,60 +1,58 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__PlaceBlockPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__PlaceBlockPacket_H__ - -#include "../Packet.h" - -class PlaceBlockPacket : public Packet -{ -public: - - // the id of the player who is placing the block, used to animate the player - int entityId; - int x, z; - unsigned char y, facing, blockId, blockData; - - PlaceBlockPacket() - { - } - - PlaceBlockPacket(int entityId, int x, int y, int z, int facing, int blockId, int blockData) - : entityId(entityId), - x(x), - y((unsigned char)(y & 0xff)), - z(z), - facing ((unsigned char)(facing & 0xff)), - blockId((unsigned char)(blockId & 0xff)), - blockData((unsigned char)(blockData & 0xff)) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_PLACEBLOCK)); - - bitStream->Write(entityId); - bitStream->Write(x); - bitStream->Write(z); - bitStream->Write(y); - bitStream->Write(facing); - bitStream->Write(blockId); - bitStream->Write(blockData); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(x); - bitStream->Read(z); - bitStream->Read(y); - bitStream->Read(facing); - bitStream->Read(blockId); - bitStream->Read(blockData); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (PlaceBlockPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__PlaceBlockPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class PlaceBlockPacket : public Packet +{ +public: + + // the id of the player who is placing the block, used to animate the player + int entityId; + int x, z; + unsigned char y, facing, blockId, blockData; + + PlaceBlockPacket() + { + } + + PlaceBlockPacket(int entityId, int x, int y, int z, int facing, int blockId, int blockData) + : entityId(entityId), + x(x), + y((unsigned char)(y & 0xff)), + z(z), + facing ((unsigned char)(facing & 0xff)), + blockId((unsigned char)(blockId & 0xff)), + blockData((unsigned char)(blockData & 0xff)) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_PLACEBLOCK)); + + bitStream->Write(entityId); + bitStream->Write(x); + bitStream->Write(z); + bitStream->Write(y); + bitStream->Write(facing); + bitStream->Write(blockId); + bitStream->Write(blockData); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(x); + bitStream->Read(z); + bitStream->Read(y); + bitStream->Read(facing); + bitStream->Read(blockId); + bitStream->Read(blockData); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (PlaceBlockPacket*)this); + } +}; + diff --git a/src/network/packet/PlayerActionPacket.h b/src/network/packet/PlayerActionPacket.h index 714dbd0..6a78465 100755 --- a/src/network/packet/PlayerActionPacket.h +++ b/src/network/packet/PlayerActionPacket.h @@ -1,62 +1,60 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__PlayerActionPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__PlayerActionPacket_H__ - -#include "../Packet.h" - -class PlayerActionPacket : public Packet -{ -public: - static const int START_DESTROY_BLOCK = 0; - static const int ABORT_DESTROY_BLOCK = 1; - static const int STOP_DESTROY_BLOCK = 2; - static const int GET_UPDATED_BLOCK = 3; - static const int DROP_ITEM = 4; - static const int RELEASE_USE_ITEM = 5; - static const int STOP_SLEEPING = 6; - - PlayerActionPacket() - : x(0), - y(0), - z(0), - action(0), - face(0), - entityId(0) - {} - - PlayerActionPacket(int action, int x, int y, int z, int face, int entityId) - : x(x), - y(y), - z(z), - face(face), - action(action), - entityId(entityId) - {} - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(action); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - bitStream->Read(face); - bitStream->Read(entityId); - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_PLAYERACTION)); - - bitStream->Write(action); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(face); - bitStream->Write(entityId); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (PlayerActionPacket*)this); - } - - int x, y, z, face, action, entityId; -}; - -#endif /* NET_MINECRAFT_NETWORK_PACKET__PlayerActionPacket_H__ */ +#pragma once + +#include "../Packet.h" + +class PlayerActionPacket : public Packet +{ +public: + static const int START_DESTROY_BLOCK = 0; + static const int ABORT_DESTROY_BLOCK = 1; + static const int STOP_DESTROY_BLOCK = 2; + static const int GET_UPDATED_BLOCK = 3; + static const int DROP_ITEM = 4; + static const int RELEASE_USE_ITEM = 5; + static const int STOP_SLEEPING = 6; + + PlayerActionPacket() + : x(0), + y(0), + z(0), + action(0), + face(0), + entityId(0) + {} + + PlayerActionPacket(int action, int x, int y, int z, int face, int entityId) + : x(x), + y(y), + z(z), + face(face), + action(action), + entityId(entityId) + {} + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(action); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + bitStream->Read(face); + bitStream->Read(entityId); + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_PLAYERACTION)); + + bitStream->Write(action); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(face); + bitStream->Write(entityId); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (PlayerActionPacket*)this); + } + + int x, y, z, face, action, entityId; +}; + diff --git a/src/network/packet/PlayerArmorEquipmentPacket.h b/src/network/packet/PlayerArmorEquipmentPacket.h index 69b28f1..bf1da27 100755 --- a/src/network/packet/PlayerArmorEquipmentPacket.h +++ b/src/network/packet/PlayerArmorEquipmentPacket.h @@ -1,78 +1,76 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__PlayerArmorEquipmentPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__PlayerArmorEquipmentPacket_H__ - -#include "../Packet.h" -#include "../../world/entity/player/Player.h" -#include "../../world/item/ArmorItem.h" -#include "../../world/item/ItemInstance.h" - -// @note: A visual update only -class PlayerArmorEquipmentPacket : public Packet -{ -public: - int entityId; - signed char head; - signed char torso; - signed char legs; - signed char feet; - - PlayerArmorEquipmentPacket() { - } - - PlayerArmorEquipmentPacket(Player* player) - : entityId(player->entityId) - { - get(head, player->getArmor(ArmorItem::SLOT_HEAD)); - get(torso, player->getArmor(ArmorItem::SLOT_TORSO)); - get(legs, player->getArmor(ArmorItem::SLOT_LEGS)); - get(feet, player->getArmor(ArmorItem::SLOT_FEET)); - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_PLAYERARMOREQUIPMENT)); - - bitStream->Write(entityId); - bitStream->Write(head); - bitStream->Write(torso); - bitStream->Write(legs); - bitStream->Write(feet); - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(entityId); - bitStream->Read(head); - bitStream->Read(torso); - bitStream->Read(legs); - bitStream->Read(feet); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (PlayerArmorEquipmentPacket*)this); - } - - void fillIn(Player* player) { - set(player, head, ArmorItem::SLOT_HEAD); - set(player, torso, ArmorItem::SLOT_TORSO); - set(player, legs, ArmorItem::SLOT_LEGS); - set(player, feet, ArmorItem::SLOT_FEET); - } - -private: - void get(signed char& s, const ItemInstance* item) { - if (item) { - s = item->id - 256; - } else { - s = -1; - } - } - - void set(Player* p, signed char s, int slot) { - if (s < 0) p->setArmor(slot, NULL); - else { - ItemInstance item((int)s + 256, 1, 0); - p->setArmor(slot, &item); - } - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__PlayerArmorEquipmentPacket_H__*/ +#pragma once + +#include "../Packet.h" +#include "../../world/entity/player/Player.h" +#include "../../world/item/ArmorItem.h" +#include "../../world/item/ItemInstance.h" + +// @note: A visual update only +class PlayerArmorEquipmentPacket : public Packet +{ +public: + int entityId; + signed char head; + signed char torso; + signed char legs; + signed char feet; + + PlayerArmorEquipmentPacket() { + } + + PlayerArmorEquipmentPacket(Player* player) + : entityId(player->entityId) + { + get(head, player->getArmor(ArmorItem::SLOT_HEAD)); + get(torso, player->getArmor(ArmorItem::SLOT_TORSO)); + get(legs, player->getArmor(ArmorItem::SLOT_LEGS)); + get(feet, player->getArmor(ArmorItem::SLOT_FEET)); + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_PLAYERARMOREQUIPMENT)); + + bitStream->Write(entityId); + bitStream->Write(head); + bitStream->Write(torso); + bitStream->Write(legs); + bitStream->Write(feet); + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(entityId); + bitStream->Read(head); + bitStream->Read(torso); + bitStream->Read(legs); + bitStream->Read(feet); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (PlayerArmorEquipmentPacket*)this); + } + + void fillIn(Player* player) { + set(player, head, ArmorItem::SLOT_HEAD); + set(player, torso, ArmorItem::SLOT_TORSO); + set(player, legs, ArmorItem::SLOT_LEGS); + set(player, feet, ArmorItem::SLOT_FEET); + } + +private: + void get(signed char& s, const ItemInstance* item) { + if (item) { + s = item->id - 256; + } else { + s = -1; + } + } + + void set(Player* p, signed char s, int slot) { + if (s < 0) p->setArmor(slot, NULL); + else { + ItemInstance item((int)s + 256, 1, 0); + p->setArmor(slot, &item); + } + } +}; + diff --git a/src/network/packet/PlayerEquipmentPacket.h b/src/network/packet/PlayerEquipmentPacket.h index 5dfb315..63cec5c 100755 --- a/src/network/packet/PlayerEquipmentPacket.h +++ b/src/network/packet/PlayerEquipmentPacket.h @@ -1,46 +1,44 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__PlayerEquipmentPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__PlayerEquipmentPacket_H__ - -#include "../Packet.h" - -class PlayerEquipmentPacket : public Packet -{ -public: - int entityId; - unsigned short itemId; - unsigned short itemAuxValue; - - PlayerEquipmentPacket() - { - } - - PlayerEquipmentPacket(int entityId, int itemId, int data) - : entityId(entityId), - itemId(itemId), - itemAuxValue(data) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_PLAYEREQUIPMENT)); - - bitStream->Write(entityId); - bitStream->Write(itemId); - bitStream->Write(itemAuxValue); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(itemId); - bitStream->Read(itemAuxValue); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (PlayerEquipmentPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__PlayerEquipmentPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class PlayerEquipmentPacket : public Packet +{ +public: + int entityId; + unsigned short itemId; + unsigned short itemAuxValue; + + PlayerEquipmentPacket() + { + } + + PlayerEquipmentPacket(int entityId, int itemId, int data) + : entityId(entityId), + itemId(itemId), + itemAuxValue(data) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_PLAYEREQUIPMENT)); + + bitStream->Write(entityId); + bitStream->Write(itemId); + bitStream->Write(itemAuxValue); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(itemId); + bitStream->Read(itemAuxValue); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (PlayerEquipmentPacket*)this); + } +}; + diff --git a/src/network/packet/ReadyPacket.h b/src/network/packet/ReadyPacket.h index fa19ce3..4ae95c1 100755 --- a/src/network/packet/ReadyPacket.h +++ b/src/network/packet/ReadyPacket.h @@ -1,42 +1,40 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__ReadyPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__ReadyPacket_H__ - -#include "../Packet.h" - -class ReadyPacket: public Packet -{ -public: - static const char READY_UNDEFINED = 0; - static const char READY_CLIENTGENERATION = 1; - static const char READY_REQUESTEDCHUNKS = 2; - - ReadyPacket() - : type(READY_UNDEFINED) - { - } - - ReadyPacket(char type) - : type(type) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_READY)); - bitStream->Write(type); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(type); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (ReadyPacket*)this); - } - - char type; -}; - -#endif /*#NET_MINECRAFT_NETWORK_PACKET__ReadyPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class ReadyPacket: public Packet +{ +public: + static const char READY_UNDEFINED = 0; + static const char READY_CLIENTGENERATION = 1; + static const char READY_REQUESTEDCHUNKS = 2; + + ReadyPacket() + : type(READY_UNDEFINED) + { + } + + ReadyPacket(char type) + : type(type) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_READY)); + bitStream->Write(type); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(type); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (ReadyPacket*)this); + } + + char type; +}; + diff --git a/src/network/packet/RemoveBlockPacket.h b/src/network/packet/RemoveBlockPacket.h index 2f2ec5d..8e24ef9 100755 --- a/src/network/packet/RemoveBlockPacket.h +++ b/src/network/packet/RemoveBlockPacket.h @@ -1,52 +1,50 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__RemoveBlockPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__RemoveBlockPacket_H__ - -#include "../Packet.h" -#include "../../world/entity/player/Player.h" - -class RemoveBlockPacket : public Packet -{ -public: - - // the id of the player who is placing the block, used to animate the player - int entityId; - int x, z; - unsigned char y; - - RemoveBlockPacket() - { - } - - RemoveBlockPacket(Player* p, int x, int y, int z) - : entityId(p->entityId), - x(x), - y((unsigned char)(y & 0xff)), - z(z) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_REMOVEBLOCK)); - - bitStream->Write(entityId); - bitStream->Write(x); - bitStream->Write(z); - bitStream->Write(y); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(x); - bitStream->Read(z); - bitStream->Read(y); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (RemoveBlockPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__RemoveBlockPacket_H__*/ +#pragma once + +#include "../Packet.h" +#include "../../world/entity/player/Player.h" + +class RemoveBlockPacket : public Packet +{ +public: + + // the id of the player who is placing the block, used to animate the player + int entityId; + int x, z; + unsigned char y; + + RemoveBlockPacket() + { + } + + RemoveBlockPacket(Player* p, int x, int y, int z) + : entityId(p->entityId), + x(x), + y((unsigned char)(y & 0xff)), + z(z) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_REMOVEBLOCK)); + + bitStream->Write(entityId); + bitStream->Write(x); + bitStream->Write(z); + bitStream->Write(y); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(x); + bitStream->Read(z); + bitStream->Read(y); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (RemoveBlockPacket*)this); + } +}; + diff --git a/src/network/packet/RemoveEntityPacket.h b/src/network/packet/RemoveEntityPacket.h index 3579c29..8ef072f 100755 --- a/src/network/packet/RemoveEntityPacket.h +++ b/src/network/packet/RemoveEntityPacket.h @@ -1,39 +1,37 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__RemoveEntityPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__RemoveEntityPacket_H__ - -#include "../Packet.h" - -class RemoveEntityPacket : public Packet -{ -public: - - int entityId; - - RemoveEntityPacket() - { - } - - RemoveEntityPacket(int entityId) - : entityId(entityId) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_REMOVEENTITY)); - - bitStream->Write(entityId); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (RemoveEntityPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__RemoveEntityPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class RemoveEntityPacket : public Packet +{ +public: + + int entityId; + + RemoveEntityPacket() + { + } + + RemoveEntityPacket(int entityId) + : entityId(entityId) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_REMOVEENTITY)); + + bitStream->Write(entityId); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (RemoveEntityPacket*)this); + } +}; + diff --git a/src/network/packet/RemovePlayerPacket.h b/src/network/packet/RemovePlayerPacket.h index 86840d4..2bbe6d4 100755 --- a/src/network/packet/RemovePlayerPacket.h +++ b/src/network/packet/RemovePlayerPacket.h @@ -1,41 +1,39 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__RemovePlayerPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__RemovePlayerPacket_H__ - -#include "../Packet.h" -#include "../../world/entity/player/Player.h" - -class RemovePlayerPacket : public Packet -{ -public: - RemovePlayerPacket() {} - - RemovePlayerPacket(const Player* p) - : entityId(p->entityId), - owner(p->owner) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_REMOVEPLAYER)); - - bitStream->Write(entityId); - bitStream->Write(owner); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(owner); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (RemovePlayerPacket*)this); - } - - int entityId; - RakNet::RakNetGUID owner; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__RemovePlayerPacket_H__*/ +#pragma once + +#include "../Packet.h" +#include "../../world/entity/player/Player.h" + +class RemovePlayerPacket : public Packet +{ +public: + RemovePlayerPacket() {} + + RemovePlayerPacket(const Player* p) + : entityId(p->entityId), + owner(p->owner) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_REMOVEPLAYER)); + + bitStream->Write(entityId); + bitStream->Write(owner); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(owner); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (RemovePlayerPacket*)this); + } + + int entityId; + RakNet::RakNetGUID owner; +}; + diff --git a/src/network/packet/RequestChunkPacket.h b/src/network/packet/RequestChunkPacket.h index e25add0..a8b63cf 100755 --- a/src/network/packet/RequestChunkPacket.h +++ b/src/network/packet/RequestChunkPacket.h @@ -1,42 +1,40 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__RequestChunkPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__RequestChunkPacket_H__ - -#include "../Packet.h" - -class RequestChunkPacket : public Packet -{ -public: - - int x, z; - - RequestChunkPacket() - { - } - - RequestChunkPacket(int _x, int _z) - { - x = _x; - z = _z; - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_REQUESTCHUNK)); - - bitStream->Write(x); - bitStream->Write(z); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(x); - bitStream->Read(z); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (RequestChunkPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__RequestChunkPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class RequestChunkPacket : public Packet +{ +public: + + int x, z; + + RequestChunkPacket() + { + } + + RequestChunkPacket(int _x, int _z) + { + x = _x; + z = _z; + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_REQUESTCHUNK)); + + bitStream->Write(x); + bitStream->Write(z); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(x); + bitStream->Read(z); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (RequestChunkPacket*)this); + } +}; + diff --git a/src/network/packet/RespawnPacket.h b/src/network/packet/RespawnPacket.h index 74e2371..b5fa761 100755 --- a/src/network/packet/RespawnPacket.h +++ b/src/network/packet/RespawnPacket.h @@ -1,47 +1,45 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__RespawnPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__RespawnPacket_H__ - -#include "../Packet.h" - -class RespawnPacket: public Packet -{ -public: - RespawnPacket() - { - } - - RespawnPacket(const Player* p) - : x(p->x),y(p->y),z(p->z), - entityId(p->entityId) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_RESPAWN)); - bitStream->Write(entityId); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (RespawnPacket*)this); - } - - float x; - float y; - float z; - int entityId; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__RespawnPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class RespawnPacket: public Packet +{ +public: + RespawnPacket() + { + } + + RespawnPacket(const Player* p) + : x(p->x),y(p->y),z(p->z), + entityId(p->entityId) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_RESPAWN)); + bitStream->Write(entityId); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (RespawnPacket*)this); + } + + float x; + float y; + float z; + int entityId; +}; + diff --git a/src/network/packet/SendInventoryPacket.h b/src/network/packet/SendInventoryPacket.h index 65d12f4..c56a3bb 100755 --- a/src/network/packet/SendInventoryPacket.h +++ b/src/network/packet/SendInventoryPacket.h @@ -1,69 +1,67 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__SendInventoryPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__SendInventoryPacket_H__ - -#include "../Packet.h" - -class SendInventoryPacket: public Packet -{ -public: - SendInventoryPacket() - { - } - - SendInventoryPacket(Player* player, bool dropItems) - : entityId(player->entityId), - extra(dropItems? ExtraDrop : 0) - { - Inventory* inv = player->inventory; - numItems = 0; - for (int i = Inventory::MAX_SELECTION_SIZE; i < inv->getContainerSize(); ++i) { - ++numItems; - ItemInstance* item = inv->getItem(i); - items.push_back(item? *item : ItemInstance()); - } - for (int i = 0; i < NumArmorItems; ++i) { - ItemInstance* item = player->getArmor(i); - items.push_back(item? *item : ItemInstance()); - } - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SENDINVENTORY)); - bitStream->Write(entityId); - bitStream->Write(extra); - bitStream->Write(numItems); - // Inventory - for (int i = 0; i < numItems; ++i) - PacketUtil::writeItemInstance(items[i], bitStream); - // Armor - for (int i = 0; i < NumArmorItems; ++i) - PacketUtil::writeItemInstance(items[i + numItems], bitStream); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(entityId); - bitStream->Read(extra); - bitStream->Read(numItems); - items.clear(); - // Inventory, Armor - for (int i = 0; i < numItems + NumArmorItems; ++i) - items.push_back(PacketUtil::readItemInstance(bitStream)); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (SendInventoryPacket*)this); - } - - int entityId; - std::vector items; - short numItems; - unsigned char extra; - - static const int ExtraDrop = 1; - static const int NumArmorItems = 4; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__SendInventoryPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class SendInventoryPacket: public Packet +{ +public: + SendInventoryPacket() + { + } + + SendInventoryPacket(Player* player, bool dropItems) + : entityId(player->entityId), + extra(dropItems? ExtraDrop : 0) + { + Inventory* inv = player->inventory; + numItems = 0; + for (int i = Inventory::MAX_SELECTION_SIZE; i < inv->getContainerSize(); ++i) { + ++numItems; + ItemInstance* item = inv->getItem(i); + items.push_back(item? *item : ItemInstance()); + } + for (int i = 0; i < NumArmorItems; ++i) { + ItemInstance* item = player->getArmor(i); + items.push_back(item? *item : ItemInstance()); + } + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SENDINVENTORY)); + bitStream->Write(entityId); + bitStream->Write(extra); + bitStream->Write(numItems); + // Inventory + for (int i = 0; i < numItems; ++i) + PacketUtil::writeItemInstance(items[i], bitStream); + // Armor + for (int i = 0; i < NumArmorItems; ++i) + PacketUtil::writeItemInstance(items[i + numItems], bitStream); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(entityId); + bitStream->Read(extra); + bitStream->Read(numItems); + items.clear(); + // Inventory, Armor + for (int i = 0; i < numItems + NumArmorItems; ++i) + items.push_back(PacketUtil::readItemInstance(bitStream)); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (SendInventoryPacket*)this); + } + + int entityId; + std::vector items; + short numItems; + unsigned char extra; + + static const int ExtraDrop = 1; + static const int NumArmorItems = 4; +}; + diff --git a/src/network/packet/SetEntityDataPacket.h b/src/network/packet/SetEntityDataPacket.h index 4588716..5e81c26 100755 --- a/src/network/packet/SetEntityDataPacket.h +++ b/src/network/packet/SetEntityDataPacket.h @@ -1,64 +1,62 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__SetEntityDataPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__SetEntityDataPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -#include "../../world/entity/SynchedEntityData.h" -#include "../../util/RakDataIO.h" - -class SetEntityDataPacket: public Packet -{ -public: - SetEntityDataPacket() - : deletePackedItems(false) - {} - - SetEntityDataPacket(int id, SynchedEntityData& entityData) - : id(id), - deletePackedItems(false), - packedItems(entityData.packDirty()) - { - } - - ~SetEntityDataPacket() { - if (deletePackedItems) - for (unsigned int i = 0; i < packedItems.size(); ++i) - delete packedItems[i]; - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETENTITYDATA)); - bitStream->Write(id); - - RakDataOutput dos(*bitStream); - SynchedEntityData::pack(&packedItems, &dos); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(id); - - RakDataInput dis(*bitStream); - packedItems = SynchedEntityData::unpack(&dis); - deletePackedItems = true; - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (SetEntityDataPacket*)this); - } - - SynchedEntityData::DataList& getUnpackedData() { - return packedItems; - } -public: - int id; -private: - bool deletePackedItems; - SynchedEntityData::DataList packedItems; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__SetEntityDataPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +#include "../../world/entity/SynchedEntityData.h" +#include "../../util/RakDataIO.h" + +class SetEntityDataPacket: public Packet +{ +public: + SetEntityDataPacket() + : deletePackedItems(false) + {} + + SetEntityDataPacket(int id, SynchedEntityData& entityData) + : id(id), + deletePackedItems(false), + packedItems(entityData.packDirty()) + { + } + + ~SetEntityDataPacket() { + if (deletePackedItems) + for (unsigned int i = 0; i < packedItems.size(); ++i) + delete packedItems[i]; + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETENTITYDATA)); + bitStream->Write(id); + + RakDataOutput dos(*bitStream); + SynchedEntityData::pack(&packedItems, &dos); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(id); + + RakDataInput dis(*bitStream); + packedItems = SynchedEntityData::unpack(&dis); + deletePackedItems = true; + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (SetEntityDataPacket*)this); + } + + SynchedEntityData::DataList& getUnpackedData() { + return packedItems; + } +public: + int id; +private: + bool deletePackedItems; + SynchedEntityData::DataList packedItems; +}; + diff --git a/src/network/packet/SetEntityMotionPacket.h b/src/network/packet/SetEntityMotionPacket.h index dc93b7e..b93fbc1 100755 --- a/src/network/packet/SetEntityMotionPacket.h +++ b/src/network/packet/SetEntityMotionPacket.h @@ -1,68 +1,66 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__SetEntityMotionPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__SetEntityMotionPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" -#include "../../world/entity/Entity.h" - -class SetEntityMotionPacket: public Packet -{ -public: - SetEntityMotionPacket() {} - - SetEntityMotionPacket(Entity* e) { - init(e->entityId, e->xd, e->yd, e->zd); - } - - SetEntityMotionPacket(int id, float xd, float yd, float zd) { - init(id, xd, yd, zd); - } - - void write(RakNet::BitStream* bitStream) - { - const float M = 3.9f; - short xa = (short)(8000.0f * Mth::clamp(xd, -M, M)); - short ya = (short)(8000.0f * Mth::clamp(yd, -M, M)); - short za = (short)(8000.0f * Mth::clamp(zd, -M, M)); - - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETENTITYMOTION)); - bitStream->Write(id); - bitStream->Write(xa); - bitStream->Write(ya); - bitStream->Write(za); - } - - void read(RakNet::BitStream* bitStream) - { - short xa, ya, za; - bitStream->Read(id); - bitStream->Read(xa); - bitStream->Read(ya); - bitStream->Read(za); - - xd = xa / 8000.0f; - yd = ya / 8000.0f; - zd = za / 8000.0f; - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (SetEntityMotionPacket*)this); - } - -private: - void init(int entityId, float xd, float yd, float zd) { - this->id = entityId; - this->xd = xd; - this->yd = yd; - this->zd = zd; - } - -public: - int id; - float xd, yd, zd; - -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__SetEntityMotionPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" +#include "../../world/entity/Entity.h" + +class SetEntityMotionPacket: public Packet +{ +public: + SetEntityMotionPacket() {} + + SetEntityMotionPacket(Entity* e) { + init(e->entityId, e->xd, e->yd, e->zd); + } + + SetEntityMotionPacket(int id, float xd, float yd, float zd) { + init(id, xd, yd, zd); + } + + void write(RakNet::BitStream* bitStream) + { + const float M = 3.9f; + short xa = (short)(8000.0f * Mth::clamp(xd, -M, M)); + short ya = (short)(8000.0f * Mth::clamp(yd, -M, M)); + short za = (short)(8000.0f * Mth::clamp(zd, -M, M)); + + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETENTITYMOTION)); + bitStream->Write(id); + bitStream->Write(xa); + bitStream->Write(ya); + bitStream->Write(za); + } + + void read(RakNet::BitStream* bitStream) + { + short xa, ya, za; + bitStream->Read(id); + bitStream->Read(xa); + bitStream->Read(ya); + bitStream->Read(za); + + xd = xa / 8000.0f; + yd = ya / 8000.0f; + zd = za / 8000.0f; + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (SetEntityMotionPacket*)this); + } + +private: + void init(int entityId, float xd, float yd, float zd) { + this->id = entityId; + this->xd = xd; + this->yd = yd; + this->zd = zd; + } + +public: + int id; + float xd, yd, zd; + +}; + diff --git a/src/network/packet/SetHealthPacket.h b/src/network/packet/SetHealthPacket.h index bd6dbb2..0912ed6 100755 --- a/src/network/packet/SetHealthPacket.h +++ b/src/network/packet/SetHealthPacket.h @@ -1,41 +1,39 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__SetHealthPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__SetHealthPacket_H__ - -#include "../Packet.h" - -//package net.minecraft.network.packet; - -class SetHealthPacket: public Packet { -public: - static const int HEALTH_MODIFY_OFFSET = -64; - - SetHealthPacket() { - } - - SetHealthPacket(int health) - : health(health) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETHEALTH)); - bitStream->Write((signed char)health); - } - - void read(RakNet::BitStream* bitStream) - { - signed char tmpHealth; - bitStream->Read(tmpHealth); - health = tmpHealth; - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (SetHealthPacket*)this); - } - - int health; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__SetHealthPacket_H__*/ +#pragma once + +#include "../Packet.h" + +//package net.minecraft.network.packet; + +class SetHealthPacket: public Packet { +public: + static const int HEALTH_MODIFY_OFFSET = -64; + + SetHealthPacket() { + } + + SetHealthPacket(int health) + : health(health) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETHEALTH)); + bitStream->Write((signed char)health); + } + + void read(RakNet::BitStream* bitStream) + { + signed char tmpHealth; + bitStream->Read(tmpHealth); + health = tmpHealth; + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (SetHealthPacket*)this); + } + + int health; +}; + diff --git a/src/network/packet/SetSpawnPositionPacket.h b/src/network/packet/SetSpawnPositionPacket.h index 6b409a6..e38a17b 100755 --- a/src/network/packet/SetSpawnPositionPacket.h +++ b/src/network/packet/SetSpawnPositionPacket.h @@ -1,52 +1,50 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__SetSpawnPositionPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__SetSpawnPositionPacket_H__ - -#include "../Packet.h" - -class SetSpawnPositionPacket : public Packet -{ -public: - int entityId; - int x, z; - unsigned char y; - - SetSpawnPositionPacket() - { - } - - SetSpawnPositionPacket(int x, int y, int z) - : x(x), - y((unsigned char)(y & 0xff)), - z(z) - { - } - SetSpawnPositionPacket(const Pos& pos) - : x(pos.x), - y((unsigned char)(pos.y & 0xff)), - z(pos.z) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETSPAWNPOSITION)); - - bitStream->Write(x); - bitStream->Write(z); - bitStream->Write(y); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(x); - bitStream->Read(z); - bitStream->Read(y); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (SetSpawnPositionPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__SetSpawnPositionPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class SetSpawnPositionPacket : public Packet +{ +public: + int entityId; + int x, z; + unsigned char y; + + SetSpawnPositionPacket() + { + } + + SetSpawnPositionPacket(int x, int y, int z) + : x(x), + y((unsigned char)(y & 0xff)), + z(z) + { + } + SetSpawnPositionPacket(const Pos& pos) + : x(pos.x), + y((unsigned char)(pos.y & 0xff)), + z(pos.z) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETSPAWNPOSITION)); + + bitStream->Write(x); + bitStream->Write(z); + bitStream->Write(y); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(x); + bitStream->Read(z); + bitStream->Read(y); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (SetSpawnPositionPacket*)this); + } +}; + diff --git a/src/network/packet/SetTimePacket.h b/src/network/packet/SetTimePacket.h index e2fb484..600fe8d 100755 --- a/src/network/packet/SetTimePacket.h +++ b/src/network/packet/SetTimePacket.h @@ -1,37 +1,35 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__SetTimePacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__SetTimePacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" -#include - -class SetTimePacket: public Packet { -public: - SetTimePacket() { - } - - SetTimePacket(long time) - : time((int32_t)time) - {} - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETTIME)); - bitStream->Write(time); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(time); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (SetTimePacket*)this); - } - - int32_t time; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__SetTimePacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" +#include + +class SetTimePacket: public Packet { +public: + SetTimePacket() { + } + + SetTimePacket(long time) + : time((int32_t)time) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SETTIME)); + bitStream->Write(time); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(time); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (SetTimePacket*)this); + } + + int32_t time; +}; + diff --git a/src/network/packet/SignUpdatePacket.h b/src/network/packet/SignUpdatePacket.h index 1fadf5d..17b595b 100755 --- a/src/network/packet/SignUpdatePacket.h +++ b/src/network/packet/SignUpdatePacket.h @@ -1,68 +1,66 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__SignUpdatePacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__SignUpdatePacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" -#include "../../util/RakDataIO.h" -#include "../../world/level/tile/entity/SignTileEntity.h" - -class SignUpdatePacket: public Packet -{ -public: - SignUpdatePacket() {} - - SignUpdatePacket(int x, int y, int z, const std::string lines[]) - : x(x), - y(y), - z(z) - { - for (int i = 0; i < 4; ++i) - this->lines[i] = lines[i]; - } - - /*@Override*/ - void read(RakNet::BitStream* bitStream) { - short xx, zz; - unsigned char yy; - bitStream->Read(xx); - bitStream->Read(yy); - bitStream->Read(zz); - x = xx; - z = zz; - y = yy; - - RakDataInput dis(*bitStream); - for (int i = 0; i < 4; ++i) { - lines[i] = dis.readString(); - if (lines[i].length() > SignTileEntity::MAX_LINE_LENGTH) - lines[i].resize(SignTileEntity::MAX_LINE_LENGTH); - } - } - - /*@Override*/ - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SIGNUPDATE)); - short xx = x; - short zz = z; - unsigned char yy = y; - bitStream->Write(xx); - bitStream->Write(yy); - bitStream->Write(zz); - - RakDataOutput dos(*bitStream); - for (int i = 0; i < 4; ++i) - dos.writeString(lines[i]); - } - - /*@Override*/ - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (SignUpdatePacket*)this); - } - -public: - int x, y, z; - std::string lines[4]; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__SignUpdatePacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" +#include "../../util/RakDataIO.h" +#include "../../world/level/tile/entity/SignTileEntity.h" + +class SignUpdatePacket: public Packet +{ +public: + SignUpdatePacket() {} + + SignUpdatePacket(int x, int y, int z, const std::string lines[]) + : x(x), + y(y), + z(z) + { + for (int i = 0; i < 4; ++i) + this->lines[i] = lines[i]; + } + + /*@Override*/ + void read(RakNet::BitStream* bitStream) { + short xx, zz; + unsigned char yy; + bitStream->Read(xx); + bitStream->Read(yy); + bitStream->Read(zz); + x = xx; + z = zz; + y = yy; + + RakDataInput dis(*bitStream); + for (int i = 0; i < 4; ++i) { + lines[i] = dis.readString(); + if (lines[i].length() > SignTileEntity::MAX_LINE_LENGTH) + lines[i].resize(SignTileEntity::MAX_LINE_LENGTH); + } + } + + /*@Override*/ + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_SIGNUPDATE)); + short xx = x; + short zz = z; + unsigned char yy = y; + bitStream->Write(xx); + bitStream->Write(yy); + bitStream->Write(zz); + + RakDataOutput dos(*bitStream); + for (int i = 0; i < 4; ++i) + dos.writeString(lines[i]); + } + + /*@Override*/ + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (SignUpdatePacket*)this); + } + +public: + int x, y, z; + std::string lines[4]; +}; + diff --git a/src/network/packet/StartGamePacket.h b/src/network/packet/StartGamePacket.h index 24adead..9e289a4 100755 --- a/src/network/packet/StartGamePacket.h +++ b/src/network/packet/StartGamePacket.h @@ -1,62 +1,60 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__StartGamePacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__StartGamePacket_H__ - -#include "../Packet.h" -#include - -class StartGamePacket : public Packet -{ -public: - int32_t levelSeed; - int levelGeneratorVersion; - int gameType; - - int entityId; - float x, y, z; - - StartGamePacket() - { - } - - StartGamePacket(long seed, int levelGeneratorVersion, int gameType, int entityId, float x, float y, float z) - : levelSeed((int32_t)seed), - levelGeneratorVersion(levelGeneratorVersion), - gameType(gameType), - entityId(entityId), - x(x), - y(y), - z(z) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_STARTGAME)); - - bitStream->Write(levelSeed); - bitStream->Write(levelGeneratorVersion); - bitStream->Write(gameType); - bitStream->Write(entityId); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(levelSeed); - bitStream->Read(levelGeneratorVersion); - bitStream->Read(gameType); - bitStream->Read(entityId); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (StartGamePacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__StartGamePacket_H__*/ +#pragma once + +#include "../Packet.h" +#include + +class StartGamePacket : public Packet +{ +public: + int32_t levelSeed; + int levelGeneratorVersion; + int gameType; + + int entityId; + float x, y, z; + + StartGamePacket() + { + } + + StartGamePacket(long seed, int levelGeneratorVersion, int gameType, int entityId, float x, float y, float z) + : levelSeed((int32_t)seed), + levelGeneratorVersion(levelGeneratorVersion), + gameType(gameType), + entityId(entityId), + x(x), + y(y), + z(z) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_STARTGAME)); + + bitStream->Write(levelSeed); + bitStream->Write(levelGeneratorVersion); + bitStream->Write(gameType); + bitStream->Write(entityId); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(levelSeed); + bitStream->Read(levelGeneratorVersion); + bitStream->Read(gameType); + bitStream->Read(entityId); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (StartGamePacket*)this); + } +}; + diff --git a/src/network/packet/TakeItemEntityPacket.h b/src/network/packet/TakeItemEntityPacket.h index ada5fed..6ce128d 100755 --- a/src/network/packet/TakeItemEntityPacket.h +++ b/src/network/packet/TakeItemEntityPacket.h @@ -1,42 +1,40 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__TakeItemEntityPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__TakeItemEntityPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -class TakeItemEntityPacket: public Packet -{ -public: - TakeItemEntityPacket() { - } - - TakeItemEntityPacket(int itemId, int playerId) - : itemId(itemId), - playerId(playerId) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_TAKEITEMENTITY)); - bitStream->Write(itemId); - bitStream->Write(playerId); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(itemId); - bitStream->Read(playerId); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (TakeItemEntityPacket*)this); - } - - int itemId; - int playerId; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__TakeItemEntityPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +class TakeItemEntityPacket: public Packet +{ +public: + TakeItemEntityPacket() { + } + + TakeItemEntityPacket(int itemId, int playerId) + : itemId(itemId), + playerId(playerId) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_TAKEITEMENTITY)); + bitStream->Write(itemId); + bitStream->Write(playerId); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(itemId); + bitStream->Read(playerId); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (TakeItemEntityPacket*)this); + } + + int itemId; + int playerId; +}; + diff --git a/src/network/packet/TeleportEntityPacket.h b/src/network/packet/TeleportEntityPacket.h index cb3a462..ed127fc 100755 --- a/src/network/packet/TeleportEntityPacket.h +++ b/src/network/packet/TeleportEntityPacket.h @@ -1,77 +1,75 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__TeleportEntityPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__TeleportEntityPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -#include "../../world/entity/Entity.h" -#include "../../util/Mth.h" - -class TeleportEntityPacket: public Packet -{ -public: - TeleportEntityPacket() { - } - - TeleportEntityPacket(Entity* e, char cause) - : id(e->entityId), - x(e->x), - y(e->y), - z(e->z), - yRot(e->yRot), - xRot(e->xRot), - cause(cause) - { - } - - TeleportEntityPacket(int id, float x, float y, float z, float yRot, float xRot, char cause) - : id(id), - x(x), - y(y), - z(z), - yRot(yRot), - xRot(xRot), - cause(cause) - { - } - - void write(RakNet::BitStream* bitStream) { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_TELEPORTENTITY)); - bitStream->Write(id); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(PacketUtil::Rot_degreesToChar(yRot)); - bitStream->Write(PacketUtil::Rot_degreesToChar(xRot)); - bitStream->Write(cause); - } - - void read(RakNet::BitStream* bitStream) { - bitStream->Read(id); - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - char rx, ry; - bitStream->Read(ry); - bitStream->Read(rx); - bitStream->Read(cause); - yRot = PacketUtil::Rot_degreesToChar(ry); - xRot = PacketUtil::Rot_charToDegrees(rx); - - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (TeleportEntityPacket*)this); - } - - int id; - float x, y, z; - float xRot, yRot; // sent as byte - char cause; - - static const int WANT_RESPAWN = 1; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__TeleportEntityPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +#include "../../world/entity/Entity.h" +#include "../../util/Mth.h" + +class TeleportEntityPacket: public Packet +{ +public: + TeleportEntityPacket() { + } + + TeleportEntityPacket(Entity* e, char cause) + : id(e->entityId), + x(e->x), + y(e->y), + z(e->z), + yRot(e->yRot), + xRot(e->xRot), + cause(cause) + { + } + + TeleportEntityPacket(int id, float x, float y, float z, float yRot, float xRot, char cause) + : id(id), + x(x), + y(y), + z(z), + yRot(yRot), + xRot(xRot), + cause(cause) + { + } + + void write(RakNet::BitStream* bitStream) { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_TELEPORTENTITY)); + bitStream->Write(id); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(PacketUtil::Rot_degreesToChar(yRot)); + bitStream->Write(PacketUtil::Rot_degreesToChar(xRot)); + bitStream->Write(cause); + } + + void read(RakNet::BitStream* bitStream) { + bitStream->Read(id); + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + char rx, ry; + bitStream->Read(ry); + bitStream->Read(rx); + bitStream->Read(cause); + yRot = PacketUtil::Rot_degreesToChar(ry); + xRot = PacketUtil::Rot_charToDegrees(rx); + + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (TeleportEntityPacket*)this); + } + + int id; + float x, y, z; + float xRot, yRot; // sent as byte + char cause; + + static const int WANT_RESPAWN = 1; +}; + diff --git a/src/network/packet/TileEventPacket.h b/src/network/packet/TileEventPacket.h index 1319fd0..9048ae4 100755 --- a/src/network/packet/TileEventPacket.h +++ b/src/network/packet/TileEventPacket.h @@ -1,48 +1,46 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__TileEventPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__TileEventPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -class TileEventPacket: public Packet { -public: - TileEventPacket() {} - - TileEventPacket(int x, int y, int z, int b0, int b1) - : x(x), - y(y), - z(z), - b0(b0), - b1(b1) - {} - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_TILEEVENT)); - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(b0); - bitStream->Write(b1); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - bitStream->Read(b0); - bitStream->Read(b1); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (TileEventPacket*)this); - } - - int x, y, z; - int b0, b1; -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__TileEventPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +class TileEventPacket: public Packet { +public: + TileEventPacket() {} + + TileEventPacket(int x, int y, int z, int b0, int b1) + : x(x), + y(y), + z(z), + b0(b0), + b1(b1) + {} + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_TILEEVENT)); + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(b0); + bitStream->Write(b1); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + bitStream->Read(b0); + bitStream->Read(b1); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (TileEventPacket*)this); + } + + int x, y, z; + int b0, b1; +}; + diff --git a/src/network/packet/UpdateArmorPacket.h b/src/network/packet/UpdateArmorPacket.h index c1e812f..4276355 100755 --- a/src/network/packet/UpdateArmorPacket.h +++ b/src/network/packet/UpdateArmorPacket.h @@ -1,28 +1,26 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__UpdateArmorPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__UpdateArmorPacket_H__ - -#include "../Packet.h" - -class UpdateArmorPacket: public Packet -{ -public: - UpdateArmorPacket(Player* player) - { - } - - void write(RakNet::BitStream* bitStream){ - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_UPDATEARMOR)); - - //bitStream->Write(); - } - - void read(RakNet::BitStream* bitStream) { - //bitStream->Read(); - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { - callback->handle(source, (UpdateArmorPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__UpdateArmorPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class UpdateArmorPacket: public Packet +{ +public: + UpdateArmorPacket(Player* player) + { + } + + void write(RakNet::BitStream* bitStream){ + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_UPDATEARMOR)); + + //bitStream->Write(); + } + + void read(RakNet::BitStream* bitStream) { + //bitStream->Read(); + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) { + callback->handle(source, (UpdateArmorPacket*)this); + } +}; + diff --git a/src/network/packet/UpdateBlockPacket.h b/src/network/packet/UpdateBlockPacket.h index 3559034..78e97f2 100755 --- a/src/network/packet/UpdateBlockPacket.h +++ b/src/network/packet/UpdateBlockPacket.h @@ -1,55 +1,53 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__UpdateBlockPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__UpdateBlockPacket_H__ - -#include "../Packet.h" - -class UpdateBlockPacket : public Packet -{ -public: - - int x, z; - unsigned char y; - unsigned char blockId; - unsigned char blockData; - - UpdateBlockPacket() - { - } - - UpdateBlockPacket(int _x, int _y, int _z, int _blockId, int _blockData) - { - x = _x; - y = (unsigned char)(_y & 0xff); - z = _z; - blockId = (unsigned char)(_blockId & 0xff); - blockData = (unsigned char)(_blockData & 0xff); - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_UPDATEBLOCK)); - - bitStream->Write(x); - bitStream->Write(z); - bitStream->Write(y); - bitStream->Write(blockId); - bitStream->Write(blockData); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(x); - bitStream->Read(z); - bitStream->Read(y); - bitStream->Read(blockId); - bitStream->Read(blockData); - - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (UpdateBlockPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__UpdateBlockPacket_H__*/ +#pragma once + +#include "../Packet.h" + +class UpdateBlockPacket : public Packet +{ +public: + + int x, z; + unsigned char y; + unsigned char blockId; + unsigned char blockData; + + UpdateBlockPacket() + { + } + + UpdateBlockPacket(int _x, int _y, int _z, int _blockId, int _blockData) + { + x = _x; + y = (unsigned char)(_y & 0xff); + z = _z; + blockId = (unsigned char)(_blockId & 0xff); + blockData = (unsigned char)(_blockData & 0xff); + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_UPDATEBLOCK)); + + bitStream->Write(x); + bitStream->Write(z); + bitStream->Write(y); + bitStream->Write(blockId); + bitStream->Write(blockData); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(x); + bitStream->Read(z); + bitStream->Read(y); + bitStream->Read(blockId); + bitStream->Read(blockData); + + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (UpdateBlockPacket*)this); + } +}; + diff --git a/src/network/packet/UseItemPacket.h b/src/network/packet/UseItemPacket.h index e1583de..e4f58a3 100755 --- a/src/network/packet/UseItemPacket.h +++ b/src/network/packet/UseItemPacket.h @@ -1,86 +1,84 @@ -#ifndef NET_MINECRAFT_NETWORK_PACKET__UseItemPacket_H__ -#define NET_MINECRAFT_NETWORK_PACKET__UseItemPacket_H__ - -//package net.minecraft.network.packet; - -#include "../Packet.h" - -#include "../../world/item/ItemInstance.h" - -class UseItemPacket: public Packet -{ -public: - int x, y, z, face; - float clickX, clickY, clickZ; - int entityId; - short itemId; - unsigned char itemData; - ItemInstance item; - - UseItemPacket() {} - - UseItemPacket(int x, int y, int z, int face, const ItemInstance* item, int entityId, float clickX, float clickY, float clickZ) - : x(x), - y(y), - z(z), - face(face), - itemId(item? item->id : 0), - itemData(item? item->getAuxValue() : 0), - entityId(entityId), - clickX(clickX), - clickY(clickY), - clickZ(clickZ) - {} - - UseItemPacket(const ItemInstance* item, int entityId, const Vec3& aim) - : face(255), - itemId(item? item->id : 0), - itemData(item? item->getAuxValue() : 0), - entityId(entityId), - x((int)(aim.x * 32768.0f)), - y((int)(aim.y * 32768.0f)), - z((int)(aim.z * 32768.0f)) - { - } - - void write(RakNet::BitStream* bitStream) - { - bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_USEITEM)); - - bitStream->Write(x); - bitStream->Write(y); - bitStream->Write(z); - bitStream->Write(face); - bitStream->Write(itemId); - bitStream->Write(itemData); - bitStream->Write(entityId); - bitStream->Write(clickX); - bitStream->Write(clickY); - bitStream->Write(clickZ); - } - - void read(RakNet::BitStream* bitStream) - { - bitStream->Read(x); - bitStream->Read(y); - bitStream->Read(z); - bitStream->Read(face); - bitStream->Read(itemId); - bitStream->Read(itemData); - bitStream->Read(entityId); - bitStream->Read(clickX); - bitStream->Read(clickY); - bitStream->Read(clickZ); - item.id = itemId; - item.setAuxValue(itemData); - item.count = (itemId == 0 && itemData == 0)? 0 : 1; - - } - - void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) - { - callback->handle(source, (UseItemPacket*)this); - } -}; - -#endif /*NET_MINECRAFT_NETWORK_PACKET__UseItemPacket_H__*/ +#pragma once + +//package net.minecraft.network.packet; + +#include "../Packet.h" + +#include "../../world/item/ItemInstance.h" + +class UseItemPacket: public Packet +{ +public: + int x, y, z, face; + float clickX, clickY, clickZ; + int entityId; + short itemId; + unsigned char itemData; + ItemInstance item; + + UseItemPacket() {} + + UseItemPacket(int x, int y, int z, int face, const ItemInstance* item, int entityId, float clickX, float clickY, float clickZ) + : x(x), + y(y), + z(z), + face(face), + itemId(item? item->id : 0), + itemData(item? item->getAuxValue() : 0), + entityId(entityId), + clickX(clickX), + clickY(clickY), + clickZ(clickZ) + {} + + UseItemPacket(const ItemInstance* item, int entityId, const Vec3& aim) + : face(255), + itemId(item? item->id : 0), + itemData(item? item->getAuxValue() : 0), + entityId(entityId), + x((int)(aim.x * 32768.0f)), + y((int)(aim.y * 32768.0f)), + z((int)(aim.z * 32768.0f)) + { + } + + void write(RakNet::BitStream* bitStream) + { + bitStream->Write((RakNet::MessageID)(ID_USER_PACKET_ENUM + PACKET_USEITEM)); + + bitStream->Write(x); + bitStream->Write(y); + bitStream->Write(z); + bitStream->Write(face); + bitStream->Write(itemId); + bitStream->Write(itemData); + bitStream->Write(entityId); + bitStream->Write(clickX); + bitStream->Write(clickY); + bitStream->Write(clickZ); + } + + void read(RakNet::BitStream* bitStream) + { + bitStream->Read(x); + bitStream->Read(y); + bitStream->Read(z); + bitStream->Read(face); + bitStream->Read(itemId); + bitStream->Read(itemData); + bitStream->Read(entityId); + bitStream->Read(clickX); + bitStream->Read(clickY); + bitStream->Read(clickZ); + item.id = itemId; + item.setAuxValue(itemData); + item.count = (itemId == 0 && itemData == 0)? 0 : 1; + + } + + void handle(const RakNet::RakNetGUID& source, NetEventCallback* callback) + { + callback->handle(source, (UseItemPacket*)this); + } +}; + diff --git a/src/platform/HttpClient.h b/src/platform/HttpClient.h index 68f3c96..a44621c 100644 --- a/src/platform/HttpClient.h +++ b/src/platform/HttpClient.h @@ -1,5 +1,4 @@ -#ifndef HTTPCLIENT_H__ -#define HTTPCLIENT_H__ +#pragma once #include #include @@ -10,4 +9,3 @@ bool download(const std::string& url, std::vector& outBody); } // namespace HttpClient -#endif /* HTTPCLIENT_H__ */ diff --git a/src/platform/PngLoader.h b/src/platform/PngLoader.h index cc1d0a4..8dd62c4 100644 --- a/src/platform/PngLoader.h +++ b/src/platform/PngLoader.h @@ -1,5 +1,4 @@ -#ifndef PNGLOADER_H__ -#define PNGLOADER_H__ +#pragma once #include "../client/renderer/TextureData.h" @@ -9,4 +8,3 @@ /// Returns an empty TextureData on failure. TextureData loadPngFromMemory(const unsigned char* data, size_t size); -#endif // PNGLOADER_H__ diff --git a/src/platform/android/AppPlatform_android.h b/src/platform/android/AppPlatform_android.h index 3f6c2ce..fd68f99 100755 --- a/src/platform/android/AppPlatform_android.h +++ b/src/platform/android/AppPlatform_android.h @@ -1,654 +1,652 @@ -#ifndef APPPLATFORM_ANDROID_H__ -#define APPPLATFORM_ANDROID_H__ - -#include -#include "client/renderer/gles.h" -#include "platform/log.h" -#include "platform/time.h" -#include -#include -#include -#include -class JVMAttacher { -public: - JVMAttacher(JavaVM* vm) - : _vm(vm), - _isAttached(false), - _env(NULL) - { - if( _vm->GetEnv((void**)&_env, JNI_VERSION_1_4 ) != JNI_OK ) { - _vm->AttachCurrentThread(&_env, NULL); - _isAttached = _env != NULL; - } - } - - ~JVMAttacher() { - forceDetach(); - } - - JNIEnv* getEnv() { - return _env; - } - - void forceDetach() { - if (!_isAttached) return; - _vm->DetachCurrentThread(); - _isAttached = false; - } - -private: - JavaVM* _vm; - JNIEnv* _env; - bool _isAttached; -}; - -class AppPlatform_android: public AppPlatform -{ - typedef AppPlatform super; -public: - AppPlatform_android() - : _vm(NULL), - _isInited(false), - - instance(0), - _activityClass(0), - - _methodSaveScreenshot(0), - _postScreenshotToFacebook(0), - _getImageData(0), - _readAssetFile(0), - _methodPlaySound(0), - _showDialog(0), - _methodTick(0), - _methodFinish(0), - - _methodUserInputInitiate(0), - _methodUserInputStatus(0), - _methodUserInputString(0), - - _methodGetDateString(0), - - _methodVibrate(0), - _methodSupportsTouchscreen(0), - _methodSetIsPowerVR(0), - _methodIsNetworkEnabled(0), - - _getScreenWidth(0), - _getScreenHeight(0), - _methodGetPixelsPerMillimeter(0), - _methodGetPlatformStringVar(0), - - _classWindow(0), - _classContext(0), - _fieldINPUT_METHOD_SERVICE(0), - _classInputManager(0), - _methodGetSystemService(0), - _methodGetWindow(0), - _methodGetDecorView(0), - _methodShowSoftInput(0), - _classView(0), - _methodGetWindowToken(0), - _methodHideSoftInput(0), - - _screenWidth(854), - _screenHeight(480), - _hasSetPowerVR(false), - _nativeActivity(0), - - _methodGetKeyFromKeyCode(0) - { - } - - int getScreenWidth() { return _screenWidth; } - int getScreenHeight() { return _screenHeight; } - void setScreenDimensions(int w, int h) { _screenWidth = w; _screenHeight = h; } - - // Note, this has to be called from the main thread (e.g. do it from JNI_onLoad) - // Somewhere between calling this, and calling the AppPlatform methods, - // this->instance will be assigned by its creator - int init(JavaVM* vm) { - if (_isInited) - return -1; - - JVMAttacher ta(vm); - JNIEnv* env = ta.getEnv(); - - if(!env) { - LOGI("%s - Failed to get the environment using JVMAttacher::getEnv()", __FUNCTION__); - return -2; - } - - // Get Class reference - const char* interface_path = "com/mojang/minecraftpe/MainActivity"; - jclass clazz = NULL; - if( (clazz = env->FindClass( interface_path )) == 0 ) { - return -3; - } - _activityClass = (jclass)env->NewGlobalRef(clazz); - - // Save all the method IDs - _methodSaveScreenshot = env->GetStaticMethodID( _activityClass, "saveScreenshot", "(Ljava/lang/String;II[I)V"); - _postScreenshotToFacebook = env->GetMethodID( _activityClass, "postScreenshotToFacebook", "(Ljava/lang/String;II[I)V"); - _getImageData = env->GetMethodID( _activityClass, "getImageData", "(Ljava/lang/String;)[I"); - _readAssetFile = env->GetMethodID( _activityClass, "getFileDataBytes", "(Ljava/lang/String;)[B"); - #if defined(PRE_ANDROID23) - _methodPlaySound = env->GetMethodID( _activityClass, "playSound", "(Ljava/lang/String;FF)V"); - #endif - _showDialog = env->GetMethodID( _activityClass, "displayDialog", "(I)V"); - _methodTick = env->GetMethodID( _activityClass, "tick", "()V"); - _methodFinish = env->GetMethodID( _activityClass, "quit", "()V"); - - _methodUserInputInitiate = env->GetMethodID( _activityClass, "initiateUserInput", "(I)V"); - _methodUserInputStatus = env->GetMethodID( _activityClass, "getUserInputStatus", "()I"); - _methodUserInputString = env->GetMethodID( _activityClass, "getUserInputString", "()[Ljava/lang/String;"); - - _methodGetDateString = env->GetMethodID( _activityClass, "getDateString", "(I)Ljava/lang/String;"); - - _methodVibrate = env->GetMethodID( _activityClass, "vibrate", "(I)V"); - _methodSupportsTouchscreen = env->GetMethodID( _activityClass, "supportsTouchscreen", "()Z"); - _methodSetIsPowerVR = env->GetMethodID( _activityClass, "setIsPowerVR", "(Z)V"); - _methodIsNetworkEnabled = env->GetMethodID( _activityClass, "isNetworkEnabled", "(Z)Z"); - - _methodGetPixelsPerMillimeter = env->GetMethodID( _activityClass, "getPixelsPerMillimeter", "()F"); - _methodGetPlatformStringVar = env->GetMethodID( _activityClass, "getPlatformStringVar", "(I)Ljava/lang/String;"); - // custom helper to launch external URLs - _methodOpenURL = env->GetMethodID(_activityClass, "openURL", "(Ljava/lang/String;)V"); - - _classWindow = (jclass)env->NewGlobalRef(env->FindClass("android/view/Window")); - _classContext = (jclass)env->NewGlobalRef(env->FindClass("android/content/Context")); - _classView = (jclass)env->NewGlobalRef(env->FindClass( "android/view/View")); - _classInputManager = (jclass)env->NewGlobalRef(env->FindClass("android/view/inputmethod/InputMethodManager")); - - _fieldINPUT_METHOD_SERVICE = env->GetStaticFieldID(_classContext, "INPUT_METHOD_SERVICE", "Ljava/lang/String;"); - _methodGetSystemService = env->GetMethodID(_activityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); - _methodGetWindow = env->GetMethodID( _activityClass, "getWindow", "()Landroid/view/Window;"); - _methodGetDecorView = env->GetMethodID(_classWindow, "getDecorView", "()Landroid/view/View;"); - _methodShowSoftInput = env->GetMethodID(_classInputManager, "showSoftInput", "(Landroid/view/View;I)Z"); - _methodGetWindowToken = env->GetMethodID(_classView, "getWindowToken", "()Landroid/os/IBinder;"); - _methodHideSoftInput = env->GetMethodID(_classInputManager, "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z"); - - _methodGetKeyFromKeyCode = env->GetMethodID( _activityClass, "getKeyFromKeyCode", "(III)I"); - - if (env->ExceptionOccurred()) { - env->ExceptionDescribe(); - } - - // LOGI("Class: %d\n. Methods: %d,%d\n", _activityClass, - // _methodSaveScreenshot, - // _postScreenshotToFacebook); - - _vm = vm; - _isInited = true; - - return JNI_VERSION_1_4; - } - - // Stuff that should only be written once, e.g. device specs - // @note: This is called after instance is set, BUT this will - // be rewritten later on anyway - int initConsts() { - - LOGI("initConsts: start\n"); - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - LOGI("initConsts: getting method IDs\n"); - jmethodID fWidth = env->GetMethodID( _activityClass, "getScreenWidth", "()I"); - LOGI("initConsts: got fWidth=%p\n", fWidth); - jmethodID fHeight = env->GetMethodID( _activityClass, "getScreenHeight", "()I"); - LOGI("initConsts: got fHeight=%p, calling getScreenWidth\n", fHeight); - - _screenWidth = env->CallIntMethod(instance, fWidth); - LOGI("initConsts: screenWidth=%d, calling getScreenHeight\n", _screenWidth); - _screenHeight = env->CallIntMethod(instance, fHeight); - LOGI("initConsts: screenHeight=%d, done\n", _screenHeight); - - return 1; - } - - void tick() { - if (!_isInited) return; - if (!_methodTick) return; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - env->CallVoidMethod(instance, _methodTick); - } - - void showDialog(int dialogId) { - if (!_isInited) return; - if (!_showDialog) return; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - env->CallVoidMethod(instance, _showDialog, dialogId); - } - - void createUserInput() { - if (!_isInited) return; - if (!_methodUserInputInitiate) return; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - env->CallVoidMethod(instance, _methodUserInputInitiate, 1); - } - - int getUserInputStatus() { - if (!_isInited) return -2; - if (!_methodUserInputStatus) return -2; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - return env->CallIntMethod(instance, _methodUserInputStatus); - } - - float getPixelsPerMillimeter() { - if (!_isInited) return 10; - if (!_methodGetPixelsPerMillimeter) return 10; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - return env->CallFloatMethod(instance, _methodGetPixelsPerMillimeter); - } - - StringVector getUserInput() { - if (!_isInited) return std::vector(); - if (!_methodUserInputString) return std::vector(); - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - jobjectArray sa = (jobjectArray) env->CallObjectMethod(instance, _methodUserInputString); - jsize len = env->GetArrayLength(sa); - - StringVector out; - for (int i = 0; i < len; ++i) { - - jstring s = (jstring)env->GetObjectArrayElement(sa, i); - int length = env->GetStringLength (s); - if (length > 1023) - length = 1023; - static char buf[1024]; - - // Only supporting 7 bit chars, right now - const char* str = env->GetStringUTFChars(s, 0); - strncpy(buf, str, 1023); - buf[1023] = 0; - - out.push_back(std::string(buf)); - } - return out; - } - - void saveScreenshot(const std::string& filename, int glWidth, int glHeight) { - if (!_isInited) return; - if (!_methodSaveScreenshot) return; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - const int numPixels = glWidth * glHeight; - unsigned int* pixels = new unsigned int[numPixels]; - - if (!pixels) - return; - - // Create the OpenGL "screenshot" - glReadPixels(0, 0, glWidth, glHeight, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - convertOpenGlToAndroidPixels(glWidth, glHeight, pixels); - - // Tell Android to save the screenshot - jintArray jPixels = env->NewIntArray(numPixels); - if (jPixels != NULL) - { - jobject gpixRef = env->NewGlobalRef(jPixels); - env->SetIntArrayRegion(jPixels, 0, numPixels, (int*)pixels); -// env->CallVoidMethod( instance, -// _postScreenshotToFacebook, -// env->NewStringUTF(filename.c_str()), -// glWidth, glHeight, jPixels); - env->CallStaticVoidMethod( _activityClass, - _methodSaveScreenshot, - env->NewStringUTF(filename.c_str()), - glWidth, glHeight, jPixels); - // Teardown - env->DeleteGlobalRef(gpixRef); - delete[] pixels; - } - } - - inline unsigned int rgbToBgr(unsigned int p) { - return (p & 0xff00ff00) | ((p >> 16) & 0xff) | ((p << 16) & 0xff0000); - } - - void convertOpenGlToAndroidPixels(int w, int h, unsigned int* pixels) { - // Making the conversion in-place - for (int y = 0; y < h/2; ++y) - for (int x = 0; x < w; ++x) { - const int i0 = y * w + x; - const int i1 = (h - y - 1) * w + x; - const unsigned int p1 = pixels[i1]; - const unsigned int p0 = pixels[i0]; - pixels[i0] = rgbToBgr(p1); - pixels[i1] = rgbToBgr(p0); - } - // Handle the middle row, if any - if (h & 1) { - const int start = w * h/2; - const int stop = start + w; - for (int i = start; i < stop; ++i) { - const unsigned int p = pixels[i]; - pixels[i] = rgbToBgr(p); - } - } - } - - virtual void playSound(const std::string& filename, float volume, float pitch) { - if (!_isInited || !_methodPlaySound) return; - - //static Stopwatch w; - //w.start(); - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - env->CallVoidMethod(instance, _methodPlaySound, env->NewStringUTF(filename.c_str()), volume, pitch); - //w.stop(); - //w.printEvery(1, "playSound-java"); - } - - virtual void uploadPlatformDependentData(int id, void* data) { - if (!_isInited) return; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - if (id == 1) { - } - if (id == 2) { - } - } - - TextureData loadTexture(const std::string& filename, bool textureFolder) { - if (!_isInited) return TextureData(); - if (!_getImageData) return TextureData(); - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - std::string path = textureFolder ? "images/" + filename : filename; - jintArray arr = (jintArray)env->CallObjectMethod( - instance, _getImageData, env->NewStringUTF(path.c_str())); - - if (!arr) - return TextureData(); - - jsize len = env->GetArrayLength(arr); - int numPixels = len-2; - - // pixels = [width, height, p_0, p_1, ..., p_numPixels-1] - int* pixels = new int[numPixels]; - jint* body = env->GetIntArrayElements(arr, 0); - - int w = body[0]; - int h = body[1]; - memcpy(pixels, &body[2], numPixels * sizeof(int)); - - // Convert pixels - for (int i = 0; i < numPixels; ++i) - pixels[i] = rgbToBgr(pixels[i]); - - //LOGI("Read-Image-Data: Decided file size to be: %d x %d (len %d)\n", w, h, len); - - env->ReleaseIntArrayElements(arr, body, 0); - // LOGI("loadtexture: 9\n"); - - // Set the result - TextureData out; - out.w = w; - out.h = h; - out.data = (unsigned char*)pixels; - out.memoryHandledExternally = false; - return out; - } - - BinaryBlob readAssetFile(const std::string& filename) { - if (!_isInited) return BinaryBlob(); - if (!_readAssetFile) return BinaryBlob(); - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - jbyteArray arr = (jbyteArray)env->CallObjectMethod( - instance, _readAssetFile, env->NewStringUTF(filename.c_str())); - - if (!arr) - return BinaryBlob(); - - jsize len = env->GetArrayLength(arr); - BinaryBlob blob(new unsigned char[len], len); - jbyte* body = env->GetByteArrayElements(arr, 0); - memcpy(blob.data, body, len); - - env->ReleaseByteArrayElements(arr, body, 0); - return blob; - } - - std::string getDateString(int s) { - if (!_isInited) return ""; - if (!_methodGetDateString) return ""; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - std::string out; - jstring dateString = (jstring)env->CallObjectMethod(instance, _methodGetDateString, s); - const char* str = env->GetStringUTFChars(dateString, NULL); - if (str) - out = str; - env->ReleaseStringUTFChars(dateString, str); - return out; - } - - std::string getPlatformStringVar(int s) { - if (!_isInited) return ""; - if (!_methodGetPlatformStringVar) return ""; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - std::string out; - jstring stringVar = (jstring)env->CallObjectMethod(instance, _methodGetPlatformStringVar, s); - const char* str = env->GetStringUTFChars(stringVar, NULL); - if (str) - out = str; - env->ReleaseStringUTFChars(stringVar, str); - return out; - } - // Opens a webpage using an Android intent. Called from native code. - virtual void openURL(const std::string& url) { - if (!_isInited || !_methodOpenURL) return; - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - jstring jurl = env->NewStringUTF(url.c_str()); - env->CallVoidMethod(instance, _methodOpenURL, jurl); - env->DeleteLocalRef(jurl); - } - virtual void finish() { - if (!_isInited) return; - if (!_methodFinish) return; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - env->CallVoidMethod(instance, _methodFinish); - env->DeleteGlobalRef( _activityClass ); - - env->DeleteGlobalRef( _classWindow ); - env->DeleteGlobalRef( _classContext ); - env->DeleteGlobalRef( _classView ); - env->DeleteGlobalRef( _classInputManager ); - } - - virtual bool supportsTouchscreen() { - if (!_isInited) return true; - if (!_methodSupportsTouchscreen) return true; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - return env->CallBooleanMethod(instance, _methodSupportsTouchscreen); - } - - virtual void vibrate(int milliSeconds) { - if (!_isInited) return; - if (!_methodVibrate) return; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - return env->CallVoidMethod(instance, _methodVibrate, milliSeconds); - } - - virtual bool isPowerVR() { - bool is = super::isPowerVR(); - - if (_methodSetIsPowerVR && _isInited && !_hasSetPowerVR ) { - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - _hasSetPowerVR = true; - env->CallVoidMethod(instance, _methodSetIsPowerVR, is); - } - return is; - } - - virtual bool isNetworkEnabled(bool onlyWifiAllowed) { - if (!_isInited) return false; - if (!_methodIsNetworkEnabled) return false; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - return env->CallBooleanMethod(instance, _methodIsNetworkEnabled, onlyWifiAllowed); - } - - static inline bool isSquare(int n) { - int L = n & 0xf; - if (((1 << L) & 0x213) == 0) return false; - - int t = (int) sqrt((double) n) + 0.5; - return t*t == n; - } - - virtual void showKeyboard() { - showKeyboard(true); - super::showKeyboard(); - } - virtual void hideKeyboard() { - showKeyboard(false); - super::hideKeyboard(); - } - virtual void showKeyboard(bool bShow) { - if (!_isInited) return; - - jint lResult = 0; - jint lFlags = 0; - - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - jobject INPUT_METHOD_SERVICE = - env->GetStaticObjectField(_classContext, - _fieldINPUT_METHOD_SERVICE); - - jobject lInputMethodManager = env->CallObjectMethod( - instance, _methodGetSystemService, - INPUT_METHOD_SERVICE); - - jobject lWindow = env->CallObjectMethod(instance, - _methodGetWindow); - - jobject lDecorView = env->CallObjectMethod(lWindow, - _methodGetDecorView); - - if (bShow) { - // Runs lInputMethodManager.showSoftInput(...). - jboolean lResult = env->CallBooleanMethod( - lInputMethodManager, _methodShowSoftInput, - lDecorView, lFlags); - } else { - // Runs lWindow.getViewToken() - jobject lBinder = env->CallObjectMethod(lDecorView, - _methodGetWindowToken); - jboolean lRes = env->CallBooleanMethod( - lInputMethodManager, _methodHideSoftInput, - lBinder, lFlags); - } - } - virtual int getKeyFromKeyCode(int keyCode, int metaState, int deviceId) { - JVMAttacher ta(_vm); - JNIEnv* env = ta.getEnv(); - - return (int) env->CallIntMethod(instance, _methodGetKeyFromKeyCode, keyCode, metaState, deviceId); - } -public: - jobject instance; - -private: - bool _isInited; - JavaVM* _vm; - - jclass _activityClass; - - jmethodID _methodSaveScreenshot; - jmethodID _postScreenshotToFacebook; - jmethodID _getImageData; - jmethodID _readAssetFile; - jmethodID _methodPlaySound; - jmethodID _showDialog; - jmethodID _methodTick; - jmethodID _methodFinish; - - jmethodID _methodUserInputInitiate; - jmethodID _methodUserInputStatus; - jmethodID _methodUserInputString; - - jmethodID _methodGetDateString; - - jmethodID _getScreenWidth; - jmethodID _getScreenHeight; - jmethodID _methodGetPixelsPerMillimeter; - jmethodID _methodVibrate; - jmethodID _methodSupportsTouchscreen; - jmethodID _methodSetIsPowerVR; - jmethodID _methodIsNetworkEnabled; - - jmethodID _methodGetPlatformStringVar; - jmethodID _methodOpenURL; // new JNI method for launching browser - - jclass _classWindow; - jclass _classContext; - jfieldID _fieldINPUT_METHOD_SERVICE; - jclass _classInputManager; - jmethodID _methodGetSystemService; - jmethodID _methodGetWindow; - jmethodID _methodGetDecorView; - jmethodID _methodShowSoftInput; - jclass _classView; - jmethodID _methodGetWindowToken; - jmethodID _methodHideSoftInput; - - jmethodID _methodGetKeyFromKeyCode; - - int _screenWidth; - int _screenHeight; - bool _hasSetPowerVR; -public: - ANativeActivity* _nativeActivity; -}; - -#endif /*APPPLATFORM_ANDROID_H__*/ +#pragma once + +#include +#include "client/renderer/gles.h" +#include "platform/log.h" +#include "platform/time.h" +#include +#include +#include +#include +class JVMAttacher { +public: + JVMAttacher(JavaVM* vm) + : _vm(vm), + _isAttached(false), + _env(NULL) + { + if( _vm->GetEnv((void**)&_env, JNI_VERSION_1_4 ) != JNI_OK ) { + _vm->AttachCurrentThread(&_env, NULL); + _isAttached = _env != NULL; + } + } + + ~JVMAttacher() { + forceDetach(); + } + + JNIEnv* getEnv() { + return _env; + } + + void forceDetach() { + if (!_isAttached) return; + _vm->DetachCurrentThread(); + _isAttached = false; + } + +private: + JavaVM* _vm; + JNIEnv* _env; + bool _isAttached; +}; + +class AppPlatform_android: public AppPlatform +{ + typedef AppPlatform super; +public: + AppPlatform_android() + : _vm(NULL), + _isInited(false), + + instance(0), + _activityClass(0), + + _methodSaveScreenshot(0), + _postScreenshotToFacebook(0), + _getImageData(0), + _readAssetFile(0), + _methodPlaySound(0), + _showDialog(0), + _methodTick(0), + _methodFinish(0), + + _methodUserInputInitiate(0), + _methodUserInputStatus(0), + _methodUserInputString(0), + + _methodGetDateString(0), + + _methodVibrate(0), + _methodSupportsTouchscreen(0), + _methodSetIsPowerVR(0), + _methodIsNetworkEnabled(0), + + _getScreenWidth(0), + _getScreenHeight(0), + _methodGetPixelsPerMillimeter(0), + _methodGetPlatformStringVar(0), + + _classWindow(0), + _classContext(0), + _fieldINPUT_METHOD_SERVICE(0), + _classInputManager(0), + _methodGetSystemService(0), + _methodGetWindow(0), + _methodGetDecorView(0), + _methodShowSoftInput(0), + _classView(0), + _methodGetWindowToken(0), + _methodHideSoftInput(0), + + _screenWidth(854), + _screenHeight(480), + _hasSetPowerVR(false), + _nativeActivity(0), + + _methodGetKeyFromKeyCode(0) + { + } + + int getScreenWidth() { return _screenWidth; } + int getScreenHeight() { return _screenHeight; } + void setScreenDimensions(int w, int h) { _screenWidth = w; _screenHeight = h; } + + // Note, this has to be called from the main thread (e.g. do it from JNI_onLoad) + // Somewhere between calling this, and calling the AppPlatform methods, + // this->instance will be assigned by its creator + int init(JavaVM* vm) { + if (_isInited) + return -1; + + JVMAttacher ta(vm); + JNIEnv* env = ta.getEnv(); + + if(!env) { + LOGI("%s - Failed to get the environment using JVMAttacher::getEnv()", __FUNCTION__); + return -2; + } + + // Get Class reference + const char* interface_path = "com/mojang/minecraftpe/MainActivity"; + jclass clazz = NULL; + if( (clazz = env->FindClass( interface_path )) == 0 ) { + return -3; + } + _activityClass = (jclass)env->NewGlobalRef(clazz); + + // Save all the method IDs + _methodSaveScreenshot = env->GetStaticMethodID( _activityClass, "saveScreenshot", "(Ljava/lang/String;II[I)V"); + _postScreenshotToFacebook = env->GetMethodID( _activityClass, "postScreenshotToFacebook", "(Ljava/lang/String;II[I)V"); + _getImageData = env->GetMethodID( _activityClass, "getImageData", "(Ljava/lang/String;)[I"); + _readAssetFile = env->GetMethodID( _activityClass, "getFileDataBytes", "(Ljava/lang/String;)[B"); + #if defined(PRE_ANDROID23) + _methodPlaySound = env->GetMethodID( _activityClass, "playSound", "(Ljava/lang/String;FF)V"); + #endif + _showDialog = env->GetMethodID( _activityClass, "displayDialog", "(I)V"); + _methodTick = env->GetMethodID( _activityClass, "tick", "()V"); + _methodFinish = env->GetMethodID( _activityClass, "quit", "()V"); + + _methodUserInputInitiate = env->GetMethodID( _activityClass, "initiateUserInput", "(I)V"); + _methodUserInputStatus = env->GetMethodID( _activityClass, "getUserInputStatus", "()I"); + _methodUserInputString = env->GetMethodID( _activityClass, "getUserInputString", "()[Ljava/lang/String;"); + + _methodGetDateString = env->GetMethodID( _activityClass, "getDateString", "(I)Ljava/lang/String;"); + + _methodVibrate = env->GetMethodID( _activityClass, "vibrate", "(I)V"); + _methodSupportsTouchscreen = env->GetMethodID( _activityClass, "supportsTouchscreen", "()Z"); + _methodSetIsPowerVR = env->GetMethodID( _activityClass, "setIsPowerVR", "(Z)V"); + _methodIsNetworkEnabled = env->GetMethodID( _activityClass, "isNetworkEnabled", "(Z)Z"); + + _methodGetPixelsPerMillimeter = env->GetMethodID( _activityClass, "getPixelsPerMillimeter", "()F"); + _methodGetPlatformStringVar = env->GetMethodID( _activityClass, "getPlatformStringVar", "(I)Ljava/lang/String;"); + // custom helper to launch external URLs + _methodOpenURL = env->GetMethodID(_activityClass, "openURL", "(Ljava/lang/String;)V"); + + _classWindow = (jclass)env->NewGlobalRef(env->FindClass("android/view/Window")); + _classContext = (jclass)env->NewGlobalRef(env->FindClass("android/content/Context")); + _classView = (jclass)env->NewGlobalRef(env->FindClass( "android/view/View")); + _classInputManager = (jclass)env->NewGlobalRef(env->FindClass("android/view/inputmethod/InputMethodManager")); + + _fieldINPUT_METHOD_SERVICE = env->GetStaticFieldID(_classContext, "INPUT_METHOD_SERVICE", "Ljava/lang/String;"); + _methodGetSystemService = env->GetMethodID(_activityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); + _methodGetWindow = env->GetMethodID( _activityClass, "getWindow", "()Landroid/view/Window;"); + _methodGetDecorView = env->GetMethodID(_classWindow, "getDecorView", "()Landroid/view/View;"); + _methodShowSoftInput = env->GetMethodID(_classInputManager, "showSoftInput", "(Landroid/view/View;I)Z"); + _methodGetWindowToken = env->GetMethodID(_classView, "getWindowToken", "()Landroid/os/IBinder;"); + _methodHideSoftInput = env->GetMethodID(_classInputManager, "hideSoftInputFromWindow", "(Landroid/os/IBinder;I)Z"); + + _methodGetKeyFromKeyCode = env->GetMethodID( _activityClass, "getKeyFromKeyCode", "(III)I"); + + if (env->ExceptionOccurred()) { + env->ExceptionDescribe(); + } + + // LOGI("Class: %d\n. Methods: %d,%d\n", _activityClass, + // _methodSaveScreenshot, + // _postScreenshotToFacebook); + + _vm = vm; + _isInited = true; + + return JNI_VERSION_1_4; + } + + // Stuff that should only be written once, e.g. device specs + // @note: This is called after instance is set, BUT this will + // be rewritten later on anyway + int initConsts() { + + LOGI("initConsts: start\n"); + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + LOGI("initConsts: getting method IDs\n"); + jmethodID fWidth = env->GetMethodID( _activityClass, "getScreenWidth", "()I"); + LOGI("initConsts: got fWidth=%p\n", fWidth); + jmethodID fHeight = env->GetMethodID( _activityClass, "getScreenHeight", "()I"); + LOGI("initConsts: got fHeight=%p, calling getScreenWidth\n", fHeight); + + _screenWidth = env->CallIntMethod(instance, fWidth); + LOGI("initConsts: screenWidth=%d, calling getScreenHeight\n", _screenWidth); + _screenHeight = env->CallIntMethod(instance, fHeight); + LOGI("initConsts: screenHeight=%d, done\n", _screenHeight); + + return 1; + } + + void tick() { + if (!_isInited) return; + if (!_methodTick) return; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + env->CallVoidMethod(instance, _methodTick); + } + + void showDialog(int dialogId) { + if (!_isInited) return; + if (!_showDialog) return; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + env->CallVoidMethod(instance, _showDialog, dialogId); + } + + void createUserInput() { + if (!_isInited) return; + if (!_methodUserInputInitiate) return; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + env->CallVoidMethod(instance, _methodUserInputInitiate, 1); + } + + int getUserInputStatus() { + if (!_isInited) return -2; + if (!_methodUserInputStatus) return -2; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + return env->CallIntMethod(instance, _methodUserInputStatus); + } + + float getPixelsPerMillimeter() { + if (!_isInited) return 10; + if (!_methodGetPixelsPerMillimeter) return 10; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + return env->CallFloatMethod(instance, _methodGetPixelsPerMillimeter); + } + + StringVector getUserInput() { + if (!_isInited) return std::vector(); + if (!_methodUserInputString) return std::vector(); + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + jobjectArray sa = (jobjectArray) env->CallObjectMethod(instance, _methodUserInputString); + jsize len = env->GetArrayLength(sa); + + StringVector out; + for (int i = 0; i < len; ++i) { + + jstring s = (jstring)env->GetObjectArrayElement(sa, i); + int length = env->GetStringLength (s); + if (length > 1023) + length = 1023; + static char buf[1024]; + + // Only supporting 7 bit chars, right now + const char* str = env->GetStringUTFChars(s, 0); + strncpy(buf, str, 1023); + buf[1023] = 0; + + out.push_back(std::string(buf)); + } + return out; + } + + void saveScreenshot(const std::string& filename, int glWidth, int glHeight) { + if (!_isInited) return; + if (!_methodSaveScreenshot) return; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + const int numPixels = glWidth * glHeight; + unsigned int* pixels = new unsigned int[numPixels]; + + if (!pixels) + return; + + // Create the OpenGL "screenshot" + glReadPixels(0, 0, glWidth, glHeight, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + convertOpenGlToAndroidPixels(glWidth, glHeight, pixels); + + // Tell Android to save the screenshot + jintArray jPixels = env->NewIntArray(numPixels); + if (jPixels != NULL) + { + jobject gpixRef = env->NewGlobalRef(jPixels); + env->SetIntArrayRegion(jPixels, 0, numPixels, (int*)pixels); +// env->CallVoidMethod( instance, +// _postScreenshotToFacebook, +// env->NewStringUTF(filename.c_str()), +// glWidth, glHeight, jPixels); + env->CallStaticVoidMethod( _activityClass, + _methodSaveScreenshot, + env->NewStringUTF(filename.c_str()), + glWidth, glHeight, jPixels); + // Teardown + env->DeleteGlobalRef(gpixRef); + delete[] pixels; + } + } + + inline unsigned int rgbToBgr(unsigned int p) { + return (p & 0xff00ff00) | ((p >> 16) & 0xff) | ((p << 16) & 0xff0000); + } + + void convertOpenGlToAndroidPixels(int w, int h, unsigned int* pixels) { + // Making the conversion in-place + for (int y = 0; y < h/2; ++y) + for (int x = 0; x < w; ++x) { + const int i0 = y * w + x; + const int i1 = (h - y - 1) * w + x; + const unsigned int p1 = pixels[i1]; + const unsigned int p0 = pixels[i0]; + pixels[i0] = rgbToBgr(p1); + pixels[i1] = rgbToBgr(p0); + } + // Handle the middle row, if any + if (h & 1) { + const int start = w * h/2; + const int stop = start + w; + for (int i = start; i < stop; ++i) { + const unsigned int p = pixels[i]; + pixels[i] = rgbToBgr(p); + } + } + } + + virtual void playSound(const std::string& filename, float volume, float pitch) { + if (!_isInited || !_methodPlaySound) return; + + //static Stopwatch w; + //w.start(); + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + env->CallVoidMethod(instance, _methodPlaySound, env->NewStringUTF(filename.c_str()), volume, pitch); + //w.stop(); + //w.printEvery(1, "playSound-java"); + } + + virtual void uploadPlatformDependentData(int id, void* data) { + if (!_isInited) return; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + if (id == 1) { + } + if (id == 2) { + } + } + + TextureData loadTexture(const std::string& filename, bool textureFolder) { + if (!_isInited) return TextureData(); + if (!_getImageData) return TextureData(); + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + std::string path = textureFolder ? "images/" + filename : filename; + jintArray arr = (jintArray)env->CallObjectMethod( + instance, _getImageData, env->NewStringUTF(path.c_str())); + + if (!arr) + return TextureData(); + + jsize len = env->GetArrayLength(arr); + int numPixels = len-2; + + // pixels = [width, height, p_0, p_1, ..., p_numPixels-1] + int* pixels = new int[numPixels]; + jint* body = env->GetIntArrayElements(arr, 0); + + int w = body[0]; + int h = body[1]; + memcpy(pixels, &body[2], numPixels * sizeof(int)); + + // Convert pixels + for (int i = 0; i < numPixels; ++i) + pixels[i] = rgbToBgr(pixels[i]); + + //LOGI("Read-Image-Data: Decided file size to be: %d x %d (len %d)\n", w, h, len); + + env->ReleaseIntArrayElements(arr, body, 0); + // LOGI("loadtexture: 9\n"); + + // Set the result + TextureData out; + out.w = w; + out.h = h; + out.data = (unsigned char*)pixels; + out.memoryHandledExternally = false; + return out; + } + + BinaryBlob readAssetFile(const std::string& filename) { + if (!_isInited) return BinaryBlob(); + if (!_readAssetFile) return BinaryBlob(); + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + jbyteArray arr = (jbyteArray)env->CallObjectMethod( + instance, _readAssetFile, env->NewStringUTF(filename.c_str())); + + if (!arr) + return BinaryBlob(); + + jsize len = env->GetArrayLength(arr); + BinaryBlob blob(new unsigned char[len], len); + jbyte* body = env->GetByteArrayElements(arr, 0); + memcpy(blob.data, body, len); + + env->ReleaseByteArrayElements(arr, body, 0); + return blob; + } + + std::string getDateString(int s) { + if (!_isInited) return ""; + if (!_methodGetDateString) return ""; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + std::string out; + jstring dateString = (jstring)env->CallObjectMethod(instance, _methodGetDateString, s); + const char* str = env->GetStringUTFChars(dateString, NULL); + if (str) + out = str; + env->ReleaseStringUTFChars(dateString, str); + return out; + } + + std::string getPlatformStringVar(int s) { + if (!_isInited) return ""; + if (!_methodGetPlatformStringVar) return ""; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + std::string out; + jstring stringVar = (jstring)env->CallObjectMethod(instance, _methodGetPlatformStringVar, s); + const char* str = env->GetStringUTFChars(stringVar, NULL); + if (str) + out = str; + env->ReleaseStringUTFChars(stringVar, str); + return out; + } + // Opens a webpage using an Android intent. Called from native code. + virtual void openURL(const std::string& url) { + if (!_isInited || !_methodOpenURL) return; + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + jstring jurl = env->NewStringUTF(url.c_str()); + env->CallVoidMethod(instance, _methodOpenURL, jurl); + env->DeleteLocalRef(jurl); + } + virtual void finish() { + if (!_isInited) return; + if (!_methodFinish) return; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + env->CallVoidMethod(instance, _methodFinish); + env->DeleteGlobalRef( _activityClass ); + + env->DeleteGlobalRef( _classWindow ); + env->DeleteGlobalRef( _classContext ); + env->DeleteGlobalRef( _classView ); + env->DeleteGlobalRef( _classInputManager ); + } + + virtual bool supportsTouchscreen() { + if (!_isInited) return true; + if (!_methodSupportsTouchscreen) return true; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + return env->CallBooleanMethod(instance, _methodSupportsTouchscreen); + } + + virtual void vibrate(int milliSeconds) { + if (!_isInited) return; + if (!_methodVibrate) return; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + return env->CallVoidMethod(instance, _methodVibrate, milliSeconds); + } + + virtual bool isPowerVR() { + bool is = super::isPowerVR(); + + if (_methodSetIsPowerVR && _isInited && !_hasSetPowerVR ) { + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + _hasSetPowerVR = true; + env->CallVoidMethod(instance, _methodSetIsPowerVR, is); + } + return is; + } + + virtual bool isNetworkEnabled(bool onlyWifiAllowed) { + if (!_isInited) return false; + if (!_methodIsNetworkEnabled) return false; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + return env->CallBooleanMethod(instance, _methodIsNetworkEnabled, onlyWifiAllowed); + } + + static inline bool isSquare(int n) { + int L = n & 0xf; + if (((1 << L) & 0x213) == 0) return false; + + int t = (int) sqrt((double) n) + 0.5; + return t*t == n; + } + + virtual void showKeyboard() { + showKeyboard(true); + super::showKeyboard(); + } + virtual void hideKeyboard() { + showKeyboard(false); + super::hideKeyboard(); + } + virtual void showKeyboard(bool bShow) { + if (!_isInited) return; + + jint lResult = 0; + jint lFlags = 0; + + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + jobject INPUT_METHOD_SERVICE = + env->GetStaticObjectField(_classContext, + _fieldINPUT_METHOD_SERVICE); + + jobject lInputMethodManager = env->CallObjectMethod( + instance, _methodGetSystemService, + INPUT_METHOD_SERVICE); + + jobject lWindow = env->CallObjectMethod(instance, + _methodGetWindow); + + jobject lDecorView = env->CallObjectMethod(lWindow, + _methodGetDecorView); + + if (bShow) { + // Runs lInputMethodManager.showSoftInput(...). + jboolean lResult = env->CallBooleanMethod( + lInputMethodManager, _methodShowSoftInput, + lDecorView, lFlags); + } else { + // Runs lWindow.getViewToken() + jobject lBinder = env->CallObjectMethod(lDecorView, + _methodGetWindowToken); + jboolean lRes = env->CallBooleanMethod( + lInputMethodManager, _methodHideSoftInput, + lBinder, lFlags); + } + } + virtual int getKeyFromKeyCode(int keyCode, int metaState, int deviceId) { + JVMAttacher ta(_vm); + JNIEnv* env = ta.getEnv(); + + return (int) env->CallIntMethod(instance, _methodGetKeyFromKeyCode, keyCode, metaState, deviceId); + } +public: + jobject instance; + +private: + bool _isInited; + JavaVM* _vm; + + jclass _activityClass; + + jmethodID _methodSaveScreenshot; + jmethodID _postScreenshotToFacebook; + jmethodID _getImageData; + jmethodID _readAssetFile; + jmethodID _methodPlaySound; + jmethodID _showDialog; + jmethodID _methodTick; + jmethodID _methodFinish; + + jmethodID _methodUserInputInitiate; + jmethodID _methodUserInputStatus; + jmethodID _methodUserInputString; + + jmethodID _methodGetDateString; + + jmethodID _getScreenWidth; + jmethodID _getScreenHeight; + jmethodID _methodGetPixelsPerMillimeter; + jmethodID _methodVibrate; + jmethodID _methodSupportsTouchscreen; + jmethodID _methodSetIsPowerVR; + jmethodID _methodIsNetworkEnabled; + + jmethodID _methodGetPlatformStringVar; + jmethodID _methodOpenURL; // new JNI method for launching browser + + jclass _classWindow; + jclass _classContext; + jfieldID _fieldINPUT_METHOD_SERVICE; + jclass _classInputManager; + jmethodID _methodGetSystemService; + jmethodID _methodGetWindow; + jmethodID _methodGetDecorView; + jmethodID _methodShowSoftInput; + jclass _classView; + jmethodID _methodGetWindowToken; + jmethodID _methodHideSoftInput; + + jmethodID _methodGetKeyFromKeyCode; + + int _screenWidth; + int _screenHeight; + bool _hasSetPowerVR; +public: + ANativeActivity* _nativeActivity; +}; + diff --git a/src/platform/audio/SoundSystem.h b/src/platform/audio/SoundSystem.h index 7576e9f..845e299 100755 --- a/src/platform/audio/SoundSystem.h +++ b/src/platform/audio/SoundSystem.h @@ -1,29 +1,27 @@ -#ifndef SoundSystem_H__ -#define SoundSystem_H__ - -#include "../../world/level/tile/Tile.h" -#include - -class SoundDesc; - -class SoundSystem -{ -public: - SoundSystem() {} - virtual ~SoundSystem() {} - - virtual bool isAvailable() { return false; } - virtual void enable(bool status) {} - - virtual void setListenerPos(float x, float y, float z){} - virtual void setListenerAngle(float deg){} - - virtual void load(const std::string& name){} - virtual void play(const std::string& name){} - virtual void pause(const std::string& name){} - virtual void stop(const std::string& name){} - - virtual void playAt(const SoundDesc& desc, float x, float y, float z, float volume, float pitch){} -}; - -#endif /*SoundSystem_H__ */ +#pragma once + +#include "../../world/level/tile/Tile.h" +#include + +class SoundDesc; + +class SoundSystem +{ +public: + SoundSystem() {} + virtual ~SoundSystem() {} + + virtual bool isAvailable() { return false; } + virtual void enable(bool status) {} + + virtual void setListenerPos(float x, float y, float z){} + virtual void setListenerAngle(float deg){} + + virtual void load(const std::string& name){} + virtual void play(const std::string& name){} + virtual void pause(const std::string& name){} + virtual void stop(const std::string& name){} + + virtual void playAt(const SoundDesc& desc, float x, float y, float z, float volume, float pitch){} +}; + diff --git a/src/platform/audio/SoundSystemAL.h b/src/platform/audio/SoundSystemAL.h index ca0ac7f..48d78f6 100755 --- a/src/platform/audio/SoundSystemAL.h +++ b/src/platform/audio/SoundSystemAL.h @@ -1,73 +1,71 @@ -#ifndef SoundSystemAL_H__ -#define SoundSystemAL_H__ - -#include "SoundSystem.h" - -#include -#include - -#include -#include - -// -// NOTE: This class is only the core OpenAL part of the sound engine. -// Some audio setup code can still be managed from respective app -// setup code (e.g. the main app delegate for iOS). -// - -class SoundSystemAL: public SoundSystem -{ - //typedef std::list SoundList; -public: - SoundSystemAL(); - ~SoundSystemAL(); - - virtual void init(); - virtual void destroy(); - - virtual void enable(bool status); - - virtual void setListenerPos(float x, float y, float z); - virtual void setListenerAngle(float deg); - - virtual void load(const std::string& name){} - virtual void play(const std::string& name){} - virtual void pause(const std::string& name){} - virtual void stop(const std::string& name){} - virtual void playAt(const SoundDesc& sound, float x, float y, float z, float volume, float pitch); - -private: - class Buffer { - public: - Buffer() - : inited(false) - {} - bool inited; - ALuint bufferID; - char* framePtr; - }; - - void removeStoppedSounds(); - - static const int MaxNumSources = 12; - - //SoundList playingBuffers; - - Vec3 _listenerPos; - float _rotation; - - bool available; - - ALCcontext* context; - ALCdevice* device; - - ALuint _sources[MaxNumSources]; - std::vector _buffers; - - bool getFreeSourceIndex(int* src); - bool getBufferId(const SoundDesc& sound, ALuint* buf); - -public: -}; - -#endif /*SoundSystemAL_H__ */ +#pragma once + +#include "SoundSystem.h" + +#include +#include + +#include +#include + +// +// NOTE: This class is only the core OpenAL part of the sound engine. +// Some audio setup code can still be managed from respective app +// setup code (e.g. the main app delegate for iOS). +// + +class SoundSystemAL: public SoundSystem +{ + //typedef std::list SoundList; +public: + SoundSystemAL(); + ~SoundSystemAL(); + + virtual void init(); + virtual void destroy(); + + virtual void enable(bool status); + + virtual void setListenerPos(float x, float y, float z); + virtual void setListenerAngle(float deg); + + virtual void load(const std::string& name){} + virtual void play(const std::string& name){} + virtual void pause(const std::string& name){} + virtual void stop(const std::string& name){} + virtual void playAt(const SoundDesc& sound, float x, float y, float z, float volume, float pitch); + +private: + class Buffer { + public: + Buffer() + : inited(false) + {} + bool inited; + ALuint bufferID; + char* framePtr; + }; + + void removeStoppedSounds(); + + static const int MaxNumSources = 12; + + //SoundList playingBuffers; + + Vec3 _listenerPos; + float _rotation; + + bool available; + + ALCcontext* context; + ALCdevice* device; + + ALuint _sources[MaxNumSources]; + std::vector _buffers; + + bool getFreeSourceIndex(int* src); + bool getBufferId(const SoundDesc& sound, ALuint* buf); + +public: +}; + diff --git a/src/platform/audio/SoundSystemSL.h b/src/platform/audio/SoundSystemSL.h index 0606d91..b7afacb 100755 --- a/src/platform/audio/SoundSystemSL.h +++ b/src/platform/audio/SoundSystemSL.h @@ -1,79 +1,77 @@ -#ifndef SoundSystemSL_H__ -#define SoundSystemSL_H__ - -#include "SoundSystem.h" -#include -#include - -#include -#include - -#ifdef ANDROID -#include -class Mutex { - pthread_mutex_t _mutex; -public: - Mutex() { pthread_mutex_init(&_mutex, NULL); } - ~Mutex() { pthread_mutex_destroy(&_mutex); } - void lock() { pthread_mutex_lock(&_mutex); } - void unlock() { pthread_mutex_unlock(&_mutex); } -}; -#else -class Mutex { -public: - Mutex() {} - void lock() {} - void unlock() {}; -}; -#endif - - -class SoundSystemSL: public SoundSystem -{ - typedef std::list SoundList; -public: - SoundSystemSL(); - ~SoundSystemSL(); - - virtual void init(); - virtual void destroy(); - - virtual void setListenerPos(float x, float y, float z); - virtual void setListenerAngle(float deg); - - virtual void load(const std::string& name){} - virtual void play(const std::string& name){} - virtual void pause(const std::string& name){} - virtual void stop(const std::string& name){} - virtual void playAt(const SoundDesc& sound, float x, float y, float z, float volume, float pitch); - -private: - bool checkErr( SLresult res ); - - void removeStoppedSounds(); - - SoundList playingBuffers; - - static SLObjectItf objEngine; - SLEngineItf engEngine; - - SLObjectItf objListener; - SL3DLocationItf listener; - - SLObjectItf objOutput; - - Vec3 listenerPos; - int numBuffersPlaying; - - bool available; - std::vector toRemoveCopy; - - static Mutex toRemoveMutex; - static std::vector toRemove; - static const int MAX_BUFFERS_PLAYING = 4; - -public: - static void removePlayer(SLAndroidSimpleBufferQueueItf bq, void *context); -}; - -#endif /*SoundSystemSL_H__ */ +#pragma once + +#include "SoundSystem.h" +#include +#include + +#include +#include + +#ifdef ANDROID +#include +class Mutex { + pthread_mutex_t _mutex; +public: + Mutex() { pthread_mutex_init(&_mutex, NULL); } + ~Mutex() { pthread_mutex_destroy(&_mutex); } + void lock() { pthread_mutex_lock(&_mutex); } + void unlock() { pthread_mutex_unlock(&_mutex); } +}; +#else +class Mutex { +public: + Mutex() {} + void lock() {} + void unlock() {}; +}; +#endif + + +class SoundSystemSL: public SoundSystem +{ + typedef std::list SoundList; +public: + SoundSystemSL(); + ~SoundSystemSL(); + + virtual void init(); + virtual void destroy(); + + virtual void setListenerPos(float x, float y, float z); + virtual void setListenerAngle(float deg); + + virtual void load(const std::string& name){} + virtual void play(const std::string& name){} + virtual void pause(const std::string& name){} + virtual void stop(const std::string& name){} + virtual void playAt(const SoundDesc& sound, float x, float y, float z, float volume, float pitch); + +private: + bool checkErr( SLresult res ); + + void removeStoppedSounds(); + + SoundList playingBuffers; + + static SLObjectItf objEngine; + SLEngineItf engEngine; + + SLObjectItf objListener; + SL3DLocationItf listener; + + SLObjectItf objOutput; + + Vec3 listenerPos; + int numBuffersPlaying; + + bool available; + std::vector toRemoveCopy; + + static Mutex toRemoveMutex; + static std::vector toRemove; + static const int MAX_BUFFERS_PLAYING = 4; + +public: + static void removePlayer(SLAndroidSimpleBufferQueueItf bq, void *context); +}; + diff --git a/src/platform/file.h b/src/platform/file.h index af57bee..b60cba2 100755 --- a/src/platform/file.h +++ b/src/platform/file.h @@ -1,68 +1,66 @@ -#ifndef FILE_H__ -#define FILE_H__ - -bool DeleteDirectory(const std::string&, bool noRecycleBin = true); - -#ifdef WIN32 - #include - #include - #include - #include - -bool DeleteDirectory(const std::string& dir, bool noRecycleBin /*true*/) -{ - int len = strlen(dir.c_str()); - //TCHAR *pszFrom = new TCHAR[len+2]; - char* pszFrom = new char[len+2]; - strncpy(pszFrom, dir.c_str(), len); - pszFrom[len] = 0; - pszFrom[len+1] = 0; - - SHFILEOPSTRUCT fileop; - fileop.hwnd = NULL; // no status display - fileop.wFunc = FO_DELETE; // delete operation - fileop.pFrom = pszFrom; // source file name as double null terminated string - fileop.pTo = NULL; // no destination needed - fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT; // do not prompt the user - - if(!noRecycleBin) - fileop.fFlags |= FOF_ALLOWUNDO; - - fileop.fAnyOperationsAborted = FALSE; - fileop.lpszProgressTitle = NULL; - fileop.hNameMappings = NULL; - - int ret = SHFileOperation(&fileop); - delete [] pszFrom; - return (ret == 0); -} -#else - #include - #include - -bool DeleteDirectory(const std::string& d, bool noRecycleBin /*true*/) -{ - const char* folder = d.c_str(); - - const size_t CMAX = 1024; - char fullPath[CMAX]; - DIR* dir = opendir(folder); - if (!dir) - return false; - - struct dirent *entry; - while ((entry = readdir(dir))) { - if (strcmp(".", entry->d_name) && strcmp("..", entry->d_name)) { - snprintf(fullPath, CMAX, "%s/%s", folder, entry->d_name); - remove(fullPath); - } - } - - closedir(dir); - - return remove(folder) == 0; -} - -#endif /*(ELSE) WIN32*/ - -#endif /*FILE_H__*/ +#pragma once + +bool DeleteDirectory(const std::string&, bool noRecycleBin = true); + +#ifdef WIN32 + #include + #include + #include + #include + +bool DeleteDirectory(const std::string& dir, bool noRecycleBin /*true*/) +{ + int len = strlen(dir.c_str()); + //TCHAR *pszFrom = new TCHAR[len+2]; + char* pszFrom = new char[len+2]; + strncpy(pszFrom, dir.c_str(), len); + pszFrom[len] = 0; + pszFrom[len+1] = 0; + + SHFILEOPSTRUCT fileop; + fileop.hwnd = NULL; // no status display + fileop.wFunc = FO_DELETE; // delete operation + fileop.pFrom = pszFrom; // source file name as double null terminated string + fileop.pTo = NULL; // no destination needed + fileop.fFlags = FOF_NOCONFIRMATION|FOF_SILENT; // do not prompt the user + + if(!noRecycleBin) + fileop.fFlags |= FOF_ALLOWUNDO; + + fileop.fAnyOperationsAborted = FALSE; + fileop.lpszProgressTitle = NULL; + fileop.hNameMappings = NULL; + + int ret = SHFileOperation(&fileop); + delete [] pszFrom; + return (ret == 0); +} +#else + #include + #include + +bool DeleteDirectory(const std::string& d, bool noRecycleBin /*true*/) +{ + const char* folder = d.c_str(); + + const size_t CMAX = 1024; + char fullPath[CMAX]; + DIR* dir = opendir(folder); + if (!dir) + return false; + + struct dirent *entry; + while ((entry = readdir(dir))) { + if (strcmp(".", entry->d_name) && strcmp("..", entry->d_name)) { + snprintf(fullPath, CMAX, "%s/%s", folder, entry->d_name); + remove(fullPath); + } + } + + closedir(dir); + + return remove(folder) == 0; +} + +#endif /*(ELSE) WIN32*/ + diff --git a/src/platform/glfw/PlatformGlfw.h b/src/platform/glfw/PlatformGlfw.h index dfae27a..349a39b 100755 --- a/src/platform/glfw/PlatformGlfw.h +++ b/src/platform/glfw/PlatformGlfw.h @@ -1,75 +1,73 @@ -#ifndef APPPLATFORM_GLFW_H__ -#define APPPLATFORM_GLFW_H__ - -#include -#include "platform/log.h" -#include "platform/HttpClient.h" -#include "platform/PngLoader.h" -#include "client/renderer/gles.h" -#include "world/level/storage/FolderMethods.h" -#include -#include - -#ifdef __EMSCRIPTEN__ - #include -#endif - -class PlatformGlfw : public IPlatform { -public: - bool init() override; - void finish() override; - - TextureData loadTexture(const std::string& filename_, bool textureFolder) override; - - TextureData loadTextureFromMemory(const unsigned char* data, size_t size) override { return loadPngFromMemory(data, size); } - - std::string getDateString(int s) override; - - int getScreenWidth() override { - #ifdef __EMSCRIPTEN__ - int w, h; - emscripten_get_canvas_element_size("canvas", &w, &h); - - return w; - #endif - - return 854; - }; - - int getScreenHeight() override { - #ifdef __EMSCRIPTEN__ - int w, h; - emscripten_get_canvas_element_size("canvas", &w, &h); - - return h; - #endif - - return 480; - }; - - float getPixelsPerMillimeter() override; - - bool supportsTouchscreen() override { return false; /* glfw supports only mouse and keyboard */ } - - void hideCursor(bool hide) override; - - void openURL(const std::string& url) override; - - void swapBuffers() override; - - void setVSync(bool on) override; - -private: - static int transformKey(int glfwkey); - - static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); - static void character_callback(GLFWwindow* window, unsigned int codepoint); - static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos); - static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); - static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); - static void window_size_callback(GLFWwindow* window, int width, int height); - static void error_callback(int error, const char* desc); - - GLFWwindow* m_window; -}; -#endif /*APPPLATFORM_GLFW_H__*/ +#pragma once + +#include +#include "platform/log.h" +#include "platform/HttpClient.h" +#include "platform/PngLoader.h" +#include "client/renderer/gles.h" +#include "world/level/storage/FolderMethods.h" +#include +#include + +#ifdef __EMSCRIPTEN__ + #include +#endif + +class PlatformGlfw : public IPlatform { +public: + bool init() override; + void finish() override; + + TextureData loadTexture(const std::string& filename_, bool textureFolder) override; + + TextureData loadTextureFromMemory(const unsigned char* data, size_t size) override { return loadPngFromMemory(data, size); } + + std::string getDateString(int s) override; + + int getScreenWidth() override { + #ifdef __EMSCRIPTEN__ + int w, h; + emscripten_get_canvas_element_size("canvas", &w, &h); + + return w; + #endif + + return 854; + }; + + int getScreenHeight() override { + #ifdef __EMSCRIPTEN__ + int w, h; + emscripten_get_canvas_element_size("canvas", &w, &h); + + return h; + #endif + + return 480; + }; + + float getPixelsPerMillimeter() override; + + bool supportsTouchscreen() override { return false; /* glfw supports only mouse and keyboard */ } + + void hideCursor(bool hide) override; + + void openURL(const std::string& url) override; + + void swapBuffers() override; + + void setVSync(bool on) override; + +private: + static int transformKey(int glfwkey); + + static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); + static void character_callback(GLFWwindow* window, unsigned int codepoint); + static void cursor_position_callback(GLFWwindow* window, double xpos, double ypos); + static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); + static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); + static void window_size_callback(GLFWwindow* window, int width, int height); + static void error_callback(int error, const char* desc); + + GLFWwindow* m_window; +}; diff --git a/src/platform/input/Controller.h b/src/platform/input/Controller.h index 49ae289..9fa13bc 100755 --- a/src/platform/input/Controller.h +++ b/src/platform/input/Controller.h @@ -1,33 +1,31 @@ -#ifndef CONTROLLER_H__ -#define CONTROLLER_H__ - -#include "../log.h" - -class Controller -{ -public: - static const int NUM_STICKS = 2; - static const int STATE_TOUCH = 1; - static const int STATE_RELEASE = 0; - static const int STATE_MOVE =-1; - - static bool isTouched(int stickIndex); - - static void feed(int stickIndex, int state, float dx, float dy); - - static float getX(int stickIndex); - static float getY(int stickIndex); - - static float getTransformedX(int stickIndex, float deadZone, float scale=1.0f, bool limit1=false); - static float getTransformedY(int stickIndex, float deadZone, float scale=1.0f, bool limit1=false); - -private: - static bool isValidStick(int stick); - static float linearTransform(float value, float deadZone, float scale=1.0f, bool limit1=false); - - static float stickValuesX[NUM_STICKS]; - static float stickValuesY[NUM_STICKS]; - static bool isTouchedValues[NUM_STICKS]; -}; - -#endif /*CONTROLLER_H__*/ +#pragma once + +#include "../log.h" + +class Controller +{ +public: + static const int NUM_STICKS = 2; + static const int STATE_TOUCH = 1; + static const int STATE_RELEASE = 0; + static const int STATE_MOVE =-1; + + static bool isTouched(int stickIndex); + + static void feed(int stickIndex, int state, float dx, float dy); + + static float getX(int stickIndex); + static float getY(int stickIndex); + + static float getTransformedX(int stickIndex, float deadZone, float scale=1.0f, bool limit1=false); + static float getTransformedY(int stickIndex, float deadZone, float scale=1.0f, bool limit1=false); + +private: + static bool isValidStick(int stick); + static float linearTransform(float value, float deadZone, float scale=1.0f, bool limit1=false); + + static float stickValuesX[NUM_STICKS]; + static float stickValuesY[NUM_STICKS]; + static bool isTouchedValues[NUM_STICKS]; +}; + diff --git a/src/platform/input/Keyboard.h b/src/platform/input/Keyboard.h index 91868a0..2995649 100755 --- a/src/platform/input/Keyboard.h +++ b/src/platform/input/Keyboard.h @@ -1,142 +1,140 @@ -#ifndef KEYBOARD_H__ -#define KEYBOARD_H__ - -#include - -/** A keyboard action; key-down or key-up */ -class KeyboardAction -{ -public: - static const int KEYUP = 0; - static const int KEYDOWN = 1; - - KeyboardAction(unsigned char keyCode, int state) { - this->key = keyCode; - this->state = state; - } - - int state; - unsigned char key; -}; - -/* Iterators */ -typedef std::vector KeyboardActionVec; -typedef KeyboardActionVec::iterator KeyboardActionIt; -typedef KeyboardActionVec::const_iterator KeyboardActionCIt; - -/** A static keyboard class, written to resemble the one in lwjgl somewhat */ -class Keyboard -{ -public: - static const int KEY_A = 65; - static const int KEY_B = 66; - static const int KEY_C = 67; - static const int KEY_D = 68; - static const int KEY_E = 69; - static const int KEY_F = 70; - static const int KEY_G = 71; - static const int KEY_H = 72; - static const int KEY_I = 73; - static const int KEY_J = 74; - static const int KEY_K = 75; - static const int KEY_L = 76; - static const int KEY_M = 77; - static const int KEY_N = 78; - static const int KEY_O = 79; - static const int KEY_P = 80; - static const int KEY_Q = 81; - static const int KEY_R = 82; - static const int KEY_S = 83; - static const int KEY_T = 84; - static const int KEY_U = 85; - static const int KEY_V = 86; - static const int KEY_W = 87; - static const int KEY_X = 88; - static const int KEY_Y = 89; - static const int KEY_Z = 90; - - static const int KEY_BACKSPACE = 8; - static const int KEY_TAB = 9; - static const int KEY_RETURN = 13; - - static const int KEY_F1 = 112; - static const int KEY_F2 = 113; - static const int KEY_F3 = 114; - static const int KEY_F4 = 115; - static const int KEY_F5 = 116; - static const int KEY_F6 = 117; - static const int KEY_F7 = 118; - static const int KEY_F8 = 119; - static const int KEY_F9 = 120; - static const int KEY_F10 = 121; - static const int KEY_F11 = 122; - static const int KEY_F12 = 123; - - - static const int KEY_ESCAPE = 27; - static const int KEY_SPACE = 32; - static const int KEY_LSHIFT = 10; - static const int KEY_LEFT_CTRL = 232; - - static bool isKeyDown(int keyCode) { - return _states[keyCode] == KeyboardAction::KEYDOWN; - } - - static void reset() { - _inputs.clear(); - _inputText.clear(); - _index = -1; - _textIndex = -1; - } - - static void feed(unsigned char keyCode, int state) { - _inputs.push_back(KeyboardAction(keyCode, state)); - - _states[keyCode] = state; - } - static void feedText(char character) { - _inputText.push_back(character); - } - - static bool next() { - if (_index + 1 >= (int)_inputs.size()) - return false; - - ++_index; - return true; - } - - static bool nextTextChar() { - if(_textIndex + 1 >= (int)_inputText.size()) - return false; - ++_textIndex; - return true; - } - - static void rewind() { - _index = -1; - _textIndex = -1; - } - - static int getEventKey() { - return _inputs[_index].key; - } - - static int getEventKeyState() { - return _inputs[_index].state; - } - static char getChar() { - return _inputText[_textIndex]; - } - - static const char* getKeyName(int key); -private: - static int _index; - static int _textIndex; - static int _states[256]; - static std::vector _inputs; - static std::vector _inputText; - static bool _inited; -}; - -#endif//KEYBOARD_H__ +#pragma once + +#include + +/** A keyboard action; key-down or key-up */ +class KeyboardAction +{ +public: + static const int KEYUP = 0; + static const int KEYDOWN = 1; + + KeyboardAction(unsigned char keyCode, int state) { + this->key = keyCode; + this->state = state; + } + + int state; + unsigned char key; +}; + +/* Iterators */ +typedef std::vector KeyboardActionVec; +typedef KeyboardActionVec::iterator KeyboardActionIt; +typedef KeyboardActionVec::const_iterator KeyboardActionCIt; + +/** A static keyboard class, written to resemble the one in lwjgl somewhat */ +class Keyboard +{ +public: + static const int KEY_A = 65; + static const int KEY_B = 66; + static const int KEY_C = 67; + static const int KEY_D = 68; + static const int KEY_E = 69; + static const int KEY_F = 70; + static const int KEY_G = 71; + static const int KEY_H = 72; + static const int KEY_I = 73; + static const int KEY_J = 74; + static const int KEY_K = 75; + static const int KEY_L = 76; + static const int KEY_M = 77; + static const int KEY_N = 78; + static const int KEY_O = 79; + static const int KEY_P = 80; + static const int KEY_Q = 81; + static const int KEY_R = 82; + static const int KEY_S = 83; + static const int KEY_T = 84; + static const int KEY_U = 85; + static const int KEY_V = 86; + static const int KEY_W = 87; + static const int KEY_X = 88; + static const int KEY_Y = 89; + static const int KEY_Z = 90; + + static const int KEY_BACKSPACE = 8; + static const int KEY_TAB = 9; + static const int KEY_RETURN = 13; + + static const int KEY_F1 = 112; + static const int KEY_F2 = 113; + static const int KEY_F3 = 114; + static const int KEY_F4 = 115; + static const int KEY_F5 = 116; + static const int KEY_F6 = 117; + static const int KEY_F7 = 118; + static const int KEY_F8 = 119; + static const int KEY_F9 = 120; + static const int KEY_F10 = 121; + static const int KEY_F11 = 122; + static const int KEY_F12 = 123; + + + static const int KEY_ESCAPE = 27; + static const int KEY_SPACE = 32; + static const int KEY_LSHIFT = 10; + static const int KEY_LEFT_CTRL = 232; + + static bool isKeyDown(int keyCode) { + return _states[keyCode] == KeyboardAction::KEYDOWN; + } + + static void reset() { + _inputs.clear(); + _inputText.clear(); + _index = -1; + _textIndex = -1; + } + + static void feed(unsigned char keyCode, int state) { + _inputs.push_back(KeyboardAction(keyCode, state)); + + _states[keyCode] = state; + } + static void feedText(char character) { + _inputText.push_back(character); + } + + static bool next() { + if (_index + 1 >= (int)_inputs.size()) + return false; + + ++_index; + return true; + } + + static bool nextTextChar() { + if(_textIndex + 1 >= (int)_inputText.size()) + return false; + ++_textIndex; + return true; + } + + static void rewind() { + _index = -1; + _textIndex = -1; + } + + static int getEventKey() { + return _inputs[_index].key; + } + + static int getEventKeyState() { + return _inputs[_index].state; + } + static char getChar() { + return _inputText[_textIndex]; + } + + static const char* getKeyName(int key); +private: + static int _index; + static int _textIndex; + static int _states[256]; + static std::vector _inputs; + static std::vector _inputText; + static bool _inited; +}; + diff --git a/src/platform/input/Mouse.h b/src/platform/input/Mouse.h index f7caccc..096223e 100755 --- a/src/platform/input/Mouse.h +++ b/src/platform/input/Mouse.h @@ -1,112 +1,110 @@ -#ifndef MOUSE_H__ -#define MOUSE_H__ - -#include -#include "../log.h" - - -/** A mouse action such as a button press, release or mouse movement */ -class MouseAction -{ -public: - static const char ACTION_MOVE = 0; - static const char ACTION_LEFT = 1; - static const char ACTION_RIGHT = 2; - static const char ACTION_WHEEL = 3; - - static const char DATA_UP = 0; - static const char DATA_DOWN = 1; - - MouseAction(char actionButtonId, char buttonData, short x, short y, char pointerId); - MouseAction(char actionButtonId, char buttonData, short x, short y, short dx, short dy, char pointerId); - - bool isButton() const; - - short x, y; - short dx, dy; - char action; - char data; - char pointerId; -}; - -/* Iterators */ -typedef std::vector MouseActionVec; -typedef MouseActionVec::iterator MouseActionIt; -typedef MouseActionVec::const_iterator MouseActionCIt; - - -class MouseDevice -{ -public: - static const int MAX_NUM_BUTTONS = 4; - - MouseDevice(); - - char getButtonState(int buttonId); - bool isButtonDown(int buttonId); - - /// Was the current movement the first movement after mouse down? - bool wasFirstMovement(); - - short getX(); - short getY(); - - short getDX(); - short getDY(); - - void reset(); - void reset2(); - - bool next(); - void rewind(); - - bool getEventButtonState(); - char getEventButton(); - const MouseAction& getEvent(); - - void feed(char actionButtonId, char buttonData, short x, short y); - void feed(char actionButtonId, char buttonData, short x, short y, short dx, short dy); - -private: - int _index; - short _x, _y; - short _dx, _dy; - short _xOld, _yOld; - char _buttonStates[MAX_NUM_BUTTONS]; - std::vector _inputs; - int _firstMovementType; - static const int DELTA_NOTSET = -9999; -}; - -/** A static mouse class, written to resemble the one in lwjgl somewhat - UPDATE: which is very silly, since it doesn't support multi touch... */ -class Mouse -{ -public: - static char getButtonState(int buttonId); - static bool isButtonDown(int buttonId); - - static short getX(); - static short getY(); - - static short getDX(); - static short getDY(); - - static void reset(); - static void reset2(); - - static bool next(); - static void rewind(); - - static bool getEventButtonState(); - static char getEventButton(); - static const MouseAction& getEvent(); - - static void feed(char actionButtonId, char buttonData, short x, short y); - static void feed(char actionButtonId, char buttonData, short x, short y, short dx, short dy); - -private: - static MouseDevice _instance; -}; - -#endif//MOUSE_H__ +#pragma once + +#include +#include "../log.h" + + +/** A mouse action such as a button press, release or mouse movement */ +class MouseAction +{ +public: + static const char ACTION_MOVE = 0; + static const char ACTION_LEFT = 1; + static const char ACTION_RIGHT = 2; + static const char ACTION_WHEEL = 3; + + static const char DATA_UP = 0; + static const char DATA_DOWN = 1; + + MouseAction(char actionButtonId, char buttonData, short x, short y, char pointerId); + MouseAction(char actionButtonId, char buttonData, short x, short y, short dx, short dy, char pointerId); + + bool isButton() const; + + short x, y; + short dx, dy; + char action; + char data; + char pointerId; +}; + +/* Iterators */ +typedef std::vector MouseActionVec; +typedef MouseActionVec::iterator MouseActionIt; +typedef MouseActionVec::const_iterator MouseActionCIt; + + +class MouseDevice +{ +public: + static const int MAX_NUM_BUTTONS = 4; + + MouseDevice(); + + char getButtonState(int buttonId); + bool isButtonDown(int buttonId); + + /// Was the current movement the first movement after mouse down? + bool wasFirstMovement(); + + short getX(); + short getY(); + + short getDX(); + short getDY(); + + void reset(); + void reset2(); + + bool next(); + void rewind(); + + bool getEventButtonState(); + char getEventButton(); + const MouseAction& getEvent(); + + void feed(char actionButtonId, char buttonData, short x, short y); + void feed(char actionButtonId, char buttonData, short x, short y, short dx, short dy); + +private: + int _index; + short _x, _y; + short _dx, _dy; + short _xOld, _yOld; + char _buttonStates[MAX_NUM_BUTTONS]; + std::vector _inputs; + int _firstMovementType; + static const int DELTA_NOTSET = -9999; +}; + +/** A static mouse class, written to resemble the one in lwjgl somewhat + UPDATE: which is very silly, since it doesn't support multi touch... */ +class Mouse +{ +public: + static char getButtonState(int buttonId); + static bool isButtonDown(int buttonId); + + static short getX(); + static short getY(); + + static short getDX(); + static short getDY(); + + static void reset(); + static void reset2(); + + static bool next(); + static void rewind(); + + static bool getEventButtonState(); + static char getEventButton(); + static const MouseAction& getEvent(); + + static void feed(char actionButtonId, char buttonData, short x, short y); + static void feed(char actionButtonId, char buttonData, short x, short y, short dx, short dy); + +private: + static MouseDevice _instance; +}; + diff --git a/src/platform/input/Multitouch.h b/src/platform/input/Multitouch.h index 2b4390d..ba122ee 100755 --- a/src/platform/input/Multitouch.h +++ b/src/platform/input/Multitouch.h @@ -1,176 +1,174 @@ -#ifndef MULTITOUCH_H__ -#define MULTITOUCH_H__ - -#include "Mouse.h" -#include "../log.h" - -typedef MouseDevice TouchPointer; - -class Multitouch -{ -public: - static const int MAX_POINTERS = 12; - - static bool isPointerDown(int pointerId) { - return g(pointerId).isButtonDown(1); - } - - // Returns the first activeExtended (down OR released) pointer id - static int getFirstActivePointerIdEx() { - for (int i = 0; i < MAX_POINTERS; ++i) - if (_pointers[i].isButtonDown(1)) return i; - for (int i = 0; i < MAX_POINTERS; ++i) - if (_wasReleased[i]) return i; - return -1; - } - - // Returns the first activeExtended (down OR released) pointer id - // Compared to getFirstActivePointerIdEx, this method keeps the state the - // tick/render loop, while the former keeps it for a tick. - static int getFirstActivePointerIdExThisUpdate() { - for (int i = 0; i < MAX_POINTERS; ++i) - if (_pointers[i].isButtonDown(1)) return i; - for (int i = 0; i < MAX_POINTERS; ++i) - if (_wasReleasedThisUpdate[i]) return i; - return -1; - } - - // Get a list of all active (i.e. marked as touched/down) pointer ids - static int getActivePointerIds(const int** const ids) { - *ids = _activePointerList; - return _activePointerCount; - } - - // Get a list of all active (i.e. marked as touched/down) pointer ids - static int getActivePointerIdsThisUpdate(const int** const ids) { - *ids = _activePointerThisUpdateList; - return _activePointerThisUpdateCount; - } - - // Called when no more events will be pushed this update - static void commit() { - _activePointerCount = 0; - _activePointerThisUpdateCount = 0; - for (int i = 0; i < MAX_POINTERS; ++i) { - bool isDown = _pointers[i].isButtonDown(1); - if (isDown) { - _activePointerList[_activePointerCount++] = i; - _activePointerThisUpdateList[_activePointerThisUpdateCount++] = i; - } else if (_wasReleased[i]) { - _activePointerThisUpdateList[_activePointerThisUpdateCount++] = i; - } - } - } - - static short getX(int pointerId) { return g(pointerId).getX(); } - static short getY(int pointerId) { return g(pointerId).getY(); } - - static short getDX(int pointerId) { return g(pointerId).getDX(); } - static short getDY(int pointerId) { return g(pointerId).getDY(); } - - static bool wasFirstMovement(int pointerId) { return g(pointerId).wasFirstMovement(); } - - static bool isPressed(int pointerId) { - return _wasPressed[_clampPointerId(pointerId)]; - } - static bool isReleased(int pointerId) { - return _wasReleased[_clampPointerId(pointerId)]; - } - static bool isPressedThisUpdate(int pointerId) { - return _wasPressedThisUpdate[_clampPointerId(pointerId)]; - } - static bool isReleasedThisUpdate(int pointerId) { - return _wasReleasedThisUpdate[_clampPointerId(pointerId)]; - } - - static void reset() { - //LOGI("mtouch is reset\n"); - _inputs.clear(); - _index = -1; - - for (int i = 0; i < MAX_POINTERS; ++i) { - g(i).reset(); - - _wasPressed[i] = false; - _wasReleased[i] = false; - } - } - static void resetThisUpdate() { - for (int i = 0; i < MAX_POINTERS; ++i) { - _wasPressedThisUpdate[i] = false; - _wasReleasedThisUpdate[i] = false; - } - } - - static bool next() { - if (_index + 1 >= (int)_inputs.size()) - return false; - - ++_index; - return true; - } - - static void rewind() { - _index = -1; - } - - static MouseAction& getEvent() { - return _inputs[_index]; - } - - static void feed(char actionButtonId, char buttonData, short x, short y, char pointerId) { - pointerId = _clampPointerId(pointerId); - - _inputs.push_back(MouseAction(actionButtonId, buttonData, x, y, pointerId)); - g(pointerId).feed(actionButtonId, buttonData, x, y); - - if (actionButtonId > 0) { - if (buttonData == MouseAction::DATA_DOWN) { - _wasPressed[pointerId] = true; - _wasPressedThisUpdate[pointerId] = true; - //LOGI("isPressed %d %d\n", pointerId, isPressed(pointerId)); - } - else if (buttonData == MouseAction::DATA_UP) { - _wasReleased[pointerId] = true; - _wasReleasedThisUpdate[pointerId] = true; - //LOGI("isReleased %d %d\n", pointerId, isReleased(pointerId)); - } - } - } - - static int getMaxPointers() { - return MAX_POINTERS; - } - -private: - static TouchPointer& g(int pointerId) { - return _pointers[_clampPointerId(pointerId)]; - } - - static int _clampPointerId(int p) { - if (p < 0) return p; - if (p >= MAX_POINTERS) return MAX_POINTERS-1; - return p; - } - - // Between calls to reset() - static bool _wasPressed[MAX_POINTERS]; - static bool _wasReleased[MAX_POINTERS]; - - // Between calls to resetThisUpdate() - static bool _wasPressedThisUpdate[MAX_POINTERS]; - static bool _wasReleasedThisUpdate[MAX_POINTERS]; - - static TouchPointer _pointers[MAX_POINTERS]; - static std::vector _inputs; - - static int _activePointerList[MAX_POINTERS]; - static int _activePointerCount; - - static int _activePointerThisUpdateList[MAX_POINTERS]; - static int _activePointerThisUpdateCount; - - static int _index; -}; - -#endif /*MULTITOUCH_H__*/ +#pragma once + +#include "Mouse.h" +#include "../log.h" + +typedef MouseDevice TouchPointer; + +class Multitouch +{ +public: + static const int MAX_POINTERS = 12; + + static bool isPointerDown(int pointerId) { + return g(pointerId).isButtonDown(1); + } + + // Returns the first activeExtended (down OR released) pointer id + static int getFirstActivePointerIdEx() { + for (int i = 0; i < MAX_POINTERS; ++i) + if (_pointers[i].isButtonDown(1)) return i; + for (int i = 0; i < MAX_POINTERS; ++i) + if (_wasReleased[i]) return i; + return -1; + } + + // Returns the first activeExtended (down OR released) pointer id + // Compared to getFirstActivePointerIdEx, this method keeps the state the + // tick/render loop, while the former keeps it for a tick. + static int getFirstActivePointerIdExThisUpdate() { + for (int i = 0; i < MAX_POINTERS; ++i) + if (_pointers[i].isButtonDown(1)) return i; + for (int i = 0; i < MAX_POINTERS; ++i) + if (_wasReleasedThisUpdate[i]) return i; + return -1; + } + + // Get a list of all active (i.e. marked as touched/down) pointer ids + static int getActivePointerIds(const int** const ids) { + *ids = _activePointerList; + return _activePointerCount; + } + + // Get a list of all active (i.e. marked as touched/down) pointer ids + static int getActivePointerIdsThisUpdate(const int** const ids) { + *ids = _activePointerThisUpdateList; + return _activePointerThisUpdateCount; + } + + // Called when no more events will be pushed this update + static void commit() { + _activePointerCount = 0; + _activePointerThisUpdateCount = 0; + for (int i = 0; i < MAX_POINTERS; ++i) { + bool isDown = _pointers[i].isButtonDown(1); + if (isDown) { + _activePointerList[_activePointerCount++] = i; + _activePointerThisUpdateList[_activePointerThisUpdateCount++] = i; + } else if (_wasReleased[i]) { + _activePointerThisUpdateList[_activePointerThisUpdateCount++] = i; + } + } + } + + static short getX(int pointerId) { return g(pointerId).getX(); } + static short getY(int pointerId) { return g(pointerId).getY(); } + + static short getDX(int pointerId) { return g(pointerId).getDX(); } + static short getDY(int pointerId) { return g(pointerId).getDY(); } + + static bool wasFirstMovement(int pointerId) { return g(pointerId).wasFirstMovement(); } + + static bool isPressed(int pointerId) { + return _wasPressed[_clampPointerId(pointerId)]; + } + static bool isReleased(int pointerId) { + return _wasReleased[_clampPointerId(pointerId)]; + } + static bool isPressedThisUpdate(int pointerId) { + return _wasPressedThisUpdate[_clampPointerId(pointerId)]; + } + static bool isReleasedThisUpdate(int pointerId) { + return _wasReleasedThisUpdate[_clampPointerId(pointerId)]; + } + + static void reset() { + //LOGI("mtouch is reset\n"); + _inputs.clear(); + _index = -1; + + for (int i = 0; i < MAX_POINTERS; ++i) { + g(i).reset(); + + _wasPressed[i] = false; + _wasReleased[i] = false; + } + } + static void resetThisUpdate() { + for (int i = 0; i < MAX_POINTERS; ++i) { + _wasPressedThisUpdate[i] = false; + _wasReleasedThisUpdate[i] = false; + } + } + + static bool next() { + if (_index + 1 >= (int)_inputs.size()) + return false; + + ++_index; + return true; + } + + static void rewind() { + _index = -1; + } + + static MouseAction& getEvent() { + return _inputs[_index]; + } + + static void feed(char actionButtonId, char buttonData, short x, short y, char pointerId) { + pointerId = _clampPointerId(pointerId); + + _inputs.push_back(MouseAction(actionButtonId, buttonData, x, y, pointerId)); + g(pointerId).feed(actionButtonId, buttonData, x, y); + + if (actionButtonId > 0) { + if (buttonData == MouseAction::DATA_DOWN) { + _wasPressed[pointerId] = true; + _wasPressedThisUpdate[pointerId] = true; + //LOGI("isPressed %d %d\n", pointerId, isPressed(pointerId)); + } + else if (buttonData == MouseAction::DATA_UP) { + _wasReleased[pointerId] = true; + _wasReleasedThisUpdate[pointerId] = true; + //LOGI("isReleased %d %d\n", pointerId, isReleased(pointerId)); + } + } + } + + static int getMaxPointers() { + return MAX_POINTERS; + } + +private: + static TouchPointer& g(int pointerId) { + return _pointers[_clampPointerId(pointerId)]; + } + + static int _clampPointerId(int p) { + if (p < 0) return p; + if (p >= MAX_POINTERS) return MAX_POINTERS-1; + return p; + } + + // Between calls to reset() + static bool _wasPressed[MAX_POINTERS]; + static bool _wasReleased[MAX_POINTERS]; + + // Between calls to resetThisUpdate() + static bool _wasPressedThisUpdate[MAX_POINTERS]; + static bool _wasReleasedThisUpdate[MAX_POINTERS]; + + static TouchPointer _pointers[MAX_POINTERS]; + static std::vector _inputs; + + static int _activePointerList[MAX_POINTERS]; + static int _activePointerCount; + + static int _activePointerThisUpdateList[MAX_POINTERS]; + static int _activePointerThisUpdateCount; + + static int _index; +}; + diff --git a/src/platform/ios/AppPlatform_iOS.h b/src/platform/ios/AppPlatform_iOS.h index b9b87e1..52e3ac1 100755 --- a/src/platform/ios/AppPlatform_iOS.h +++ b/src/platform/ios/AppPlatform_iOS.h @@ -1,66 +1,64 @@ -#ifndef APPPLATFORM_IOS_H__ -#define APPPLATFORM_IOS_H__ - -#include -#include "client/renderer/gles.h" -#include "platform/log.h" -#include -#include -#include - -@class minecraftpeViewController; - -class AppPlatform_iOS: public AppPlatform -{ - typedef AppPlatform super; -public: - AppPlatform_iOS(minecraftpeViewController* vc) { - _viewController = vc; - srand(time(0)); - - LOGI("ViewController in AppPlatform: %p\n", _viewController); - } - - void setBasePath(const std::string& bp) { _basePath = bp; } - - void saveScreenshot(const std::string& filename, int glWidth, int glHeight) { - //@todo - } - - inline unsigned int rgbToBgr(unsigned int p) { - return (p & 0xff00ff00) | ((p >> 16) & 0xff) | ((p << 16) & 0xff0000); - } - - virtual void showDialog(int dialogId); - virtual int getUserInputStatus(); - virtual StringVector getUserInput(); - - TextureData loadTexture(const std::string& filename_, bool textureFolder); - - virtual BinaryBlob readAssetFile(const std::string& filename); - - std::string getDateString(int s); - - virtual int getScreenWidth(); - virtual int getScreenHeight(); - virtual float getPixelsPerMillimeter(); - - virtual bool isTouchscreen(); - virtual void vibrate(int milliSeconds); - - virtual bool isNetworkEnabled(bool onlyWifiAllowed); - - virtual StringVector getOptionStrings(); - - virtual bool isPowerVR() { return false; } - virtual bool isSuperFast(); - virtual void showKeyboard(); - virtual void hideKeyboard(); - virtual void isPowerVR(); -private: - - std::string _basePath; - minecraftpeViewController* _viewController; -}; - -#endif /*APPPLATFORM_IOS_H__*/ +#pragma once + +#include +#include "client/renderer/gles.h" +#include "platform/log.h" +#include +#include +#include + +@class minecraftpeViewController; + +class AppPlatform_iOS: public AppPlatform +{ + typedef AppPlatform super; +public: + AppPlatform_iOS(minecraftpeViewController* vc) { + _viewController = vc; + srand(time(0)); + + LOGI("ViewController in AppPlatform: %p\n", _viewController); + } + + void setBasePath(const std::string& bp) { _basePath = bp; } + + void saveScreenshot(const std::string& filename, int glWidth, int glHeight) { + //@todo + } + + inline unsigned int rgbToBgr(unsigned int p) { + return (p & 0xff00ff00) | ((p >> 16) & 0xff) | ((p << 16) & 0xff0000); + } + + virtual void showDialog(int dialogId); + virtual int getUserInputStatus(); + virtual StringVector getUserInput(); + + TextureData loadTexture(const std::string& filename_, bool textureFolder); + + virtual BinaryBlob readAssetFile(const std::string& filename); + + std::string getDateString(int s); + + virtual int getScreenWidth(); + virtual int getScreenHeight(); + virtual float getPixelsPerMillimeter(); + + virtual bool isTouchscreen(); + virtual void vibrate(int milliSeconds); + + virtual bool isNetworkEnabled(bool onlyWifiAllowed); + + virtual StringVector getOptionStrings(); + + virtual bool isPowerVR() { return false; } + virtual bool isSuperFast(); + virtual void showKeyboard(); + virtual void hideKeyboard(); + virtual void isPowerVR(); +private: + + std::string _basePath; + minecraftpeViewController* _viewController; +}; + diff --git a/src/platform/log.h b/src/platform/log.h index d660a90..721d461 100755 --- a/src/platform/log.h +++ b/src/platform/log.h @@ -1,47 +1,45 @@ -#ifndef LOG_H__ -#define LOG_H__ - -#ifdef __cplusplus - #include -#else - #include -#endif - -#define __LOG_PUBLISH(...) do { __VA_ARGS__; } while(0) - -#ifdef ANDROID - #include - #ifdef ANDROID_PUBLISH - #define LOGV(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) - #define LOGI(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) - #define LOGW(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) - #define LOGE(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) - #else - // @todo @fix; Obiously the tag shouldn't be hardcoded in here.. - #define LOGV(...) ((void)__android_log_print( ANDROID_LOG_VERBOSE, "MinecraftPE", __VA_ARGS__ )) - #define LOGI(...) ((void)__android_log_print( ANDROID_LOG_INFO, "MinecraftPE", __VA_ARGS__ )) - #define LOGW(...) ((void)__android_log_print( ANDROID_LOG_WARN, "MinecraftPE", __VA_ARGS__ )) - #define LOGE(...) ((void)__android_log_print( ANDROID_LOG_ERROR, "MinecraftPE", __VA_ARGS__ )) - #define printf LOGI - #endif -#else -#ifdef PUBLISH - #define LOGV(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) - #define LOGI(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) - #define LOGW(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) - #define LOGE(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) -#else - #define LOGV(...) (printf(__VA_ARGS__)) - #define LOGI(...) (printf(__VA_ARGS__)) - #define LOGW(...) (printf(__VA_ARGS__)) - #define LOGE(...) (printf(__VA_ARGS__)) -#endif -#endif - -#ifdef _DEBUG - #define LOGVV LOGV -#else - #define LOGVV(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) -#endif - -#endif /*LOG_H__*/ +#pragma once + +#ifdef __cplusplus + #include +#else + #include +#endif + +#define __LOG_PUBLISH(...) do { __VA_ARGS__; } while(0) + +#ifdef ANDROID + #include + #ifdef ANDROID_PUBLISH + #define LOGV(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) + #define LOGI(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) + #define LOGW(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) + #define LOGE(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) + #else + // @todo @fix; Obiously the tag shouldn't be hardcoded in here.. + #define LOGV(...) ((void)__android_log_print( ANDROID_LOG_VERBOSE, "MinecraftPE", __VA_ARGS__ )) + #define LOGI(...) ((void)__android_log_print( ANDROID_LOG_INFO, "MinecraftPE", __VA_ARGS__ )) + #define LOGW(...) ((void)__android_log_print( ANDROID_LOG_WARN, "MinecraftPE", __VA_ARGS__ )) + #define LOGE(...) ((void)__android_log_print( ANDROID_LOG_ERROR, "MinecraftPE", __VA_ARGS__ )) + #define printf LOGI + #endif +#else +#ifdef PUBLISH + #define LOGV(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) + #define LOGI(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) + #define LOGW(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) + #define LOGE(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) +#else + #define LOGV(...) (printf(__VA_ARGS__)) + #define LOGI(...) (printf(__VA_ARGS__)) + #define LOGW(...) (printf(__VA_ARGS__)) + #define LOGE(...) (printf(__VA_ARGS__)) +#endif +#endif + +#ifdef _DEBUG + #define LOGVV LOGV +#else + #define LOGVV(fmt, ...) __LOG_PUBLISH(__VA_ARGS__) +#endif + diff --git a/src/platform/time.h b/src/platform/time.h index a739328..044aeff 100755 --- a/src/platform/time.h +++ b/src/platform/time.h @@ -1,111 +1,109 @@ -#ifndef TIME_H__ -#define TIME_H__ - -#include -#include -#include "log.h" - -float getTimeS(); -int getTimeMs(); -int getRawTimeS(); -int getEpochTimeS(); - -void sleepMs(int ms); - -class Stopwatch { -public: - Stopwatch(); - virtual ~Stopwatch() {} - - void start(); - /** Returns the total number of seconds and stops the clock */ - virtual float stop(); - /* Returns the total number of seconds, but wont stop the clock */ - virtual float stopContinue(); - /** Returns the last measured time interval in seconds */ - float getLast(); - /** Returns the total measured time in seconds */ - float getTotal(); - /** Returns the maximum time between start() and stop() */ - float getMax(); - /** Returns the number of times the watch has been started and stopped */ - int getCount(); - - void reset(); - void printEvery(int n, const std::string& prepend = ""); - virtual void print(const std::string& prepend = ""); -private: - float _st; - float _tt; - float _last; - float _max; - int _count; - int _printcounter; -}; - -class SwStartStopper { -public: - SwStartStopper(Stopwatch& stopwatch) - : _stopwatch(stopwatch) - { - _stopwatch.start(); - } - - ~SwStartStopper() { - _stopwatch.stop(); - } -private: - Stopwatch& _stopwatch; -}; - -class SwStopper { -public: - SwStopper(Stopwatch& stopwatch) - : _stopwatch(stopwatch) - {} - - ~SwStopper() { - _stopwatch.stop(); - } -private: - Stopwatch& _stopwatch; -}; - -class StopwatchHandler { -typedef std::map Map; -public: - StopwatchHandler() - : _printcounter(0) - {} - ~StopwatchHandler() { - clearAll(); - } - Stopwatch& get(const std::string& s); - void clear(const std::string& s); - void clearAll(); - void print(); - void printEvery(int n); - -private: - Map _map; - int _printcounter; -}; - -class StopwatchNLast: public Stopwatch { -public: - StopwatchNLast(int numMeasurements); - ~StopwatchNLast(); - - float stop(); - - virtual void print(const std::string& prepend = ""); -private: - int n; - int k; - float* t; - float sum; - - Stopwatch sw; -}; - -#endif /*TIME_H__*/ +#pragma once + +#include +#include +#include "log.h" + +float getTimeS(); +int getTimeMs(); +int getRawTimeS(); +int getEpochTimeS(); + +void sleepMs(int ms); + +class Stopwatch { +public: + Stopwatch(); + virtual ~Stopwatch() {} + + void start(); + /** Returns the total number of seconds and stops the clock */ + virtual float stop(); + /* Returns the total number of seconds, but wont stop the clock */ + virtual float stopContinue(); + /** Returns the last measured time interval in seconds */ + float getLast(); + /** Returns the total measured time in seconds */ + float getTotal(); + /** Returns the maximum time between start() and stop() */ + float getMax(); + /** Returns the number of times the watch has been started and stopped */ + int getCount(); + + void reset(); + void printEvery(int n, const std::string& prepend = ""); + virtual void print(const std::string& prepend = ""); +private: + float _st; + float _tt; + float _last; + float _max; + int _count; + int _printcounter; +}; + +class SwStartStopper { +public: + SwStartStopper(Stopwatch& stopwatch) + : _stopwatch(stopwatch) + { + _stopwatch.start(); + } + + ~SwStartStopper() { + _stopwatch.stop(); + } +private: + Stopwatch& _stopwatch; +}; + +class SwStopper { +public: + SwStopper(Stopwatch& stopwatch) + : _stopwatch(stopwatch) + {} + + ~SwStopper() { + _stopwatch.stop(); + } +private: + Stopwatch& _stopwatch; +}; + +class StopwatchHandler { +typedef std::map Map; +public: + StopwatchHandler() + : _printcounter(0) + {} + ~StopwatchHandler() { + clearAll(); + } + Stopwatch& get(const std::string& s); + void clear(const std::string& s); + void clearAll(); + void print(); + void printEvery(int n); + +private: + Map _map; + int _printcounter; +}; + +class StopwatchNLast: public Stopwatch { +public: + StopwatchNLast(int numMeasurements); + ~StopwatchNLast(); + + float stop(); + + virtual void print(const std::string& prepend = ""); +private: + int n; + int k; + float* t; + float sum; + + Stopwatch sw; +}; + diff --git a/src/platform/win32/AppPlatform_win32.h b/src/platform/win32/AppPlatform_win32.h index eb73217..01be48c 100755 --- a/src/platform/win32/AppPlatform_win32.h +++ b/src/platform/win32/AppPlatform_win32.h @@ -1,142 +1,140 @@ -#ifndef APPPLATFORM_WIN32_H__ -#define APPPLATFORM_WIN32_H__ - -#include -#include "platform/log.h" -#include "platform/HttpClient.h" -#include "platform/PngLoader.h" -#include "client/renderer/gles.h" -#include "world/level/storage/FolderMethods.h" -#include "util/StringUtils.h" -#include -#include -#include -#include -#include -#include - -static void png_funcReadFile(png_structp pngPtr, png_bytep data, png_size_t length) { - ((std::istream*)png_get_io_ptr(pngPtr))->read((char*)data, length); -} - -class AppPlatform_win32: public AppPlatform -{ -public: - AppPlatform_win32() - { - } - - BinaryBlob readAssetFile(const std::string& filename) { - FILE* fp = fopen(("data/" + filename).c_str(), "r"); - if (!fp) - return BinaryBlob(); - - int size = getRemainingFileSize(fp); - - BinaryBlob blob; - blob.size = size; - blob.data = new unsigned char[size]; - - fread(blob.data, 1, size, fp); - fclose(fp); - - return blob; - } - - void saveScreenshot(const std::string& filename, int glWidth, int glHeight) { - //@todo - } - - inline unsigned int rgbToBgr(unsigned int p) { - return (p & 0xff00ff00) | ((p >> 16) & 0xff) | ((p << 16) & 0xff0000); - } - - TextureData loadTexture(const std::string& filename_, bool textureFolder) - { - // Support fetching PNG textures via HTTP/HTTPS (for skins, etc). - if (Util::startsWith(filename_, "http://") || Util::startsWith(filename_, "https://")) { - std::vector body; - if (HttpClient::download(filename_, body) && !body.empty()) { - return loadTextureFromMemory(body.data(), body.size()); - } - return TextureData(); - } - - TextureData out; - - std::string filename = textureFolder? "data/images/" + filename_ - : filename_; - std::ifstream source(filename.c_str(), std::ios::binary); - - if (source) { - png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); - - if (!pngPtr) - return out; - - png_infop infoPtr = png_create_info_struct(pngPtr); - - if (!infoPtr) { - png_destroy_read_struct(&pngPtr, NULL, NULL); - return out; - } - - // Hack to get around the broken libpng for windows - png_set_read_fn(pngPtr,(void*)&source, png_funcReadFile); - - png_read_info(pngPtr, infoPtr); - - // Set up the texdata properties - out.w = png_get_image_width(pngPtr, infoPtr); - out.h = png_get_image_height(pngPtr, infoPtr); - - png_bytep* rowPtrs = new png_bytep[out.h]; - out.data = new unsigned char[4 * out.w * out.h]; - out.memoryHandledExternally = false; - - int rowStrideBytes = 4 * out.w; - for (int i = 0; i < out.h; i++) { - rowPtrs[i] = (png_bytep)&out.data[i*rowStrideBytes]; - } - png_read_image(pngPtr, rowPtrs); - - // Teardown and return - png_destroy_read_struct(&pngPtr, &infoPtr,(png_infopp)0); - delete[] (png_bytep)rowPtrs; - source.close(); - - return out; - } - else - { - LOGI("Couldn't find file: %s\n", filename.c_str()); - return out; - } - } - - TextureData loadTextureFromMemory(const unsigned char* data, size_t size) override { - return loadPngFromMemory(data, size); - } - time_t tm = s; - - char mbstr[100]; - std::strftime(mbstr, sizeof(mbstr), "%F %T", std::localtime(&tm)); - - return std::string(mbstr); - } - - virtual int getScreenWidth(); - virtual int getScreenHeight(); - - virtual float getPixelsPerMillimeter(); - - virtual bool supportsTouchscreen(); - - virtual void openURL(const std::string& url) { - ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); - } - -private: -}; - -#endif /*APPPLATFORM_WIN32_H__*/ +#pragma once + +#include +#include "platform/log.h" +#include "platform/HttpClient.h" +#include "platform/PngLoader.h" +#include "client/renderer/gles.h" +#include "world/level/storage/FolderMethods.h" +#include "util/StringUtils.h" +#include +#include +#include +#include +#include +#include + +static void png_funcReadFile(png_structp pngPtr, png_bytep data, png_size_t length) { + ((std::istream*)png_get_io_ptr(pngPtr))->read((char*)data, length); +} + +class AppPlatform_win32: public AppPlatform +{ +public: + AppPlatform_win32() + { + } + + BinaryBlob readAssetFile(const std::string& filename) { + FILE* fp = fopen(("data/" + filename).c_str(), "r"); + if (!fp) + return BinaryBlob(); + + int size = getRemainingFileSize(fp); + + BinaryBlob blob; + blob.size = size; + blob.data = new unsigned char[size]; + + fread(blob.data, 1, size, fp); + fclose(fp); + + return blob; + } + + void saveScreenshot(const std::string& filename, int glWidth, int glHeight) { + //@todo + } + + inline unsigned int rgbToBgr(unsigned int p) { + return (p & 0xff00ff00) | ((p >> 16) & 0xff) | ((p << 16) & 0xff0000); + } + + TextureData loadTexture(const std::string& filename_, bool textureFolder) + { + // Support fetching PNG textures via HTTP/HTTPS (for skins, etc). + if (Util::startsWith(filename_, "http://") || Util::startsWith(filename_, "https://")) { + std::vector body; + if (HttpClient::download(filename_, body) && !body.empty()) { + return loadTextureFromMemory(body.data(), body.size()); + } + return TextureData(); + } + + TextureData out; + + std::string filename = textureFolder? "data/images/" + filename_ + : filename_; + std::ifstream source(filename.c_str(), std::ios::binary); + + if (source) { + png_structp pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + + if (!pngPtr) + return out; + + png_infop infoPtr = png_create_info_struct(pngPtr); + + if (!infoPtr) { + png_destroy_read_struct(&pngPtr, NULL, NULL); + return out; + } + + // Hack to get around the broken libpng for windows + png_set_read_fn(pngPtr,(void*)&source, png_funcReadFile); + + png_read_info(pngPtr, infoPtr); + + // Set up the texdata properties + out.w = png_get_image_width(pngPtr, infoPtr); + out.h = png_get_image_height(pngPtr, infoPtr); + + png_bytep* rowPtrs = new png_bytep[out.h]; + out.data = new unsigned char[4 * out.w * out.h]; + out.memoryHandledExternally = false; + + int rowStrideBytes = 4 * out.w; + for (int i = 0; i < out.h; i++) { + rowPtrs[i] = (png_bytep)&out.data[i*rowStrideBytes]; + } + png_read_image(pngPtr, rowPtrs); + + // Teardown and return + png_destroy_read_struct(&pngPtr, &infoPtr,(png_infopp)0); + delete[] (png_bytep)rowPtrs; + source.close(); + + return out; + } + else + { + LOGI("Couldn't find file: %s\n", filename.c_str()); + return out; + } + } + + TextureData loadTextureFromMemory(const unsigned char* data, size_t size) override { + return loadPngFromMemory(data, size); + } + time_t tm = s; + + char mbstr[100]; + std::strftime(mbstr, sizeof(mbstr), "%F %T", std::localtime(&tm)); + + return std::string(mbstr); + } + + virtual int getScreenWidth(); + virtual int getScreenHeight(); + + virtual float getPixelsPerMillimeter(); + + virtual bool supportsTouchscreen(); + + virtual void openURL(const std::string& url) { + ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); + } + +private: +}; + diff --git a/src/raknet/Gets.h b/src/raknet/Gets.h index 78bcb6d..7e9a47a 100755 --- a/src/raknet/Gets.h +++ b/src/raknet/Gets.h @@ -1,14 +1,12 @@ -#ifndef __GETS__H_ -#define __GETS__H_ - -#ifdef __cplusplus -extern "C" { -#endif - -char * Gets ( char * str, int num ); - -#ifdef __cplusplus -} -#endif - -#endif +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +char * Gets ( char * str, int num ); + +#ifdef __cplusplus +} +#endif + diff --git a/src/raknet/GridSectorizer.h b/src/raknet/GridSectorizer.h index 47578ff..757fa6c 100755 --- a/src/raknet/GridSectorizer.h +++ b/src/raknet/GridSectorizer.h @@ -1,68 +1,66 @@ -#ifndef _GRID_SECTORIZER_H -#define _GRID_SECTORIZER_H - -//#define _USE_ORDERED_LIST - -#include "RakMemoryOverride.h" - -#ifdef _USE_ORDERED_LIST -#include "DS_OrderedList.h" -#else -#include "DS_List.h" -#endif - -class GridSectorizer -{ -public: - GridSectorizer(); - ~GridSectorizer(); - - // _cellWidth, _cellHeight is the width and height of each cell in world units - // minX, minY, maxX, maxY are the world dimensions (can be changed to dynamically allocate later if needed) - void Init(const float _maxCellWidth, const float _maxCellHeight, const float minX, const float minY, const float maxX, const float maxY); - - // Adds a pointer to the grid with bounding rectangle dimensions - void AddEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY); - -#ifdef _USE_ORDERED_LIST - - // Removes a pointer, as above - void RemoveEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY); - - // Adds and removes in one pass, more efficient than calling both functions consecutively - void MoveEntry(void *entry, const float sourceMinX, const float sourceMinY, const float sourceMaxX, const float sourceMaxY, - const float destMinX, const float destMinY, const float destMaxX, const float destMaxY); - -#endif - - // Adds to intersectionList all entries in a certain radius - void GetEntries(DataStructures::List& intersectionList, const float minX, const float minY, const float maxX, const float maxY); - - void Clear(void); - -protected: - int WorldToCellX(const float input) const; - int WorldToCellY(const float input) const; - int WorldToCellXOffsetAndClamped(const float input) const; - int WorldToCellYOffsetAndClamped(const float input) const; - - // Returns true or false if a position crosses cells in the grid. If false, you don't need to move entries - bool PositionCrossesCells(const float originX, const float originY, const float destinationX, const float destinationY) const; - - float cellOriginX, cellOriginY; - float cellWidth, cellHeight; - float invCellWidth, invCellHeight; - float gridWidth, gridHeight; - int gridCellWidthCount, gridCellHeightCount; - - - // int gridWidth, gridHeight; - -#ifdef _USE_ORDERED_LIST - DataStructures::OrderedList* grid; -#else - DataStructures::List* grid; -#endif -}; - -#endif +#pragma once + +//#define _USE_ORDERED_LIST + +#include "RakMemoryOverride.h" + +#ifdef _USE_ORDERED_LIST +#include "DS_OrderedList.h" +#else +#include "DS_List.h" +#endif + +class GridSectorizer +{ +public: + GridSectorizer(); + ~GridSectorizer(); + + // _cellWidth, _cellHeight is the width and height of each cell in world units + // minX, minY, maxX, maxY are the world dimensions (can be changed to dynamically allocate later if needed) + void Init(const float _maxCellWidth, const float _maxCellHeight, const float minX, const float minY, const float maxX, const float maxY); + + // Adds a pointer to the grid with bounding rectangle dimensions + void AddEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY); + +#ifdef _USE_ORDERED_LIST + + // Removes a pointer, as above + void RemoveEntry(void *entry, const float minX, const float minY, const float maxX, const float maxY); + + // Adds and removes in one pass, more efficient than calling both functions consecutively + void MoveEntry(void *entry, const float sourceMinX, const float sourceMinY, const float sourceMaxX, const float sourceMaxY, + const float destMinX, const float destMinY, const float destMaxX, const float destMaxY); + +#endif + + // Adds to intersectionList all entries in a certain radius + void GetEntries(DataStructures::List& intersectionList, const float minX, const float minY, const float maxX, const float maxY); + + void Clear(void); + +protected: + int WorldToCellX(const float input) const; + int WorldToCellY(const float input) const; + int WorldToCellXOffsetAndClamped(const float input) const; + int WorldToCellYOffsetAndClamped(const float input) const; + + // Returns true or false if a position crosses cells in the grid. If false, you don't need to move entries + bool PositionCrossesCells(const float originX, const float originY, const float destinationX, const float destinationY) const; + + float cellOriginX, cellOriginY; + float cellWidth, cellHeight; + float invCellWidth, invCellHeight; + float gridWidth, gridHeight; + int gridCellWidthCount, gridCellHeightCount; + + + // int gridWidth, gridHeight; + +#ifdef _USE_ORDERED_LIST + DataStructures::OrderedList* grid; +#else + DataStructures::List* grid; +#endif +}; + diff --git a/src/raknet/IncrementalReadInterface.h b/src/raknet/IncrementalReadInterface.h index 0bf56a8..9b37cf2 100755 --- a/src/raknet/IncrementalReadInterface.h +++ b/src/raknet/IncrementalReadInterface.h @@ -1,28 +1,26 @@ -#ifndef __INCREMENTAL_READ_INTERFACE_H -#define __INCREMENTAL_READ_INTERFACE_H - -#include "FileListNodeContext.h" -#include "Export.h" - -namespace RakNet -{ - -class RAK_DLL_EXPORT IncrementalReadInterface -{ -public: - IncrementalReadInterface() {} - virtual ~IncrementalReadInterface() {} - - /// Read part of a file into \a destination - /// Return the number of bytes written. Return 0 when file is done. - /// \param[in] filename Filename to read - /// \param[in] startReadBytes What offset from the start of the file to read from - /// \param[in] numBytesToRead How many bytes to read. This is also how many bytes have been allocated to preallocatedDestination - /// \param[out] preallocatedDestination Write your data here - /// \return The number of bytes read, or 0 if none - virtual unsigned int GetFilePart( const char *filename, unsigned int startReadBytes, unsigned int numBytesToRead, void *preallocatedDestination, FileListNodeContext context); -}; - -} // namespace RakNet - -#endif +#pragma once + +#include "FileListNodeContext.h" +#include "Export.h" + +namespace RakNet +{ + +class RAK_DLL_EXPORT IncrementalReadInterface +{ +public: + IncrementalReadInterface() {} + virtual ~IncrementalReadInterface() {} + + /// Read part of a file into \a destination + /// Return the number of bytes written. Return 0 when file is done. + /// \param[in] filename Filename to read + /// \param[in] startReadBytes What offset from the start of the file to read from + /// \param[in] numBytesToRead How many bytes to read. This is also how many bytes have been allocated to preallocatedDestination + /// \param[out] preallocatedDestination Write your data here + /// \return The number of bytes read, or 0 if none + virtual unsigned int GetFilePart( const char *filename, unsigned int startReadBytes, unsigned int numBytesToRead, void *preallocatedDestination, FileListNodeContext context); +}; + +} // namespace RakNet + diff --git a/src/raknet/Itoa.h b/src/raknet/Itoa.h index 1b41ad7..8943092 100755 --- a/src/raknet/Itoa.h +++ b/src/raknet/Itoa.h @@ -1,15 +1,13 @@ -#ifndef __RAK_ITOA_H -#define __RAK_ITOA_H - -#ifdef __cplusplus -extern "C" { -#endif - -char* Itoa( int value, char* result, int base ); - -#ifdef __cplusplus -} -#endif - - -#endif +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +char* Itoa( int value, char* result, int base ); + +#ifdef __cplusplus +} +#endif + + diff --git a/src/raknet/LinuxStrings.h b/src/raknet/LinuxStrings.h index 11c8589..c9be8a9 100755 --- a/src/raknet/LinuxStrings.h +++ b/src/raknet/LinuxStrings.h @@ -1,26 +1,24 @@ -#ifndef _GCC_WIN_STRINGS -#define _GCC_WIN_STRINGS - - - - - - - - - - #if (defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__)) && !defined(_WIN32) - #ifndef _stricmp - int _stricmp(const char* s1, const char* s2); - #endif - int _strnicmp(const char* s1, const char* s2, size_t n); -#ifndef __APPLE__ - char *_strlwr(char * str ); //this won't compile on OSX for some reason -#endif - #ifndef _vsnprintf - #define _vsnprintf vsnprintf - #endif - #endif - - -#endif // _GCC_WIN_STRINGS +#pragma once + + + + + + + + + + #if (defined(__GNUC__) || defined(__GCCXML__) || defined(__S3E__)) && !defined(_WIN32) + #ifndef _stricmp + int _stricmp(const char* s1, const char* s2); + #endif + int _strnicmp(const char* s1, const char* s2, size_t n); +#ifndef __APPLE__ + char *_strlwr(char * str ); //this won't compile on OSX for some reason +#endif + #ifndef _vsnprintf + #define _vsnprintf vsnprintf + #endif + #endif + + diff --git a/src/raknet/LocklessTypes.h b/src/raknet/LocklessTypes.h index 441e6bd..b98c994 100755 --- a/src/raknet/LocklessTypes.h +++ b/src/raknet/LocklessTypes.h @@ -1,40 +1,38 @@ -#ifndef __LOCKLESS_TYPES_H -#define __LOCKLESS_TYPES_H - -#include "Export.h" -#include "NativeTypes.h" -#include "WindowsIncludes.h" -#if defined(ANDROID) || defined(__S3E__) -// __sync_fetch_and_add not supported apparently -#include "SimpleMutex.h" -#endif - -namespace RakNet -{ - -class RAK_DLL_EXPORT LocklessUint32_t -{ -public: - LocklessUint32_t(); - explicit LocklessUint32_t(uint32_t initial); - // Returns variable value after changing it - uint32_t Increment(void); - // Returns variable value after changing it - uint32_t Decrement(void); - volatile uint32_t GetValue(void) const {return value;} - -protected: -#ifdef _WIN32 - volatile LONG value; -#elif defined(ANDROID) || defined(__S3E__) - // __sync_fetch_and_add not supported apparently - SimpleMutex mutex; - uint32_t value; -#else - volatile uint32_t value; -#endif -}; - -}; - -#endif +#pragma once + +#include "Export.h" +#include "NativeTypes.h" +#include "WindowsIncludes.h" +#if defined(ANDROID) || defined(__S3E__) +// __sync_fetch_and_add not supported apparently +#include "SimpleMutex.h" +#endif + +namespace RakNet +{ + +class RAK_DLL_EXPORT LocklessUint32_t +{ +public: + LocklessUint32_t(); + explicit LocklessUint32_t(uint32_t initial); + // Returns variable value after changing it + uint32_t Increment(void); + // Returns variable value after changing it + uint32_t Decrement(void); + volatile uint32_t GetValue(void) const {return value;} + +protected: +#ifdef _WIN32 + volatile LONG value; +#elif defined(ANDROID) || defined(__S3E__) + // __sync_fetch_and_add not supported apparently + SimpleMutex mutex; + uint32_t value; +#else + volatile uint32_t value; +#endif +}; + +}; + diff --git a/src/raknet/NativeTypes.h b/src/raknet/NativeTypes.h index f1ee4cf..1f4bd3d 100755 --- a/src/raknet/NativeTypes.h +++ b/src/raknet/NativeTypes.h @@ -1,23 +1,21 @@ -#ifndef __NATIVE_TYPES_H -#define __NATIVE_TYPES_H - -#if defined(__GNUC__) || defined(__GCCXML__) || defined(__SNC__) || defined(__S3E__) -#include -#elif !defined(_STDINT_H) && !defined(_SN_STDINT_H) && !defined(_SYS_STDINT_H_) && !defined(_STDINT) && !defined(_MACHTYPES_H_) && !defined(_STDINT_H_) - typedef unsigned char uint8_t; - typedef unsigned short uint16_t; - typedef unsigned __int32 uint32_t; - typedef signed char int8_t; - typedef signed short int16_t; - typedef __int32 int32_t; - #if defined(_MSC_VER) && _MSC_VER < 1300 - typedef unsigned __int64 uint64_t; - typedef signed __int64 int64_t; - #else - typedef unsigned long long int uint64_t; - typedef signed long long int64_t; - #endif -#endif - - -#endif +#pragma once + +#if defined(__GNUC__) || defined(__GCCXML__) || defined(__SNC__) || defined(__S3E__) +#include +#elif !defined(_STDINT_H) && !defined(_SN_STDINT_H) && !defined(_SYS_STDINT_H_) && !defined(_STDINT) && !defined(_MACHTYPES_H_) && !defined(_STDINT_H_) + typedef unsigned char uint8_t; + typedef unsigned short uint16_t; + typedef unsigned __int32 uint32_t; + typedef signed char int8_t; + typedef signed short int16_t; + typedef __int32 int32_t; + #if defined(_MSC_VER) && _MSC_VER < 1300 + typedef unsigned __int64 uint64_t; + typedef signed __int64 int64_t; + #else + typedef unsigned long long int uint64_t; + typedef signed long long int64_t; + #endif +#endif + + diff --git a/src/raknet/RakNetDefines.h b/src/raknet/RakNetDefines.h index 78822f6..2c6a27a 100755 --- a/src/raknet/RakNetDefines.h +++ b/src/raknet/RakNetDefines.h @@ -1,169 +1,167 @@ -#ifndef __RAKNET_DEFINES_H -#define __RAKNET_DEFINES_H - -// If you want to change these defines, put them in RakNetDefinesOverrides so your changes are not lost when updating RakNet -// The user should not edit this file -#include "RakNetDefinesOverrides.h" - -/// Define __GET_TIME_64BIT to have RakNet::TimeMS use a 64, rather than 32 bit value. A 32 bit value will overflow after about 5 weeks. -/// However, this doubles the bandwidth use for sending times, so don't do it unless you have a reason to. -/// Comment out if you are using the iPod Touch TG. See http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 -/// This must be the same on all systems, or they won't connect -#ifndef __GET_TIME_64BIT -#define __GET_TIME_64BIT 1 -#endif - -// Define _FILE_AND_LINE_ to "",0 if you want to strip out file and line info for memory tracking from the EXE -#ifndef _FILE_AND_LINE_ -#define _FILE_AND_LINE_ __FILE__,__LINE__ -#endif - -/// Define __BITSTREAM_NATIVE_END to NOT support endian swapping in the BitStream class. This is faster and is what you should use -/// unless you actually plan to have different endianness systems connect to each other -/// Enabled by default. -// #define __BITSTREAM_NATIVE_END - -/// Maximum (stack) size to use with _alloca before using new and delete instead. -#ifndef MAX_ALLOCA_STACK_ALLOCATION -#define MAX_ALLOCA_STACK_ALLOCATION 1048576 -#endif - -// Use WaitForSingleObject instead of sleep. -// Defining it plays nicer with other systems, and uses less CPU, but gives worse RakNet performance -// Undefining it uses more CPU time, but is more responsive and faster. -#ifndef _WIN32_WCE -#define USE_WAIT_FOR_MULTIPLE_EVENTS -#endif - -/// Uncomment to use RakMemoryOverride for custom memory tracking -/// See RakMemoryOverride.h. -#ifndef _USE_RAK_MEMORY_OVERRIDE -#define _USE_RAK_MEMORY_OVERRIDE 0 -#endif - -/// If defined, OpenSSL is enabled for the class TCPInterface -/// This is necessary to use the SendEmail class with Google POP servers -/// Note that OpenSSL carries its own license restrictions that you should be aware of. If you don't agree, don't enable this define -/// This also requires that you enable header search paths to DependentExtensions\openssl-0.9.8g -// #define OPEN_SSL_CLIENT_SUPPORT -#ifndef OPEN_SSL_CLIENT_SUPPORT -#define OPEN_SSL_CLIENT_SUPPORT 0 -#endif - -/// Threshold at which to do a malloc / free rather than pushing data onto a fixed stack for the bitstream class -/// Arbitrary size, just picking something likely to be larger than most packets -#ifndef BITSTREAM_STACK_ALLOCATION_SIZE -#define BITSTREAM_STACK_ALLOCATION_SIZE 256 -#endif - -// Redefine if you want to disable or change the target for debug RAKNET_DEBUG_PRINTF -#ifndef RAKNET_DEBUG_PRINTF -#define RAKNET_DEBUG_PRINTF printf -#endif - -// Maximum number of local IP addresses supported -#ifndef MAXIMUM_NUMBER_OF_INTERNAL_IDS -#define MAXIMUM_NUMBER_OF_INTERNAL_IDS 10 -#endif - -#ifndef RakAssert - - - - -#if defined(_DEBUG) -#define RakAssert(x) assert(x); -#else -#define RakAssert(x) -#endif - -#endif - -/// This controls the amount of memory used per connection. -/// This many datagrams are tracked by datagramNumber. If more than this many datagrams are sent, then an ack for an older datagram would be ignored -/// This results in an unnecessary resend in that case -#ifndef DATAGRAM_MESSAGE_ID_ARRAY_LENGTH -#define DATAGRAM_MESSAGE_ID_ARRAY_LENGTH 512 -#endif - -/// This is the maximum number of reliable user messages that can be on the wire at a time -/// If this is too low, then high ping connections with a large throughput will be underutilized -/// This will be evident because RakNetStatistics::messagesInSend buffer will increase over time, yet at the same time the outgoing bandwidth per second is less than your connection supports -#ifndef RESEND_BUFFER_ARRAY_LENGTH -#define RESEND_BUFFER_ARRAY_LENGTH 512 -#define RESEND_BUFFER_ARRAY_MASK 511 -#endif - -/// Uncomment if you want to link in the DLMalloc library to use with RakMemoryOverride -// #define _LINK_DL_MALLOC - -#ifndef GET_TIME_SPIKE_LIMIT -/// Workaround for http://support.microsoft.com/kb/274323 -/// If two calls between RakNet::GetTime() happen farther apart than this time in microseconds, this delta will be returned instead -/// Note: This will cause ID_TIMESTAMP to be temporarily inaccurate if you set a breakpoint that pauses the UpdateNetworkLoop() thread in RakPeer -/// Define in RakNetDefinesOverrides.h to enable (non-zero) or disable (0) -#define GET_TIME_SPIKE_LIMIT 0 -#endif - -// Use sliding window congestion control instead of ping based congestion control -#ifndef USE_SLIDING_WINDOW_CONGESTION_CONTROL -#define USE_SLIDING_WINDOW_CONGESTION_CONTROL 1 -#endif - -// When a large message is arriving, preallocate the memory for the entire block -// This results in large messages not taking up time to reassembly with memcpy, but is vulnerable to attackers causing the host to run out of memory -#ifndef PREALLOCATE_LARGE_MESSAGES -#define PREALLOCATE_LARGE_MESSAGES 0 -#endif - -#ifndef RAKNET_SUPPORT_IPV6 -#define RAKNET_SUPPORT_IPV6 0 -#endif - - - - - - - - - - - -#ifndef RAKSTRING_TYPE -#if defined(_UNICODE) -#define RAKSTRING_TYPE RakWString -#define RAKSTRING_TYPE_IS_UNICODE 1 -#else -#define RAKSTRING_TYPE RakString -#define RAKSTRING_TYPE_IS_UNICODE 0 -#endif -#endif - -#ifndef RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS -#define RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS 32 -#endif - -#ifndef RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH -#define RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH 32 -#endif - -#ifndef XBOX_BYPASS_SECURITY -#define XBOX_BYPASS_SECURITY 1 -#endif - -// Controls how many allocations occur at once for the memory pool of incoming datagrams waiting to be transferred between the recvfrom thread and the main update thread -// Has large effect on memory usage, per instance of RakPeer. Approximately MAXIMUM_MTU_SIZE*BUFFERED_PACKETS_PAGE_SIZE bytes, once after calling RakPeer::Startup() -#ifndef BUFFERED_PACKETS_PAGE_SIZE -#define BUFFERED_PACKETS_PAGE_SIZE 8 -#endif - -// Controls how many allocations occur at once for the memory pool of incoming or outgoing datagrams. -// Has small effect on memory usage per connection. Uses about 256 bytes*INTERNAL_PACKET_PAGE_SIZE per connection -#ifndef INTERNAL_PACKET_PAGE_SIZE -#define INTERNAL_PACKET_PAGE_SIZE 8 -#endif - -//#define USE_THREADED_SEND - -#endif // __RAKNET_DEFINES_H +#pragma once + +// If you want to change these defines, put them in RakNetDefinesOverrides so your changes are not lost when updating RakNet +// The user should not edit this file +#include "RakNetDefinesOverrides.h" + +/// Define __GET_TIME_64BIT to have RakNet::TimeMS use a 64, rather than 32 bit value. A 32 bit value will overflow after about 5 weeks. +/// However, this doubles the bandwidth use for sending times, so don't do it unless you have a reason to. +/// Comment out if you are using the iPod Touch TG. See http://www.jenkinssoftware.com/forum/index.php?topic=2717.0 +/// This must be the same on all systems, or they won't connect +#ifndef __GET_TIME_64BIT +#define __GET_TIME_64BIT 1 +#endif + +// Define _FILE_AND_LINE_ to "",0 if you want to strip out file and line info for memory tracking from the EXE +#ifndef _FILE_AND_LINE_ +#define _FILE_AND_LINE_ __FILE__,__LINE__ +#endif + +/// Define __BITSTREAM_NATIVE_END to NOT support endian swapping in the BitStream class. This is faster and is what you should use +/// unless you actually plan to have different endianness systems connect to each other +/// Enabled by default. +// #define __BITSTREAM_NATIVE_END + +/// Maximum (stack) size to use with _alloca before using new and delete instead. +#ifndef MAX_ALLOCA_STACK_ALLOCATION +#define MAX_ALLOCA_STACK_ALLOCATION 1048576 +#endif + +// Use WaitForSingleObject instead of sleep. +// Defining it plays nicer with other systems, and uses less CPU, but gives worse RakNet performance +// Undefining it uses more CPU time, but is more responsive and faster. +#ifndef _WIN32_WCE +#define USE_WAIT_FOR_MULTIPLE_EVENTS +#endif + +/// Uncomment to use RakMemoryOverride for custom memory tracking +/// See RakMemoryOverride.h. +#ifndef _USE_RAK_MEMORY_OVERRIDE +#define _USE_RAK_MEMORY_OVERRIDE 0 +#endif + +/// If defined, OpenSSL is enabled for the class TCPInterface +/// This is necessary to use the SendEmail class with Google POP servers +/// Note that OpenSSL carries its own license restrictions that you should be aware of. If you don't agree, don't enable this define +/// This also requires that you enable header search paths to DependentExtensions\openssl-0.9.8g +// #define OPEN_SSL_CLIENT_SUPPORT +#ifndef OPEN_SSL_CLIENT_SUPPORT +#define OPEN_SSL_CLIENT_SUPPORT 0 +#endif + +/// Threshold at which to do a malloc / free rather than pushing data onto a fixed stack for the bitstream class +/// Arbitrary size, just picking something likely to be larger than most packets +#ifndef BITSTREAM_STACK_ALLOCATION_SIZE +#define BITSTREAM_STACK_ALLOCATION_SIZE 256 +#endif + +// Redefine if you want to disable or change the target for debug RAKNET_DEBUG_PRINTF +#ifndef RAKNET_DEBUG_PRINTF +#define RAKNET_DEBUG_PRINTF printf +#endif + +// Maximum number of local IP addresses supported +#ifndef MAXIMUM_NUMBER_OF_INTERNAL_IDS +#define MAXIMUM_NUMBER_OF_INTERNAL_IDS 10 +#endif + +#ifndef RakAssert + + + + +#if defined(_DEBUG) +#define RakAssert(x) assert(x); +#else +#define RakAssert(x) +#endif + +#endif + +/// This controls the amount of memory used per connection. +/// This many datagrams are tracked by datagramNumber. If more than this many datagrams are sent, then an ack for an older datagram would be ignored +/// This results in an unnecessary resend in that case +#ifndef DATAGRAM_MESSAGE_ID_ARRAY_LENGTH +#define DATAGRAM_MESSAGE_ID_ARRAY_LENGTH 512 +#endif + +/// This is the maximum number of reliable user messages that can be on the wire at a time +/// If this is too low, then high ping connections with a large throughput will be underutilized +/// This will be evident because RakNetStatistics::messagesInSend buffer will increase over time, yet at the same time the outgoing bandwidth per second is less than your connection supports +#ifndef RESEND_BUFFER_ARRAY_LENGTH +#define RESEND_BUFFER_ARRAY_LENGTH 512 +#define RESEND_BUFFER_ARRAY_MASK 511 +#endif + +/// Uncomment if you want to link in the DLMalloc library to use with RakMemoryOverride +// #define _LINK_DL_MALLOC + +#ifndef GET_TIME_SPIKE_LIMIT +/// Workaround for http://support.microsoft.com/kb/274323 +/// If two calls between RakNet::GetTime() happen farther apart than this time in microseconds, this delta will be returned instead +/// Note: This will cause ID_TIMESTAMP to be temporarily inaccurate if you set a breakpoint that pauses the UpdateNetworkLoop() thread in RakPeer +/// Define in RakNetDefinesOverrides.h to enable (non-zero) or disable (0) +#define GET_TIME_SPIKE_LIMIT 0 +#endif + +// Use sliding window congestion control instead of ping based congestion control +#ifndef USE_SLIDING_WINDOW_CONGESTION_CONTROL +#define USE_SLIDING_WINDOW_CONGESTION_CONTROL 1 +#endif + +// When a large message is arriving, preallocate the memory for the entire block +// This results in large messages not taking up time to reassembly with memcpy, but is vulnerable to attackers causing the host to run out of memory +#ifndef PREALLOCATE_LARGE_MESSAGES +#define PREALLOCATE_LARGE_MESSAGES 0 +#endif + +#ifndef RAKNET_SUPPORT_IPV6 +#define RAKNET_SUPPORT_IPV6 0 +#endif + + + + + + + + + + + +#ifndef RAKSTRING_TYPE +#if defined(_UNICODE) +#define RAKSTRING_TYPE RakWString +#define RAKSTRING_TYPE_IS_UNICODE 1 +#else +#define RAKSTRING_TYPE RakString +#define RAKSTRING_TYPE_IS_UNICODE 0 +#endif +#endif + +#ifndef RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS +#define RPC4_GLOBAL_REGISTRATION_MAX_FUNCTIONS 32 +#endif + +#ifndef RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH +#define RPC4_GLOBAL_REGISTRATION_MAX_FUNCTION_NAME_LENGTH 32 +#endif + +#ifndef XBOX_BYPASS_SECURITY +#define XBOX_BYPASS_SECURITY 1 +#endif + +// Controls how many allocations occur at once for the memory pool of incoming datagrams waiting to be transferred between the recvfrom thread and the main update thread +// Has large effect on memory usage, per instance of RakPeer. Approximately MAXIMUM_MTU_SIZE*BUFFERED_PACKETS_PAGE_SIZE bytes, once after calling RakPeer::Startup() +#ifndef BUFFERED_PACKETS_PAGE_SIZE +#define BUFFERED_PACKETS_PAGE_SIZE 8 +#endif + +// Controls how many allocations occur at once for the memory pool of incoming or outgoing datagrams. +// Has small effect on memory usage per connection. Uses about 256 bytes*INTERNAL_PACKET_PAGE_SIZE per connection +#ifndef INTERNAL_PACKET_PAGE_SIZE +#define INTERNAL_PACKET_PAGE_SIZE 8 +#endif + +//#define USE_THREADED_SEND + diff --git a/src/raknet/RakNetSmartPtr.h b/src/raknet/RakNetSmartPtr.h index fb9b9d8..02fef22 100755 --- a/src/raknet/RakNetSmartPtr.h +++ b/src/raknet/RakNetSmartPtr.h @@ -1,173 +1,171 @@ -#ifndef __RAKNET_SMART_PTR_H -#define __RAKNET_SMART_PTR_H - -// From http://www.codeproject.com/KB/cpp/SmartPointers.aspx -// with bugs fixed - -#include "RakMemoryOverride.h" -#include "Export.h" - -//static int allocCount=0; -//static int deallocCount=0; - -namespace RakNet -{ - -class RAK_DLL_EXPORT ReferenceCounter -{ -private: - int refCount; - -public: - ReferenceCounter() {refCount=0;} - ~ReferenceCounter() {} - void AddRef() {refCount++;} - int Release() {return --refCount;} - int GetRefCount(void) const {return refCount;} -}; - -template < typename T > class RAK_DLL_EXPORT RakNetSmartPtr -{ -private: - T* ptr; // pointer - ReferenceCounter* reference; // Reference refCount - -public: - RakNetSmartPtr() : ptr(0), reference(0) - { - // Do not allocate by default, wasteful if we just have a list of preallocated and unassigend smart pointers - } - - RakNetSmartPtr(T* pValue) : ptr(pValue) - { - reference = RakNet::OP_NEW(_FILE_AND_LINE_); - reference->AddRef(); - -// allocCount+=2; -// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); - } - - RakNetSmartPtr(const RakNetSmartPtr& sp) : ptr(sp.ptr), reference(sp.reference) - { - if (reference) - reference->AddRef(); - } - - ~RakNetSmartPtr() - { - if(reference && reference->Release() == 0) - { - RakNet::OP_DELETE(ptr, _FILE_AND_LINE_); - RakNet::OP_DELETE(reference, _FILE_AND_LINE_); - -// deallocCount+=2; -// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); - } - } - - bool IsNull(void) const - { - return ptr==0; - } - - void SetNull(void) - { - if(reference && reference->Release() == 0) - { - RakNet::OP_DELETE(ptr, _FILE_AND_LINE_); - RakNet::OP_DELETE(reference, _FILE_AND_LINE_); - -// deallocCount+=2; -// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); - } - ptr=0; - reference=0; - } - - bool IsUnique(void) const - { - return reference->GetRefCount()==1; - } - - // Allow you to change the values of the internal contents of the pointer, without changing what is pointed to by other instances of the smart pointer - void Clone(bool copyContents) - { - if (IsUnique()==false) - { - reference->Release(); - - reference = RakNet::OP_NEW(_FILE_AND_LINE_); - reference->AddRef(); - T* oldPtr=ptr; - ptr=RakNet::OP_NEW(_FILE_AND_LINE_); - if (copyContents) - *ptr=*oldPtr; - } - } - - int GetRefCount(void) const - { - return reference->GetRefCount(); - } - - T& operator* () - { - return *ptr; - } - - const T& operator* () const - { - return *ptr; - } - - T* operator-> () - { - return ptr; - } - - const T* operator-> () const - { - return ptr; - } - - bool operator == (const RakNetSmartPtr& sp) - { - return ptr == sp.ptr; - } - bool operator<( const RakNetSmartPtr &right ) {return ptr < right.ptr;} - bool operator>( const RakNetSmartPtr &right ) {return ptr > right.ptr;} - - bool operator != (const RakNetSmartPtr& sp) - { - return ptr != sp.ptr; - } - - RakNetSmartPtr& operator = (const RakNetSmartPtr& sp) - { - // Assignment operator - - if (this != &sp) // Avoid self assignment - { - if(reference && reference->Release() == 0) - { - RakNet::OP_DELETE(ptr, _FILE_AND_LINE_); - RakNet::OP_DELETE(reference, _FILE_AND_LINE_); - -// deallocCount+=2; -// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); - } - - ptr = sp.ptr; - reference = sp.reference; - if (reference) - reference->AddRef(); - } - return *this; - } - - -}; - -} // namespace RakNet - -#endif +#pragma once + +// From http://www.codeproject.com/KB/cpp/SmartPointers.aspx +// with bugs fixed + +#include "RakMemoryOverride.h" +#include "Export.h" + +//static int allocCount=0; +//static int deallocCount=0; + +namespace RakNet +{ + +class RAK_DLL_EXPORT ReferenceCounter +{ +private: + int refCount; + +public: + ReferenceCounter() {refCount=0;} + ~ReferenceCounter() {} + void AddRef() {refCount++;} + int Release() {return --refCount;} + int GetRefCount(void) const {return refCount;} +}; + +template < typename T > class RAK_DLL_EXPORT RakNetSmartPtr +{ +private: + T* ptr; // pointer + ReferenceCounter* reference; // Reference refCount + +public: + RakNetSmartPtr() : ptr(0), reference(0) + { + // Do not allocate by default, wasteful if we just have a list of preallocated and unassigend smart pointers + } + + RakNetSmartPtr(T* pValue) : ptr(pValue) + { + reference = RakNet::OP_NEW(_FILE_AND_LINE_); + reference->AddRef(); + +// allocCount+=2; +// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); + } + + RakNetSmartPtr(const RakNetSmartPtr& sp) : ptr(sp.ptr), reference(sp.reference) + { + if (reference) + reference->AddRef(); + } + + ~RakNetSmartPtr() + { + if(reference && reference->Release() == 0) + { + RakNet::OP_DELETE(ptr, _FILE_AND_LINE_); + RakNet::OP_DELETE(reference, _FILE_AND_LINE_); + +// deallocCount+=2; +// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); + } + } + + bool IsNull(void) const + { + return ptr==0; + } + + void SetNull(void) + { + if(reference && reference->Release() == 0) + { + RakNet::OP_DELETE(ptr, _FILE_AND_LINE_); + RakNet::OP_DELETE(reference, _FILE_AND_LINE_); + +// deallocCount+=2; +// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); + } + ptr=0; + reference=0; + } + + bool IsUnique(void) const + { + return reference->GetRefCount()==1; + } + + // Allow you to change the values of the internal contents of the pointer, without changing what is pointed to by other instances of the smart pointer + void Clone(bool copyContents) + { + if (IsUnique()==false) + { + reference->Release(); + + reference = RakNet::OP_NEW(_FILE_AND_LINE_); + reference->AddRef(); + T* oldPtr=ptr; + ptr=RakNet::OP_NEW(_FILE_AND_LINE_); + if (copyContents) + *ptr=*oldPtr; + } + } + + int GetRefCount(void) const + { + return reference->GetRefCount(); + } + + T& operator* () + { + return *ptr; + } + + const T& operator* () const + { + return *ptr; + } + + T* operator-> () + { + return ptr; + } + + const T* operator-> () const + { + return ptr; + } + + bool operator == (const RakNetSmartPtr& sp) + { + return ptr == sp.ptr; + } + bool operator<( const RakNetSmartPtr &right ) {return ptr < right.ptr;} + bool operator>( const RakNetSmartPtr &right ) {return ptr > right.ptr;} + + bool operator != (const RakNetSmartPtr& sp) + { + return ptr != sp.ptr; + } + + RakNetSmartPtr& operator = (const RakNetSmartPtr& sp) + { + // Assignment operator + + if (this != &sp) // Avoid self assignment + { + if(reference && reference->Release() == 0) + { + RakNet::OP_DELETE(ptr, _FILE_AND_LINE_); + RakNet::OP_DELETE(reference, _FILE_AND_LINE_); + +// deallocCount+=2; +// printf("allocCount=%i deallocCount=%i Line=%i\n",allocCount, deallocCount, __LINE__); + } + + ptr = sp.ptr; + reference = sp.reference; + if (reference) + reference->AddRef(); + } + return *this; + } + + +}; + +} // namespace RakNet + diff --git a/src/raknet/RakNetSocket.h b/src/raknet/RakNetSocket.h index 49c9557..e06feda 100755 --- a/src/raknet/RakNetSocket.h +++ b/src/raknet/RakNetSocket.h @@ -1,38 +1,36 @@ -#ifndef __RAKNET_SOCKET_H -#define __RAKNET_SOCKET_H - -#include "RakNetTypes.h" -#include "RakNetDefines.h" -#include "Export.h" - -namespace RakNet -{ - -struct RAK_DLL_EXPORT RakNetSocket -{ - RakNetSocket(); - ~RakNetSocket(); - // SocketIncludes.h includes Windows.h, which messes up a lot of compiles - // SOCKET s; - unsigned int s; - unsigned int userConnectionSocketIndex; - SystemAddress boundAddress; - unsigned short socketFamily; - -#if defined (_WIN32) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) - void* recvEvent; -#endif - - - - - - - unsigned short remotePortRakNetWasStartedOn_PS3_PSP2; - - unsigned int extraSocketOptions; -}; - -} // namespace RakNet - -#endif +#pragma once + +#include "RakNetTypes.h" +#include "RakNetDefines.h" +#include "Export.h" + +namespace RakNet +{ + +struct RAK_DLL_EXPORT RakNetSocket +{ + RakNetSocket(); + ~RakNetSocket(); + // SocketIncludes.h includes Windows.h, which messes up a lot of compiles + // SOCKET s; + unsigned int s; + unsigned int userConnectionSocketIndex; + SystemAddress boundAddress; + unsigned short socketFamily; + +#if defined (_WIN32) && defined(USE_WAIT_FOR_MULTIPLE_EVENTS) + void* recvEvent; +#endif + + + + + + + unsigned short remotePortRakNetWasStartedOn_PS3_PSP2; + + unsigned int extraSocketOptions; +}; + +} // namespace RakNet + diff --git a/src/raknet/RakNetTime.h b/src/raknet/RakNetTime.h index f9e7cd9..f53f8f5 100755 --- a/src/raknet/RakNetTime.h +++ b/src/raknet/RakNetTime.h @@ -1,23 +1,21 @@ -#ifndef __RAKNET_TIME_H -#define __RAKNET_TIME_H - -#include "NativeTypes.h" -#include "RakNetDefines.h" - -namespace RakNet { - -// Define __GET_TIME_64BIT if you want to use large types for GetTime (takes more bandwidth when you transmit time though!) -// You would want to do this if your system is going to run long enough to overflow the millisecond counter (over a month) -#if __GET_TIME_64BIT==1 -typedef uint64_t Time; -typedef uint32_t TimeMS; -typedef uint64_t TimeUS; -#else -typedef uint32_t Time; -typedef uint32_t TimeMS; -typedef uint64_t TimeUS; -#endif - -}; // namespace RakNet - -#endif +#pragma once + +#include "NativeTypes.h" +#include "RakNetDefines.h" + +namespace RakNet { + +// Define __GET_TIME_64BIT if you want to use large types for GetTime (takes more bandwidth when you transmit time though!) +// You would want to do this if your system is going to run long enough to overflow the millisecond counter (over a month) +#if __GET_TIME_64BIT==1 +typedef uint64_t Time; +typedef uint32_t TimeMS; +typedef uint64_t TimeUS; +#else +typedef uint32_t Time; +typedef uint32_t TimeMS; +typedef uint64_t TimeUS; +#endif + +}; // namespace RakNet + diff --git a/src/raknet/RakSleep.h b/src/raknet/RakSleep.h index f1a4148..f0be9bb 100755 --- a/src/raknet/RakSleep.h +++ b/src/raknet/RakSleep.h @@ -1,8 +1,6 @@ -#ifndef __RAK_SLEEP_H -#define __RAK_SLEEP_H - -#include "Export.h" - -void RAK_DLL_EXPORT RakSleep(unsigned int ms); - -#endif +#pragma once + +#include "Export.h" + +void RAK_DLL_EXPORT RakSleep(unsigned int ms); + diff --git a/src/raknet/RakString.h b/src/raknet/RakString.h index 125586e..64e9ce7 100755 --- a/src/raknet/RakString.h +++ b/src/raknet/RakString.h @@ -1,307 +1,305 @@ -#ifndef __RAK_STRING_H -#define __RAK_STRING_H - -#include "Export.h" -#include "DS_List.h" -#include "RakNetTypes.h" // int64_t -#include -#include "stdarg.h" - - -#ifdef _WIN32 - - - -#include "WindowsIncludes.h" -#endif - -namespace RakNet -{ -/// Forward declarations -class SimpleMutex; -class BitStream; - -/// \brief String class -/// \details Has the following improvements over std::string -/// -Reference counting: Suitable to store in lists -/// -Variadic assignment operator -/// -Doesn't cause linker errors -class RAK_DLL_EXPORT RakString -{ -public: - // Constructors - RakString(); - RakString(char input); - RakString(unsigned char input); - RakString(const unsigned char *format, ...); - RakString(const char *format, ...); - ~RakString(); - RakString( const RakString & rhs); - - /// Implicit return of const char* - operator const char* () const {return sharedString->c_str;} - - /// Same as std::string::c_str - const char *C_String(void) const {return sharedString->c_str;} - - // Lets you modify the string. Do not make the string longer - however, you can make it shorter, or change the contents. - // Pointer is only valid in the scope of RakString itself - char *C_StringUnsafe(void) {Clone(); return sharedString->c_str;} - - /// Assigment operators - RakString& operator = ( const RakString& rhs ); - RakString& operator = ( const char *str ); - RakString& operator = ( char *str ); - RakString& operator = ( const unsigned char *str ); - RakString& operator = ( char unsigned *str ); - RakString& operator = ( const char c ); - - /// Concatenation - RakString& operator +=( const RakString& rhs); - RakString& operator += ( const char *str ); - RakString& operator += ( char *str ); - RakString& operator += ( const unsigned char *str ); - RakString& operator += ( char unsigned *str ); - RakString& operator += ( const char c ); - - /// Character index. Do not use to change the string however. - unsigned char operator[] ( const unsigned int position ) const; - -#ifdef _WIN32 - // Return as Wide char - // Deallocate with DeallocWideChar - WCHAR * ToWideChar(void); - void DeallocWideChar(WCHAR * w); -#endif - - ///String class find replacement - ///Searches the string for the content specified in stringToFind and returns the position of the first occurrence in the string. - ///Search only includes characters on or after position pos, ignoring any possible occurrences in previous locations. - /// \param[in] stringToFind The string to find inside of this object's string - /// \param[in] pos The position in the string to start the search - /// \return Returns the position of the first occurrence in the string. - size_t Find(const char *stringToFind,size_t pos = 0 ); - - /// Equality - bool operator==(const RakString &rhs) const; - bool operator==(const char *str) const; - bool operator==(char *str) const; - - // Comparison - bool operator < ( const RakString& right ) const; - bool operator <= ( const RakString& right ) const; - bool operator > ( const RakString& right ) const; - bool operator >= ( const RakString& right ) const; - - /// Inequality - bool operator!=(const RakString &rhs) const; - bool operator!=(const char *str) const; - bool operator!=(char *str) const; - - /// Change all characters to lowercase - const char * ToLower(void); - - /// Change all characters to uppercase - const char * ToUpper(void); - - /// Set the value of the string - void Set(const char *format, ...); - - /// Sets a copy of a substring of str as the new content. The substring is the portion of str - /// that begins at the character position pos and takes up to n characters - /// (it takes less than n if the end of str is reached before). - /// \param[in] str The string to copy in - /// \param[in] pos The position on str to start the copy - /// \param[in] n How many chars to copy - /// \return Returns the string, note that the current string is set to that value as well - RakString Assign(const char *str,size_t pos, size_t n ); - - /// Returns if the string is empty. Also, C_String() would return "" - bool IsEmpty(void) const; - - /// Returns the length of the string - size_t GetLength(void) const; - size_t GetLengthUTF8(void) const; - - /// Replace character(s) in starting at index, for count, with c - void Replace(unsigned index, unsigned count, unsigned char c); - - /// Replace character at index with c - void SetChar( unsigned index, unsigned char c ); - - /// Replace character at index with string s - void SetChar( unsigned index, RakNet::RakString s ); - - /// Make sure string is no longer than \a length - void Truncate(unsigned int length); - void TruncateUTF8(unsigned int length); - - // Gets the substring starting at index for count characters - RakString SubStr(unsigned int index, unsigned int count) const; - - /// Erase characters out of the string at index for count - void Erase(unsigned int index, unsigned int count); - - /// Set the first instance of c with a NULL terminator - void TerminateAtFirstCharacter(char c); - /// Set the last instance of c with a NULL terminator - void TerminateAtLastCharacter(char c); - - /// Remove all instances of c - void RemoveCharacter(char c); - - /// Create a RakString with a value, without doing printf style parsing - /// Equivalent to assignment operator - static RakNet::RakString NonVariadic(const char *str); - - /// Has the string into an unsigned int - static unsigned long ToInteger(const char *str); - static unsigned long ToInteger(const RakString &rs); - - // Like strncat, but for a fixed length - void AppendBytes(const char *bytes, unsigned int count); - - /// Compare strings (case sensitive) - int StrCmp(const RakString &rhs) const; - - /// Compare strings (not case sensitive) - int StrICmp(const RakString &rhs) const; - - /// Clear the string - void Clear(void); - - /// Print the string to the screen - void Printf(void); - - /// Print the string to a file - void FPrintf(FILE *fp); - - /// Does the given IP address match the IP address encoded into this string, accounting for wildcards? - bool IPAddressMatch(const char *IP); - - /// Does the string contain non-printable characters other than spaces? - bool ContainsNonprintableExceptSpaces(void) const; - - /// Is this a valid email address? - bool IsEmailAddress(void) const; - - /// URL Encode the string. See http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4029/ - RakNet::RakString& URLEncode(void); - - /// URL decode the string - RakNet::RakString& URLDecode(void); - - /// https://servers.api.rackspacecloud.com/v1.0 to https://, servers.api.rackspacecloud.com, /v1.0 - void SplitURI(RakNet::RakString &header, RakNet::RakString &domain, RakNet::RakString &path); - - /// Scan for quote, double quote, and backslash and prepend with backslash - RakNet::RakString& SQLEscape(void); - - /// Fix to be a file path, ending with / - RakNet::RakString& MakeFilePath(void); - - /// RakString uses a freeList of old no-longer used strings - /// Call this function to clear this memory on shutdown - static void FreeMemory(void); - /// \internal - static void FreeMemoryNoMutex(void); - - /// Serialize to a bitstream, uncompressed (slightly faster) - /// \param[out] bs Bitstream to serialize to - void Serialize(BitStream *bs) const; - - /// Static version of the Serialize function - static void Serialize(const char *str, BitStream *bs); - - /// Serialize to a bitstream, compressed (better bandwidth usage) - /// \param[out] bs Bitstream to serialize to - /// \param[in] languageId languageId to pass to the StringCompressor class - /// \param[in] writeLanguageId encode the languageId variable in the stream. If false, 0 is assumed, and DeserializeCompressed will not look for this variable in the stream (saves bandwidth) - /// \pre StringCompressor::AddReference must have been called to instantiate the class (Happens automatically from RakPeer::Startup()) - void SerializeCompressed(BitStream *bs, uint8_t languageId=0, bool writeLanguageId=false) const; - - /// Static version of the SerializeCompressed function - static void SerializeCompressed(const char *str, BitStream *bs, uint8_t languageId=0, bool writeLanguageId=false); - - /// Deserialize what was written by Serialize - /// \param[in] bs Bitstream to serialize from - /// \return true if the deserialization was successful - bool Deserialize(BitStream *bs); - - /// Static version of the Deserialize() function - static bool Deserialize(char *str, BitStream *bs); - - /// Deserialize compressed string, written by SerializeCompressed - /// \param[in] bs Bitstream to serialize from - /// \param[in] readLanguageId If true, looks for the variable langaugeId in the data stream. Must match what was passed to SerializeCompressed - /// \return true if the deserialization was successful - /// \pre StringCompressor::AddReference must have been called to instantiate the class (Happens automatically from RakPeer::Startup()) - bool DeserializeCompressed(BitStream *bs, bool readLanguageId=false); - - /// Static version of the DeserializeCompressed() function - static bool DeserializeCompressed(char *str, BitStream *bs, bool readLanguageId=false); - - static const char *ToString(int64_t i); - static const char *ToString(uint64_t i); - - /// \internal - static size_t GetSizeToAllocate(size_t bytes) - { - const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; - if (bytes<=smallStringSize) - return smallStringSize; - else - return bytes*2; - } - - /// \internal - struct SharedString - { - SimpleMutex *refCountMutex; - unsigned int refCount; - size_t bytesUsed; - char *bigString; - char *c_str; - char smallString[128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2]; - }; - - /// \internal - RakString( SharedString *_sharedString ); - - /// \internal - SharedString *sharedString; - -// static SimpleMutex poolMutex; -// static DataStructures::MemoryPool pool; - /// \internal - static SharedString emptyString; - - //static SharedString *sharedStringFreeList; - //static unsigned int sharedStringFreeListAllocationCount; - /// \internal - /// List of free objects to reduce memory reallocations - static DataStructures::List freeList; - - static int RakStringComp( RakString const &key, RakString const &data ); - - static void LockMutex(void); - static void UnlockMutex(void); - -protected: - void Allocate(size_t len); - void Assign(const char *str); - void Assign(const char *str, va_list ap); - - void Clone(void); - void Free(void); - unsigned char ToLower(unsigned char c); - unsigned char ToUpper(unsigned char c); - void Realloc(SharedString *sharedString, size_t bytes); -}; - -} - -const RakNet::RakString RAK_DLL_EXPORT operator+(const RakNet::RakString &lhs, const RakNet::RakString &rhs); - - -#endif +#pragma once + +#include "Export.h" +#include "DS_List.h" +#include "RakNetTypes.h" // int64_t +#include +#include "stdarg.h" + + +#ifdef _WIN32 + + + +#include "WindowsIncludes.h" +#endif + +namespace RakNet +{ +/// Forward declarations +class SimpleMutex; +class BitStream; + +/// \brief String class +/// \details Has the following improvements over std::string +/// -Reference counting: Suitable to store in lists +/// -Variadic assignment operator +/// -Doesn't cause linker errors +class RAK_DLL_EXPORT RakString +{ +public: + // Constructors + RakString(); + RakString(char input); + RakString(unsigned char input); + RakString(const unsigned char *format, ...); + RakString(const char *format, ...); + ~RakString(); + RakString( const RakString & rhs); + + /// Implicit return of const char* + operator const char* () const {return sharedString->c_str;} + + /// Same as std::string::c_str + const char *C_String(void) const {return sharedString->c_str;} + + // Lets you modify the string. Do not make the string longer - however, you can make it shorter, or change the contents. + // Pointer is only valid in the scope of RakString itself + char *C_StringUnsafe(void) {Clone(); return sharedString->c_str;} + + /// Assigment operators + RakString& operator = ( const RakString& rhs ); + RakString& operator = ( const char *str ); + RakString& operator = ( char *str ); + RakString& operator = ( const unsigned char *str ); + RakString& operator = ( char unsigned *str ); + RakString& operator = ( const char c ); + + /// Concatenation + RakString& operator +=( const RakString& rhs); + RakString& operator += ( const char *str ); + RakString& operator += ( char *str ); + RakString& operator += ( const unsigned char *str ); + RakString& operator += ( char unsigned *str ); + RakString& operator += ( const char c ); + + /// Character index. Do not use to change the string however. + unsigned char operator[] ( const unsigned int position ) const; + +#ifdef _WIN32 + // Return as Wide char + // Deallocate with DeallocWideChar + WCHAR * ToWideChar(void); + void DeallocWideChar(WCHAR * w); +#endif + + ///String class find replacement + ///Searches the string for the content specified in stringToFind and returns the position of the first occurrence in the string. + ///Search only includes characters on or after position pos, ignoring any possible occurrences in previous locations. + /// \param[in] stringToFind The string to find inside of this object's string + /// \param[in] pos The position in the string to start the search + /// \return Returns the position of the first occurrence in the string. + size_t Find(const char *stringToFind,size_t pos = 0 ); + + /// Equality + bool operator==(const RakString &rhs) const; + bool operator==(const char *str) const; + bool operator==(char *str) const; + + // Comparison + bool operator < ( const RakString& right ) const; + bool operator <= ( const RakString& right ) const; + bool operator > ( const RakString& right ) const; + bool operator >= ( const RakString& right ) const; + + /// Inequality + bool operator!=(const RakString &rhs) const; + bool operator!=(const char *str) const; + bool operator!=(char *str) const; + + /// Change all characters to lowercase + const char * ToLower(void); + + /// Change all characters to uppercase + const char * ToUpper(void); + + /// Set the value of the string + void Set(const char *format, ...); + + /// Sets a copy of a substring of str as the new content. The substring is the portion of str + /// that begins at the character position pos and takes up to n characters + /// (it takes less than n if the end of str is reached before). + /// \param[in] str The string to copy in + /// \param[in] pos The position on str to start the copy + /// \param[in] n How many chars to copy + /// \return Returns the string, note that the current string is set to that value as well + RakString Assign(const char *str,size_t pos, size_t n ); + + /// Returns if the string is empty. Also, C_String() would return "" + bool IsEmpty(void) const; + + /// Returns the length of the string + size_t GetLength(void) const; + size_t GetLengthUTF8(void) const; + + /// Replace character(s) in starting at index, for count, with c + void Replace(unsigned index, unsigned count, unsigned char c); + + /// Replace character at index with c + void SetChar( unsigned index, unsigned char c ); + + /// Replace character at index with string s + void SetChar( unsigned index, RakNet::RakString s ); + + /// Make sure string is no longer than \a length + void Truncate(unsigned int length); + void TruncateUTF8(unsigned int length); + + // Gets the substring starting at index for count characters + RakString SubStr(unsigned int index, unsigned int count) const; + + /// Erase characters out of the string at index for count + void Erase(unsigned int index, unsigned int count); + + /// Set the first instance of c with a NULL terminator + void TerminateAtFirstCharacter(char c); + /// Set the last instance of c with a NULL terminator + void TerminateAtLastCharacter(char c); + + /// Remove all instances of c + void RemoveCharacter(char c); + + /// Create a RakString with a value, without doing printf style parsing + /// Equivalent to assignment operator + static RakNet::RakString NonVariadic(const char *str); + + /// Has the string into an unsigned int + static unsigned long ToInteger(const char *str); + static unsigned long ToInteger(const RakString &rs); + + // Like strncat, but for a fixed length + void AppendBytes(const char *bytes, unsigned int count); + + /// Compare strings (case sensitive) + int StrCmp(const RakString &rhs) const; + + /// Compare strings (not case sensitive) + int StrICmp(const RakString &rhs) const; + + /// Clear the string + void Clear(void); + + /// Print the string to the screen + void Printf(void); + + /// Print the string to a file + void FPrintf(FILE *fp); + + /// Does the given IP address match the IP address encoded into this string, accounting for wildcards? + bool IPAddressMatch(const char *IP); + + /// Does the string contain non-printable characters other than spaces? + bool ContainsNonprintableExceptSpaces(void) const; + + /// Is this a valid email address? + bool IsEmailAddress(void) const; + + /// URL Encode the string. See http://www.codeguru.com/cpp/cpp/cpp_mfc/article.php/c4029/ + RakNet::RakString& URLEncode(void); + + /// URL decode the string + RakNet::RakString& URLDecode(void); + + /// https://servers.api.rackspacecloud.com/v1.0 to https://, servers.api.rackspacecloud.com, /v1.0 + void SplitURI(RakNet::RakString &header, RakNet::RakString &domain, RakNet::RakString &path); + + /// Scan for quote, double quote, and backslash and prepend with backslash + RakNet::RakString& SQLEscape(void); + + /// Fix to be a file path, ending with / + RakNet::RakString& MakeFilePath(void); + + /// RakString uses a freeList of old no-longer used strings + /// Call this function to clear this memory on shutdown + static void FreeMemory(void); + /// \internal + static void FreeMemoryNoMutex(void); + + /// Serialize to a bitstream, uncompressed (slightly faster) + /// \param[out] bs Bitstream to serialize to + void Serialize(BitStream *bs) const; + + /// Static version of the Serialize function + static void Serialize(const char *str, BitStream *bs); + + /// Serialize to a bitstream, compressed (better bandwidth usage) + /// \param[out] bs Bitstream to serialize to + /// \param[in] languageId languageId to pass to the StringCompressor class + /// \param[in] writeLanguageId encode the languageId variable in the stream. If false, 0 is assumed, and DeserializeCompressed will not look for this variable in the stream (saves bandwidth) + /// \pre StringCompressor::AddReference must have been called to instantiate the class (Happens automatically from RakPeer::Startup()) + void SerializeCompressed(BitStream *bs, uint8_t languageId=0, bool writeLanguageId=false) const; + + /// Static version of the SerializeCompressed function + static void SerializeCompressed(const char *str, BitStream *bs, uint8_t languageId=0, bool writeLanguageId=false); + + /// Deserialize what was written by Serialize + /// \param[in] bs Bitstream to serialize from + /// \return true if the deserialization was successful + bool Deserialize(BitStream *bs); + + /// Static version of the Deserialize() function + static bool Deserialize(char *str, BitStream *bs); + + /// Deserialize compressed string, written by SerializeCompressed + /// \param[in] bs Bitstream to serialize from + /// \param[in] readLanguageId If true, looks for the variable langaugeId in the data stream. Must match what was passed to SerializeCompressed + /// \return true if the deserialization was successful + /// \pre StringCompressor::AddReference must have been called to instantiate the class (Happens automatically from RakPeer::Startup()) + bool DeserializeCompressed(BitStream *bs, bool readLanguageId=false); + + /// Static version of the DeserializeCompressed() function + static bool DeserializeCompressed(char *str, BitStream *bs, bool readLanguageId=false); + + static const char *ToString(int64_t i); + static const char *ToString(uint64_t i); + + /// \internal + static size_t GetSizeToAllocate(size_t bytes) + { + const size_t smallStringSize = 128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2; + if (bytes<=smallStringSize) + return smallStringSize; + else + return bytes*2; + } + + /// \internal + struct SharedString + { + SimpleMutex *refCountMutex; + unsigned int refCount; + size_t bytesUsed; + char *bigString; + char *c_str; + char smallString[128-sizeof(unsigned int)-sizeof(size_t)-sizeof(char*)*2]; + }; + + /// \internal + RakString( SharedString *_sharedString ); + + /// \internal + SharedString *sharedString; + +// static SimpleMutex poolMutex; +// static DataStructures::MemoryPool pool; + /// \internal + static SharedString emptyString; + + //static SharedString *sharedStringFreeList; + //static unsigned int sharedStringFreeListAllocationCount; + /// \internal + /// List of free objects to reduce memory reallocations + static DataStructures::List freeList; + + static int RakStringComp( RakString const &key, RakString const &data ); + + static void LockMutex(void); + static void UnlockMutex(void); + +protected: + void Allocate(size_t len); + void Assign(const char *str); + void Assign(const char *str, va_list ap); + + void Clone(void); + void Free(void); + unsigned char ToLower(unsigned char c); + unsigned char ToUpper(unsigned char c); + void Realloc(SharedString *sharedString, size_t bytes); +}; + +} + +const RakNet::RakString RAK_DLL_EXPORT operator+(const RakNet::RakString &lhs, const RakNet::RakString &rhs); + + diff --git a/src/raknet/RakThread.h b/src/raknet/RakThread.h index e6bf005..cc9d60b 100755 --- a/src/raknet/RakThread.h +++ b/src/raknet/RakThread.h @@ -1,88 +1,86 @@ -#ifndef __RAK_THREAD_H -#define __RAK_THREAD_H - -#if defined(_WIN32_WCE) -#include "WindowsIncludes.h" -#endif - -#include "Export.h" - - - - - - -namespace RakNet -{ - -/// To define a thread, use RAK_THREAD_DECLARATION(functionName); -#if defined(_WIN32_WCE) -#define RAK_THREAD_DECLARATION(functionName) DWORD WINAPI functionName(LPVOID arguments) - - -#elif defined(_WIN32) -#define RAK_THREAD_DECLARATION(functionName) unsigned __stdcall functionName( void* arguments ) - - -#else -#define RAK_THREAD_DECLARATION(functionName) void* functionName( void* arguments ) -#endif - -class RAK_DLL_EXPORT RakThread -{ -public: - - - - - /// Create a thread, simplified to be cross platform without all the extra junk - /// To then start that thread, call RakCreateThread(functionName, arguments); - /// \param[in] start_address Function you want to call - /// \param[in] arglist Arguments to pass to the function - /// \return 0=success. >0 = error code - - /* - nice value Win32 Priority - -20 to -16 THREAD_PRIORITY_HIGHEST - -15 to -6 THREAD_PRIORITY_ABOVE_NORMAL - -5 to +4 THREAD_PRIORITY_NORMAL - +5 to +14 THREAD_PRIORITY_BELOW_NORMAL - +15 to +19 THREAD_PRIORITY_LOWEST - */ -#if defined(_WIN32_WCE) - static int Create( LPTHREAD_START_ROUTINE start_address, void *arglist, int priority=0); - - -#elif defined(_WIN32) - static int Create( unsigned __stdcall start_address( void* ), void *arglist, int priority=0); - - - -#else - static int Create( void* start_address( void* ), void *arglist, int priority=0); -#endif - - - - - - - - - - - - - - - - - - - - -}; - -} - -#endif +#pragma once + +#if defined(_WIN32_WCE) +#include "WindowsIncludes.h" +#endif + +#include "Export.h" + + + + + + +namespace RakNet +{ + +/// To define a thread, use RAK_THREAD_DECLARATION(functionName); +#if defined(_WIN32_WCE) +#define RAK_THREAD_DECLARATION(functionName) DWORD WINAPI functionName(LPVOID arguments) + + +#elif defined(_WIN32) +#define RAK_THREAD_DECLARATION(functionName) unsigned __stdcall functionName( void* arguments ) + + +#else +#define RAK_THREAD_DECLARATION(functionName) void* functionName( void* arguments ) +#endif + +class RAK_DLL_EXPORT RakThread +{ +public: + + + + + /// Create a thread, simplified to be cross platform without all the extra junk + /// To then start that thread, call RakCreateThread(functionName, arguments); + /// \param[in] start_address Function you want to call + /// \param[in] arglist Arguments to pass to the function + /// \return 0=success. >0 = error code + + /* + nice value Win32 Priority + -20 to -16 THREAD_PRIORITY_HIGHEST + -15 to -6 THREAD_PRIORITY_ABOVE_NORMAL + -5 to +4 THREAD_PRIORITY_NORMAL + +5 to +14 THREAD_PRIORITY_BELOW_NORMAL + +15 to +19 THREAD_PRIORITY_LOWEST + */ +#if defined(_WIN32_WCE) + static int Create( LPTHREAD_START_ROUTINE start_address, void *arglist, int priority=0); + + +#elif defined(_WIN32) + static int Create( unsigned __stdcall start_address( void* ), void *arglist, int priority=0); + + + +#else + static int Create( void* start_address( void* ), void *arglist, int priority=0); +#endif + + + + + + + + + + + + + + + + + + + + +}; + +} + diff --git a/src/raknet/RakWString.h b/src/raknet/RakWString.h index e3baa7e..8772467 100755 --- a/src/raknet/RakWString.h +++ b/src/raknet/RakWString.h @@ -1,113 +1,111 @@ -#ifndef __RAK_W_STRING_H -#define __RAK_W_STRING_H - -#include "Export.h" -#include "RakNetTypes.h" // int64_t -#include "RakString.h" - -#ifdef _WIN32 - - - -#include "WindowsIncludes.h" -#endif - -namespace RakNet -{ - /// \brief String class for Unicode - class RAK_DLL_EXPORT RakWString - { - public: - // Constructors - RakWString(); - RakWString( const RakString &right ); - RakWString( const wchar_t *input ); - RakWString( const RakWString & right); - RakWString( const char *input ); - ~RakWString(); - - /// Implicit return of wchar_t* - operator wchar_t* () const {if (c_str) return c_str; return (wchar_t*) L"";} - - /// Same as std::string::c_str - const wchar_t* C_String(void) const {if (c_str) return c_str; return (const wchar_t*) L"";} - - /// Assignment operators - RakWString& operator = ( const RakWString& right ); - RakWString& operator = ( const RakString& right ); - RakWString& operator = ( const wchar_t * const str ); - RakWString& operator = ( wchar_t *str ); - RakWString& operator = ( const char * const str ); - RakWString& operator = ( char *str ); - - /// Concatenation - RakWString& operator +=( const RakWString& right); - RakWString& operator += ( const wchar_t * const right ); - RakWString& operator += ( wchar_t *right ); - - /// Equality - bool operator==(const RakWString &right) const; - - // Comparison - bool operator < ( const RakWString& right ) const; - bool operator <= ( const RakWString& right ) const; - bool operator > ( const RakWString& right ) const; - bool operator >= ( const RakWString& right ) const; - - /// Inequality - bool operator!=(const RakWString &right) const; - - /// Set the value of the string - void Set( wchar_t *str ); - - /// Returns if the string is empty. Also, C_String() would return "" - bool IsEmpty(void) const; - - /// Returns the length of the string - size_t GetLength(void) const; - - /// Has the string into an unsigned int - static unsigned long ToInteger(const RakWString &rs); - - /// Compare strings (case sensitive) - int StrCmp(const RakWString &right) const; - - /// Compare strings (not case sensitive) - int StrICmp(const RakWString &right) const; - - /// Clear the string - void Clear(void); - - /// Print the string to the screen - void Printf(void); - - /// Print the string to a file - void FPrintf(FILE *fp); - - /// Serialize to a bitstream, uncompressed (slightly faster) - /// \param[out] bs Bitstream to serialize to - void Serialize(BitStream *bs) const; - - /// Static version of the Serialize function - static void Serialize(const wchar_t * const str, BitStream *bs); - - /// Deserialize what was written by Serialize - /// \param[in] bs Bitstream to serialize from - /// \return true if the deserialization was successful - bool Deserialize(BitStream *bs); - - /// Static version of the Deserialize() function - static bool Deserialize(wchar_t *str, BitStream *bs); - - - protected: - wchar_t* c_str; - size_t c_strCharLength; - }; - -} - -const RakNet::RakWString RAK_DLL_EXPORT operator+(const RakNet::RakWString &lhs, const RakNet::RakWString &rhs); - - -#endif +#pragma once + +#include "Export.h" +#include "RakNetTypes.h" // int64_t +#include "RakString.h" + +#ifdef _WIN32 + + + +#include "WindowsIncludes.h" +#endif + +namespace RakNet +{ + /// \brief String class for Unicode + class RAK_DLL_EXPORT RakWString + { + public: + // Constructors + RakWString(); + RakWString( const RakString &right ); + RakWString( const wchar_t *input ); + RakWString( const RakWString & right); + RakWString( const char *input ); + ~RakWString(); + + /// Implicit return of wchar_t* + operator wchar_t* () const {if (c_str) return c_str; return (wchar_t*) L"";} + + /// Same as std::string::c_str + const wchar_t* C_String(void) const {if (c_str) return c_str; return (const wchar_t*) L"";} + + /// Assignment operators + RakWString& operator = ( const RakWString& right ); + RakWString& operator = ( const RakString& right ); + RakWString& operator = ( const wchar_t * const str ); + RakWString& operator = ( wchar_t *str ); + RakWString& operator = ( const char * const str ); + RakWString& operator = ( char *str ); + + /// Concatenation + RakWString& operator +=( const RakWString& right); + RakWString& operator += ( const wchar_t * const right ); + RakWString& operator += ( wchar_t *right ); + + /// Equality + bool operator==(const RakWString &right) const; + + // Comparison + bool operator < ( const RakWString& right ) const; + bool operator <= ( const RakWString& right ) const; + bool operator > ( const RakWString& right ) const; + bool operator >= ( const RakWString& right ) const; + + /// Inequality + bool operator!=(const RakWString &right) const; + + /// Set the value of the string + void Set( wchar_t *str ); + + /// Returns if the string is empty. Also, C_String() would return "" + bool IsEmpty(void) const; + + /// Returns the length of the string + size_t GetLength(void) const; + + /// Has the string into an unsigned int + static unsigned long ToInteger(const RakWString &rs); + + /// Compare strings (case sensitive) + int StrCmp(const RakWString &right) const; + + /// Compare strings (not case sensitive) + int StrICmp(const RakWString &right) const; + + /// Clear the string + void Clear(void); + + /// Print the string to the screen + void Printf(void); + + /// Print the string to a file + void FPrintf(FILE *fp); + + /// Serialize to a bitstream, uncompressed (slightly faster) + /// \param[out] bs Bitstream to serialize to + void Serialize(BitStream *bs) const; + + /// Static version of the Serialize function + static void Serialize(const wchar_t * const str, BitStream *bs); + + /// Deserialize what was written by Serialize + /// \param[in] bs Bitstream to serialize from + /// \return true if the deserialization was successful + bool Deserialize(BitStream *bs); + + /// Static version of the Deserialize() function + static bool Deserialize(wchar_t *str, BitStream *bs); + + + protected: + wchar_t* c_str; + size_t c_strCharLength; + }; + +} + +const RakNet::RakWString RAK_DLL_EXPORT operator+(const RakNet::RakWString &lhs, const RakNet::RakWString &rhs); + + diff --git a/src/raknet/SendToThread.h b/src/raknet/SendToThread.h index 676a5f4..3950884 100755 --- a/src/raknet/SendToThread.h +++ b/src/raknet/SendToThread.h @@ -1,47 +1,45 @@ -#ifndef __SENDTO_THREAD -#define __SENDTO_THREAD - -#include "RakNetDefines.h" - -#ifdef USE_THREADED_SEND - -#include "InternalPacket.h" -#include "SocketLayer.h" -#include "DS_ThreadsafeAllocatingQueue.h" -#include "ThreadPool.h" - -namespace RakNet -{ -class SendToThread -{ -public: - SendToThread(); - ~SendToThread(); - - struct SendToThreadBlock - { - SOCKET s; - SystemAddress systemAddress; - unsigned short remotePortRakNetWasStartedOn_PS3; - unsigned int extraSocketOptions; - char data[MAXIMUM_MTU_SIZE]; - unsigned short dataWriteOffset; - }; - - static SendToThreadBlock* AllocateBlock(void); - static void ProcessBlock(SendToThreadBlock* threadedSend); - - static void AddRef(void); - static void Deref(void); - static DataStructures::ThreadsafeAllocatingQueue objectQueue; -protected: - static int refCount; - static ThreadPool threadPool; - -}; -} - - -#endif - -#endif +#pragma once + +#include "RakNetDefines.h" + +#ifdef USE_THREADED_SEND + +#include "InternalPacket.h" +#include "SocketLayer.h" +#include "DS_ThreadsafeAllocatingQueue.h" +#include "ThreadPool.h" + +namespace RakNet +{ +class SendToThread +{ +public: + SendToThread(); + ~SendToThread(); + + struct SendToThreadBlock + { + SOCKET s; + SystemAddress systemAddress; + unsigned short remotePortRakNetWasStartedOn_PS3; + unsigned int extraSocketOptions; + char data[MAXIMUM_MTU_SIZE]; + unsigned short dataWriteOffset; + }; + + static SendToThreadBlock* AllocateBlock(void); + static void ProcessBlock(SendToThreadBlock* threadedSend); + + static void AddRef(void); + static void Deref(void); + static DataStructures::ThreadsafeAllocatingQueue objectQueue; +protected: + static int refCount; + static ThreadPool threadPool; + +}; +} + + +#endif + diff --git a/src/raknet/SignaledEvent.h b/src/raknet/SignaledEvent.h index b744b40..fdf5024 100755 --- a/src/raknet/SignaledEvent.h +++ b/src/raknet/SignaledEvent.h @@ -1,59 +1,57 @@ -#ifndef __SIGNALED_EVENT_H -#define __SIGNALED_EVENT_H - - - -#if defined(_WIN32) -#include - - - -#else - #include - #include - #include "SimpleMutex.h" - - - - -#endif - -#include "Export.h" - -namespace RakNet -{ - -class RAK_DLL_EXPORT SignaledEvent -{ -public: - SignaledEvent(); - ~SignaledEvent(); - - void InitEvent(void); - void CloseEvent(void); - void SetEvent(void); - void WaitOnEvent(int timeoutMs); - -protected: -#ifdef _WIN32 - HANDLE eventList; - - - - - -#else - SimpleMutex isSignaledMutex; - bool isSignaled; -#if !defined(ANDROID) - pthread_condattr_t condAttr; -#endif - pthread_cond_t eventList; - pthread_mutex_t hMutex; - pthread_mutexattr_t mutexAttr; -#endif -}; - -} // namespace RakNet - -#endif +#pragma once + + + +#if defined(_WIN32) +#include + + + +#else + #include + #include + #include "SimpleMutex.h" + + + + +#endif + +#include "Export.h" + +namespace RakNet +{ + +class RAK_DLL_EXPORT SignaledEvent +{ +public: + SignaledEvent(); + ~SignaledEvent(); + + void InitEvent(void); + void CloseEvent(void); + void SetEvent(void); + void WaitOnEvent(int timeoutMs); + +protected: +#ifdef _WIN32 + HANDLE eventList; + + + + + +#else + SimpleMutex isSignaledMutex; + bool isSignaled; +#if !defined(ANDROID) + pthread_condattr_t condAttr; +#endif + pthread_cond_t eventList; + pthread_mutex_t hMutex; + pthread_mutexattr_t mutexAttr; +#endif +}; + +} // namespace RakNet + diff --git a/src/raknet/SocketDefines.h b/src/raknet/SocketDefines.h index f6548ab..5e03321 100755 --- a/src/raknet/SocketDefines.h +++ b/src/raknet/SocketDefines.h @@ -1,69 +1,67 @@ -#ifndef __SOCKET_DEFINES_H -#define __SOCKET_DEFINES_H - -/// Internal - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #if defined(_WIN32) - #define closesocket__ closesocket - #define select__ select - #else - #define closesocket__ close - #define select__ select - #endif -#define accept__ accept -#define connect__ connect -#define socket__ socket -#define bind__ bind -#define getsockname__ getsockname -#define getsockopt__ getsockopt -#define inet_addr__ inet_addr -#define ioctlsocket__ ioctlsocket -#define listen__ listen -#define recv__ recv -#define recvfrom__ recvfrom -#define sendto__ sendto -#define send__ send -#define setsockopt__ setsockopt -#define shutdown__ shutdown -#define WSASendTo__ WSASendTo - - -#endif +#pragma once + +/// Internal + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #if defined(_WIN32) + #define closesocket__ closesocket + #define select__ select + #else + #define closesocket__ close + #define select__ select + #endif +#define accept__ accept +#define connect__ connect +#define socket__ socket +#define bind__ bind +#define getsockname__ getsockname +#define getsockopt__ getsockopt +#define inet_addr__ inet_addr +#define ioctlsocket__ ioctlsocket +#define listen__ listen +#define recv__ recv +#define recvfrom__ recvfrom +#define sendto__ sendto +#define send__ send +#define setsockopt__ setsockopt +#define shutdown__ shutdown +#define WSASendTo__ WSASendTo + + diff --git a/src/raknet/SuperFastHash.h b/src/raknet/SuperFastHash.h index fd8463c..2279a3d 100755 --- a/src/raknet/SuperFastHash.h +++ b/src/raknet/SuperFastHash.h @@ -1,17 +1,15 @@ -#ifndef __SUPER_FAST_HASH_H -#define __SUPER_FAST_HASH_H - -#include -#include "NativeTypes.h" - -// From http://www.azillionmonkeys.com/qed/hash.html -// Author of main code is Paul Hsieh -// I just added some convenience functions -// Also note http://burtleburtle.net/bob/hash/doobs.html, which shows that this is 20% faster than the one on that page but has more collisions - -uint32_t SuperFastHash (const char * data, int length); -uint32_t SuperFastHashIncremental (const char * data, int len, unsigned int lastHash ); -uint32_t SuperFastHashFile (const char * filename); -uint32_t SuperFastHashFilePtr (FILE *fp); - -#endif +#pragma once + +#include +#include "NativeTypes.h" + +// From http://www.azillionmonkeys.com/qed/hash.html +// Author of main code is Paul Hsieh +// I just added some convenience functions +// Also note http://burtleburtle.net/bob/hash/doobs.html, which shows that this is 20% faster than the one on that page but has more collisions + +uint32_t SuperFastHash (const char * data, int length); +uint32_t SuperFastHashIncremental (const char * data, int len, unsigned int lastHash ); +uint32_t SuperFastHashFile (const char * filename); +uint32_t SuperFastHashFilePtr (FILE *fp); + diff --git a/src/raknet/TableSerializer.h b/src/raknet/TableSerializer.h index fb15bf8..587b829 100755 --- a/src/raknet/TableSerializer.h +++ b/src/raknet/TableSerializer.h @@ -1,208 +1,207 @@ -#ifndef __TABLE_SERIALIZER_H -#define __TABLE_SERIALIZER_H - -#include "RakMemoryOverride.h" -#include "DS_Table.h" -#include "Export.h" - -namespace RakNet -{ - class BitStream; -} - -namespace RakNet -{ - -class RAK_DLL_EXPORT TableSerializer -{ -public: - static void SerializeTable(DataStructures::Table *in, RakNet::BitStream *out); - static bool DeserializeTable(unsigned char *serializedTable, unsigned int dataLength, DataStructures::Table *out); - static bool DeserializeTable(RakNet::BitStream *in, DataStructures::Table *out); - static void SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out); - static void SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out, DataStructures::List &skipColumnIndices); - static bool DeserializeColumns(RakNet::BitStream *in, DataStructures::Table *out); - static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, RakNet::BitStream *out); - static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, RakNet::BitStream *out, DataStructures::List &skipColumnIndices); - static bool DeserializeRow(RakNet::BitStream *in, DataStructures::Table *out); - static void SerializeCell(RakNet::BitStream *out, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType); - static bool DeserializeCell(RakNet::BitStream *in, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType); - static void SerializeFilterQuery(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query); - // Note that this allocates query->cell->c! - static bool DeserializeFilterQuery(RakNet::BitStream *out, DataStructures::Table::FilterQuery *query); - static void SerializeFilterQueryList(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query, unsigned int numQueries, unsigned int maxQueries); - // Note that this allocates queries, cells, and query->cell->c!. Use DeallocateQueryList to free. - static bool DeserializeFilterQueryList(RakNet::BitStream *out, DataStructures::Table::FilterQuery **query, unsigned int *numQueries, unsigned int maxQueries, int allocateExtraQueries=0); - static void DeallocateQueryList(DataStructures::Table::FilterQuery *query, unsigned int numQueries); -}; - -} // namespace RakNet - -#endif - -// Test code for the table -/* -#include "LightweightDatabaseServer.h" -#include "LightweightDatabaseClient.h" -#include "TableSerializer.h" -#include "BitStream.h" -#include "StringCompressor.h" -#include "DS_Table.h" -void main(void) -{ - DataStructures::Table table; - DataStructures::Table::Row *row; - unsigned int dummydata=12345; - - // Add columns Name (string), IP (binary), score (int), and players (int). - table.AddColumn("Name", DataStructures::Table::STRING); - table.AddColumn("IP", DataStructures::Table::BINARY); - table.AddColumn("Score", DataStructures::Table::NUMERIC); - table.AddColumn("Players", DataStructures::Table::NUMERIC); - table.AddColumn("Empty Test Column", DataStructures::Table::STRING); - RakAssert(table.GetColumnCount()==5); - row=table.AddRow(0); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,5); - row->UpdateCell(3,10); - //row->UpdateCell(4,"should be unique"); - - row=table.AddRow(1); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,5); - row->UpdateCell(3,15); - - row=table.AddRow(2); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,5); - row->UpdateCell(3,20); - - row=table.AddRow(3); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,15); - row->UpdateCell(3,5); - row->UpdateCell(4,"col index 4"); - - row=table.AddRow(4); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - //row->UpdateCell(2,25); - row->UpdateCell(3,30); - //row->UpdateCell(4,"should be unique"); - - row=table.AddRow(5); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - //row->UpdateCell(2,25); - row->UpdateCell(3,5); - //row->UpdateCell(4,"should be unique"); - - row=table.AddRow(6); - RakAssert(row); - row->UpdateCell(0,"Kevin Jenkins"); - row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); - row->UpdateCell(2,35); - //row->UpdateCell(3,40); - //row->UpdateCell(4,"should be unique"); - - row=table.AddRow(7); - RakAssert(row); - row->UpdateCell(0,"Bob Jenkins"); - - row=table.AddRow(8); - RakAssert(row); - row->UpdateCell(0,"Zack Jenkins"); - - // Test multi-column sorting - DataStructures::Table::Row *rows[30]; - DataStructures::Table::SortQuery queries[4]; - queries[0].columnIndex=0; - queries[0].operation=DataStructures::Table::QS_INCREASING_ORDER; - queries[1].columnIndex=1; - queries[1].operation=DataStructures::Table::QS_INCREASING_ORDER; - queries[2].columnIndex=2; - queries[2].operation=DataStructures::Table::QS_INCREASING_ORDER; - queries[3].columnIndex=3; - queries[3].operation=DataStructures::Table::QS_DECREASING_ORDER; - table.SortTable(queries, 4, rows); - unsigned i; - char out[256]; - RAKNET_DEBUG_PRINTF("Sort: Ascending except for column index 3\n"); - for (i=0; i < table.GetRowCount(); i++) - { - table.PrintRow(out,256,',',true, rows[i]); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - - // Test query: - // Don't return column 3, and swap columns 0 and 2 - unsigned columnsToReturn[4]; - columnsToReturn[0]=2; - columnsToReturn[1]=1; - columnsToReturn[2]=0; - columnsToReturn[3]=4; - DataStructures::Table resultsTable; - table.QueryTable(columnsToReturn,4,0,0,&resultsTable); - RAKNET_DEBUG_PRINTF("Query: Don't return column 3, and swap columns 0 and 2:\n"); - for (i=0; i < resultsTable.GetRowCount(); i++) - { - resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - - // Test filter: - // Only return rows with column index 4 empty - DataStructures::Table::FilterQuery inclusionFilters[3]; - inclusionFilters[0].columnIndex=4; - inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY; - // inclusionFilters[0].cellValue; // Unused for IS_EMPTY - table.QueryTable(0,0,inclusionFilters,1,&resultsTable); - RAKNET_DEBUG_PRINTF("Filter: Only return rows with column index 4 empty:\n"); - for (i=0; i < resultsTable.GetRowCount(); i++) - { - resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - - // Column 5 empty and column 0 == Kevin Jenkins - inclusionFilters[0].columnIndex=4; - inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY; - inclusionFilters[1].columnIndex=0; - inclusionFilters[1].operation=DataStructures::Table::QF_EQUAL; - inclusionFilters[1].cellValue.Set("Kevin Jenkins"); - table.QueryTable(0,0,inclusionFilters,2,&resultsTable); - RAKNET_DEBUG_PRINTF("Filter: Column 5 empty and column 0 == Kevin Jenkins:\n"); - for (i=0; i < resultsTable.GetRowCount(); i++) - { - resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - - RakNet::BitStream bs; - RAKNET_DEBUG_PRINTF("PreSerialize:\n"); - for (i=0; i < table.GetRowCount(); i++) - { - table.PrintRow(out,256,',',true, table.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - StringCompressor::AddReference(); - TableSerializer::Serialize(&table, &bs); - TableSerializer::Deserialize(&bs, &table); - StringCompressor::RemoveReference(); - RAKNET_DEBUG_PRINTF("PostDeserialize:\n"); - for (i=0; i < table.GetRowCount(); i++) - { - table.PrintRow(out,256,',',true, table.GetRowByIndex(i)); - RAKNET_DEBUG_PRINTF("%s\n", out); - } - int a=5; -} -*/ +#pragma once + +#include "RakMemoryOverride.h" +#include "DS_Table.h" +#include "Export.h" + +namespace RakNet +{ + class BitStream; +} + +namespace RakNet +{ + +class RAK_DLL_EXPORT TableSerializer +{ +public: + static void SerializeTable(DataStructures::Table *in, RakNet::BitStream *out); + static bool DeserializeTable(unsigned char *serializedTable, unsigned int dataLength, DataStructures::Table *out); + static bool DeserializeTable(RakNet::BitStream *in, DataStructures::Table *out); + static void SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out); + static void SerializeColumns(DataStructures::Table *in, RakNet::BitStream *out, DataStructures::List &skipColumnIndices); + static bool DeserializeColumns(RakNet::BitStream *in, DataStructures::Table *out); + static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, RakNet::BitStream *out); + static void SerializeRow(DataStructures::Table::Row *in, unsigned keyIn, const DataStructures::List &columns, RakNet::BitStream *out, DataStructures::List &skipColumnIndices); + static bool DeserializeRow(RakNet::BitStream *in, DataStructures::Table *out); + static void SerializeCell(RakNet::BitStream *out, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType); + static bool DeserializeCell(RakNet::BitStream *in, DataStructures::Table::Cell *cell, DataStructures::Table::ColumnType columnType); + static void SerializeFilterQuery(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query); + // Note that this allocates query->cell->c! + static bool DeserializeFilterQuery(RakNet::BitStream *out, DataStructures::Table::FilterQuery *query); + static void SerializeFilterQueryList(RakNet::BitStream *in, DataStructures::Table::FilterQuery *query, unsigned int numQueries, unsigned int maxQueries); + // Note that this allocates queries, cells, and query->cell->c!. Use DeallocateQueryList to free. + static bool DeserializeFilterQueryList(RakNet::BitStream *out, DataStructures::Table::FilterQuery **query, unsigned int *numQueries, unsigned int maxQueries, int allocateExtraQueries=0); + static void DeallocateQueryList(DataStructures::Table::FilterQuery *query, unsigned int numQueries); +}; + +} // namespace RakNet + +#endif + +// Test code for the table +/* +#include "LightweightDatabaseServer.h" +#include "LightweightDatabaseClient.h" +#include "TableSerializer.h" +#include "BitStream.h" +#include "StringCompressor.h" +#include "DS_Table.h" +void main(void) +{ + DataStructures::Table table; + DataStructures::Table::Row *row; + unsigned int dummydata=12345; + + // Add columns Name (string), IP (binary), score (int), and players (int). + table.AddColumn("Name", DataStructures::Table::STRING); + table.AddColumn("IP", DataStructures::Table::BINARY); + table.AddColumn("Score", DataStructures::Table::NUMERIC); + table.AddColumn("Players", DataStructures::Table::NUMERIC); + table.AddColumn("Empty Test Column", DataStructures::Table::STRING); + RakAssert(table.GetColumnCount()==5); + row=table.AddRow(0); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,5); + row->UpdateCell(3,10); + //row->UpdateCell(4,"should be unique"); + + row=table.AddRow(1); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,5); + row->UpdateCell(3,15); + + row=table.AddRow(2); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,5); + row->UpdateCell(3,20); + + row=table.AddRow(3); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,15); + row->UpdateCell(3,5); + row->UpdateCell(4,"col index 4"); + + row=table.AddRow(4); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + //row->UpdateCell(2,25); + row->UpdateCell(3,30); + //row->UpdateCell(4,"should be unique"); + + row=table.AddRow(5); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + //row->UpdateCell(2,25); + row->UpdateCell(3,5); + //row->UpdateCell(4,"should be unique"); + + row=table.AddRow(6); + RakAssert(row); + row->UpdateCell(0,"Kevin Jenkins"); + row->UpdateCell(1,sizeof(dummydata), (char*)&dummydata); + row->UpdateCell(2,35); + //row->UpdateCell(3,40); + //row->UpdateCell(4,"should be unique"); + + row=table.AddRow(7); + RakAssert(row); + row->UpdateCell(0,"Bob Jenkins"); + + row=table.AddRow(8); + RakAssert(row); + row->UpdateCell(0,"Zack Jenkins"); + + // Test multi-column sorting + DataStructures::Table::Row *rows[30]; + DataStructures::Table::SortQuery queries[4]; + queries[0].columnIndex=0; + queries[0].operation=DataStructures::Table::QS_INCREASING_ORDER; + queries[1].columnIndex=1; + queries[1].operation=DataStructures::Table::QS_INCREASING_ORDER; + queries[2].columnIndex=2; + queries[2].operation=DataStructures::Table::QS_INCREASING_ORDER; + queries[3].columnIndex=3; + queries[3].operation=DataStructures::Table::QS_DECREASING_ORDER; + table.SortTable(queries, 4, rows); + unsigned i; + char out[256]; + RAKNET_DEBUG_PRINTF("Sort: Ascending except for column index 3\n"); + for (i=0; i < table.GetRowCount(); i++) + { + table.PrintRow(out,256,',',true, rows[i]); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + + // Test query: + // Don't return column 3, and swap columns 0 and 2 + unsigned columnsToReturn[4]; + columnsToReturn[0]=2; + columnsToReturn[1]=1; + columnsToReturn[2]=0; + columnsToReturn[3]=4; + DataStructures::Table resultsTable; + table.QueryTable(columnsToReturn,4,0,0,&resultsTable); + RAKNET_DEBUG_PRINTF("Query: Don't return column 3, and swap columns 0 and 2:\n"); + for (i=0; i < resultsTable.GetRowCount(); i++) + { + resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + + // Test filter: + // Only return rows with column index 4 empty + DataStructures::Table::FilterQuery inclusionFilters[3]; + inclusionFilters[0].columnIndex=4; + inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY; + // inclusionFilters[0].cellValue; // Unused for IS_EMPTY + table.QueryTable(0,0,inclusionFilters,1,&resultsTable); + RAKNET_DEBUG_PRINTF("Filter: Only return rows with column index 4 empty:\n"); + for (i=0; i < resultsTable.GetRowCount(); i++) + { + resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + + // Column 5 empty and column 0 == Kevin Jenkins + inclusionFilters[0].columnIndex=4; + inclusionFilters[0].operation=DataStructures::Table::QF_IS_EMPTY; + inclusionFilters[1].columnIndex=0; + inclusionFilters[1].operation=DataStructures::Table::QF_EQUAL; + inclusionFilters[1].cellValue.Set("Kevin Jenkins"); + table.QueryTable(0,0,inclusionFilters,2,&resultsTable); + RAKNET_DEBUG_PRINTF("Filter: Column 5 empty and column 0 == Kevin Jenkins:\n"); + for (i=0; i < resultsTable.GetRowCount(); i++) + { + resultsTable.PrintRow(out,256,',',true, resultsTable.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + + RakNet::BitStream bs; + RAKNET_DEBUG_PRINTF("PreSerialize:\n"); + for (i=0; i < table.GetRowCount(); i++) + { + table.PrintRow(out,256,',',true, table.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + StringCompressor::AddReference(); + TableSerializer::Serialize(&table, &bs); + TableSerializer::Deserialize(&bs, &table); + StringCompressor::RemoveReference(); + RAKNET_DEBUG_PRINTF("PostDeserialize:\n"); + for (i=0; i < table.GetRowCount(); i++) + { + table.PrintRow(out,256,',',true, table.GetRowByIndex(i)); + RAKNET_DEBUG_PRINTF("%s\n", out); + } + int a=5; +} +*/ diff --git a/src/raknet/ThreadPool.h b/src/raknet/ThreadPool.h index 087460e..31799a1 100755 --- a/src/raknet/ThreadPool.h +++ b/src/raknet/ThreadPool.h @@ -1,620 +1,619 @@ -#ifndef __THREAD_POOL_H -#define __THREAD_POOL_H - -#include "RakMemoryOverride.h" -#include "DS_Queue.h" -#include "SimpleMutex.h" -#include "Export.h" -#include "RakThread.h" -#include "SignaledEvent.h" - -#ifdef _MSC_VER -#pragma warning( push ) -#endif - -class ThreadDataInterface -{ -public: - ThreadDataInterface() {} - virtual ~ThreadDataInterface() {} - - virtual void* PerThreadFactory(void *context)=0; - virtual void PerThreadDestructor(void* factoryResult, void *context)=0; -}; -/// A simple class to create worker threads that processes a queue of functions with data. -/// This class does not allocate or deallocate memory. It is up to the user to handle memory management. -/// InputType and OutputType are stored directly in a queue. For large structures, if you plan to delete from the middle of the queue, -/// you might wish to store pointers rather than the structures themselves so the array can shift efficiently. -template -struct RAK_DLL_EXPORT ThreadPool -{ - ThreadPool(); - ~ThreadPool(); - - /// Start the specified number of threads. - /// \param[in] numThreads The number of threads to start - /// \param[in] stackSize 0 for default (except on consoles). - /// \param[in] _perThreadInit User callback to return data stored per thread. Pass 0 if not needed. - /// \param[in] _perThreadDeinit User callback to destroy data stored per thread, created by _perThreadInit. Pass 0 if not needed. - /// \return True on success, false on failure. - bool StartThreads(int numThreads, int stackSize, void* (*_perThreadInit)()=0, void (*_perThreadDeinit)(void*)=0); - - // Alternate form of _perThreadDataFactory, _perThreadDataDestructor - void SetThreadDataInterface(ThreadDataInterface *tdi, void *context); - - /// Stops all threads - void StopThreads(void); - - /// Adds a function to a queue with data to pass to that function. This function will be called from the thread - /// Memory management is your responsibility! This class does not allocate or deallocate memory. - /// The best way to deallocate \a inputData is in userCallback. If you call EndThreads such that callbacks were not called, you - /// can iterate through the inputQueue and deallocate all pending input data there - /// The best way to deallocate output is as it is returned to you from GetOutput. Similarly, if you end the threads such that - /// not all output was returned, you can iterate through outputQueue and deallocate it there. - /// \param[in] workerThreadCallback The function to call from the thread - /// \param[in] inputData The parameter to pass to \a userCallback - void AddInput(OutputType (*workerThreadCallback)(InputType, bool *returnOutput, void* perThreadData), InputType inputData); - - /// Adds to the output queue - /// Use it if you want to inject output into the same queue that the system uses. Normally you would not use this. Consider it a convenience function. - /// \param[in] outputData The output to inject - void AddOutput(OutputType outputData); - - /// Returns true if output from GetOutput is waiting. - /// \return true if output is waiting, false otherwise - bool HasOutput(void); - - /// Inaccurate but fast version of HasOutput. If this returns true, you should still check HasOutput for the real value. - /// \return true if output is probably waiting, false otherwise - bool HasOutputFast(void); - - /// Returns true if input from GetInput is waiting. - /// \return true if input is waiting, false otherwise - bool HasInput(void); - - /// Inaccurate but fast version of HasInput. If this returns true, you should still check HasInput for the real value. - /// \return true if input is probably waiting, false otherwise - bool HasInputFast(void); - - /// Gets the output of a call to \a userCallback - /// HasOutput must return true before you call this function. Otherwise it will assert. - /// \return The output of \a userCallback. If you have different output signatures, it is up to you to encode the data to indicate this - OutputType GetOutput(void); - - /// Clears internal buffers - void Clear(void); - - /// Lock the input buffer before calling the functions InputSize, InputAtIndex, and RemoveInputAtIndex - /// It is only necessary to lock the input or output while the threads are running - void LockInput(void); - - /// Unlock the input buffer after you are done with the functions InputSize, GetInputAtIndex, and RemoveInputAtIndex - void UnlockInput(void); - - /// Length of the input queue - unsigned InputSize(void); - - /// Get the input at a specified index - InputType GetInputAtIndex(unsigned index); - - /// Remove input from a specific index. This does NOT do memory deallocation - it only removes the item from the queue - void RemoveInputAtIndex(unsigned index); - - /// Lock the output buffer before calling the functions OutputSize, OutputAtIndex, and RemoveOutputAtIndex - /// It is only necessary to lock the input or output while the threads are running - void LockOutput(void); - - /// Unlock the output buffer after you are done with the functions OutputSize, GetOutputAtIndex, and RemoveOutputAtIndex - void UnlockOutput(void); - - /// Length of the output queue - unsigned OutputSize(void); - - /// Get the output at a specified index - OutputType GetOutputAtIndex(unsigned index); - - /// Remove output from a specific index. This does NOT do memory deallocation - it only removes the item from the queue - void RemoveOutputAtIndex(unsigned index); - - /// Removes all items from the input queue - void ClearInput(void); - - /// Removes all items from the output queue - void ClearOutput(void); - - /// Are any of the threads working, or is input or output available? - bool IsWorking(void); - - /// The number of currently active threads. - int NumThreadsWorking(void); - - /// Did we call Start? - bool WasStarted(void); - - // Block until all threads are stopped. - bool Pause(void); - - // Continue running - void Resume(void); - -protected: - // It is valid to cancel input before it is processed. To do so, lock the inputQueue with inputQueueMutex, - // Scan the list, and remove the item you don't want. - RakNet::SimpleMutex inputQueueMutex, outputQueueMutex, workingThreadCountMutex, runThreadsMutex; - - void* (*perThreadDataFactory)(); - void (*perThreadDataDestructor)(void*); - - // inputFunctionQueue & inputQueue are paired arrays so if you delete from one at a particular index you must delete from the other - // at the same index - DataStructures::Queue inputFunctionQueue; - DataStructures::Queue inputQueue; - DataStructures::Queue outputQueue; - - ThreadDataInterface *threadDataInterface; - void *tdiContext; - - - template - friend RAK_THREAD_DECLARATION(WorkerThread); - - /* -#ifdef _WIN32 - friend unsigned __stdcall WorkerThread( LPVOID arguments ); -#else - friend void* WorkerThread( void* arguments ); -#endif - */ - - /// \internal - bool runThreads; - /// \internal - int numThreadsRunning; - /// \internal - int numThreadsWorking; - /// \internal - RakNet::SimpleMutex numThreadsRunningMutex; - - RakNet::SignaledEvent quitAndIncomingDataEvents; - -// #if defined(SN_TARGET_PSP2) -// RakNet::RakThread::UltUlThreadRuntime *runtime; -// #endif -}; - -#include "ThreadPool.h" -#include "RakSleep.h" -#ifdef _WIN32 - -#else -#include -#endif - -#ifdef _MSC_VER -#pragma warning(disable:4127) -#pragma warning( disable : 4701 ) // potentially uninitialized local variable 'inputData' used -#endif - -template -RAK_THREAD_DECLARATION(WorkerThread) -/* -#ifdef _WIN32 -unsigned __stdcall WorkerThread( LPVOID arguments ) -#else -void* WorkerThread( void* arguments ) -#endif -*/ -{ - - - - ThreadPool *threadPool = (ThreadPool*) arguments; - - - bool returnOutput; - ThreadOutputType (*userCallback)(ThreadInputType, bool *, void*); - ThreadInputType inputData; - ThreadOutputType callbackOutput; - - userCallback=0; - - void *perThreadData; - if (threadPool->perThreadDataFactory) - perThreadData=threadPool->perThreadDataFactory(); - else if (threadPool->threadDataInterface) - perThreadData=threadPool->threadDataInterface->PerThreadFactory(threadPool->tdiContext); - else - perThreadData=0; - - // Increase numThreadsRunning - threadPool->numThreadsRunningMutex.Lock(); - ++threadPool->numThreadsRunning; - threadPool->numThreadsRunningMutex.Unlock(); - - while (1) - { -#ifdef _WIN32 - if (userCallback==0) - { - threadPool->quitAndIncomingDataEvents.WaitOnEvent(INFINITE); - } -#endif - - threadPool->runThreadsMutex.Lock(); - if (threadPool->runThreads==false) - { - threadPool->runThreadsMutex.Unlock(); - break; - } - threadPool->runThreadsMutex.Unlock(); - - threadPool->workingThreadCountMutex.Lock(); - ++threadPool->numThreadsWorking; - threadPool->workingThreadCountMutex.Unlock(); - - // Read input data - userCallback=0; - threadPool->inputQueueMutex.Lock(); - if (threadPool->inputFunctionQueue.Size()) - { - userCallback=threadPool->inputFunctionQueue.Pop(); - inputData=threadPool->inputQueue.Pop(); - } - threadPool->inputQueueMutex.Unlock(); - - if (userCallback) - { - callbackOutput=userCallback(inputData, &returnOutput,perThreadData); - if (returnOutput) - { - threadPool->outputQueueMutex.Lock(); - threadPool->outputQueue.Push(callbackOutput, _FILE_AND_LINE_ ); - threadPool->outputQueueMutex.Unlock(); - } - } - - threadPool->workingThreadCountMutex.Lock(); - --threadPool->numThreadsWorking; - threadPool->workingThreadCountMutex.Unlock(); - } - - // Decrease numThreadsRunning - threadPool->numThreadsRunningMutex.Lock(); - --threadPool->numThreadsRunning; - threadPool->numThreadsRunningMutex.Unlock(); - - if (threadPool->perThreadDataDestructor) - threadPool->perThreadDataDestructor(perThreadData); - else if (threadPool->threadDataInterface) - threadPool->threadDataInterface->PerThreadDestructor(perThreadData, threadPool->tdiContext); - - - - - return 0; - -} -template -ThreadPool::ThreadPool() -{ - runThreads=false; - numThreadsRunning=0; - threadDataInterface=0; - tdiContext=0; - numThreadsWorking=0; - -} -template -ThreadPool::~ThreadPool() -{ - StopThreads(); - Clear(); -} -template -bool ThreadPool::StartThreads(int numThreads, int stackSize, void* (*_perThreadDataFactory)(), void (*_perThreadDataDestructor)(void *)) -{ - (void) stackSize; - -// #if defined(SN_TARGET_PSP2) -// runtime = RakNet::RakThread::AllocRuntime(numThreads); -// #endif - - runThreadsMutex.Lock(); - if (runThreads==true) - { - // Already running - runThreadsMutex.Unlock(); - return false; - } - runThreadsMutex.Unlock(); - - quitAndIncomingDataEvents.InitEvent(); - - perThreadDataFactory=_perThreadDataFactory; - perThreadDataDestructor=_perThreadDataDestructor; - - runThreadsMutex.Lock(); - runThreads=true; - runThreadsMutex.Unlock(); - - numThreadsWorking=0; - unsigned threadId = 0; - (void) threadId; - int i; - for (i=0; i < numThreads; i++) - { - int errorCode; - - - - - errorCode = RakNet::RakThread::Create(WorkerThread, this); - - if (errorCode!=0) - { - StopThreads(); - return false; - } - } - // Wait for number of threads running to increase to numThreads - bool done=false; - while (done==false) - { - RakSleep(50); - numThreadsRunningMutex.Lock(); - if (numThreadsRunning==numThreads) - done=true; - numThreadsRunningMutex.Unlock(); - } - - return true; -} -template -void ThreadPool::SetThreadDataInterface(ThreadDataInterface *tdi, void *context) -{ - threadDataInterface=tdi; - tdiContext=context; -} -template -void ThreadPool::StopThreads(void) -{ - runThreadsMutex.Lock(); - if (runThreads==false) - { - runThreadsMutex.Unlock(); - return; - } - - runThreads=false; - runThreadsMutex.Unlock(); - - // Wait for number of threads running to decrease to 0 - bool done=false; - while (done==false) - { - quitAndIncomingDataEvents.SetEvent(); - - RakSleep(50); - numThreadsRunningMutex.Lock(); - if (numThreadsRunning==0) - done=true; - numThreadsRunningMutex.Unlock(); - } - - quitAndIncomingDataEvents.CloseEvent(); - -// #if defined(SN_TARGET_PSP2) -// RakNet::RakThread::DeallocRuntime(runtime); -// runtime=0; -// #endif - -} -template -void ThreadPool::AddInput(OutputType (*workerThreadCallback)(InputType, bool *returnOutput, void* perThreadData), InputType inputData) -{ - inputQueueMutex.Lock(); - inputQueue.Push(inputData, _FILE_AND_LINE_ ); - inputFunctionQueue.Push(workerThreadCallback, _FILE_AND_LINE_ ); - inputQueueMutex.Unlock(); - - quitAndIncomingDataEvents.SetEvent(); -} -template -void ThreadPool::AddOutput(OutputType outputData) -{ - outputQueueMutex.Lock(); - outputQueue.Push(outputData, _FILE_AND_LINE_ ); - outputQueueMutex.Unlock(); -} -template -bool ThreadPool::HasOutputFast(void) -{ - return outputQueue.IsEmpty()==false; -} -template -bool ThreadPool::HasOutput(void) -{ - bool res; - outputQueueMutex.Lock(); - res=outputQueue.IsEmpty()==false; - outputQueueMutex.Unlock(); - return res; -} -template -bool ThreadPool::HasInputFast(void) -{ - return inputQueue.IsEmpty()==false; -} -template -bool ThreadPool::HasInput(void) -{ - bool res; - inputQueueMutex.Lock(); - res=inputQueue.IsEmpty()==false; - inputQueueMutex.Unlock(); - return res; -} -template -OutputType ThreadPool::GetOutput(void) -{ - // Real output check - OutputType output; - outputQueueMutex.Lock(); - output=outputQueue.Pop(); - outputQueueMutex.Unlock(); - return output; -} -template -void ThreadPool::Clear(void) -{ - runThreadsMutex.Lock(); - if (runThreads) - { - runThreadsMutex.Unlock(); - inputQueueMutex.Lock(); - inputFunctionQueue.Clear(_FILE_AND_LINE_); - inputQueue.Clear(_FILE_AND_LINE_); - inputQueueMutex.Unlock(); - - outputQueueMutex.Lock(); - outputQueue.Clear(_FILE_AND_LINE_); - outputQueueMutex.Unlock(); - } - else - { - inputFunctionQueue.Clear(_FILE_AND_LINE_); - inputQueue.Clear(_FILE_AND_LINE_); - outputQueue.Clear(_FILE_AND_LINE_); - } -} -template -void ThreadPool::LockInput(void) -{ - inputQueueMutex.Lock(); -} -template -void ThreadPool::UnlockInput(void) -{ - inputQueueMutex.Unlock(); -} -template -unsigned ThreadPool::InputSize(void) -{ - return inputQueue.Size(); -} -template -InputType ThreadPool::GetInputAtIndex(unsigned index) -{ - return inputQueue[index]; -} -template -void ThreadPool::RemoveInputAtIndex(unsigned index) -{ - inputQueue.RemoveAtIndex(index); - inputFunctionQueue.RemoveAtIndex(index); -} -template -void ThreadPool::LockOutput(void) -{ - outputQueueMutex.Lock(); -} -template -void ThreadPool::UnlockOutput(void) -{ - outputQueueMutex.Unlock(); -} -template -unsigned ThreadPool::OutputSize(void) -{ - return outputQueue.Size(); -} -template -OutputType ThreadPool::GetOutputAtIndex(unsigned index) -{ - return outputQueue[index]; -} -template -void ThreadPool::RemoveOutputAtIndex(unsigned index) -{ - outputQueue.RemoveAtIndex(index); -} -template -void ThreadPool::ClearInput(void) -{ - inputQueue.Clear(_FILE_AND_LINE_); - inputFunctionQueue.Clear(_FILE_AND_LINE_); -} - -template -void ThreadPool::ClearOutput(void) -{ - outputQueue.Clear(_FILE_AND_LINE_); -} -template -bool ThreadPool::IsWorking(void) -{ - bool isWorking; -// workingThreadCountMutex.Lock(); -// isWorking=numThreadsWorking!=0; -// workingThreadCountMutex.Unlock(); - -// if (isWorking) -// return true; - - // Bug fix: Originally the order of these two was reversed. - // It's possible with the thread timing that working could have been false, then it picks up the data in the other thread, then it checks - // here and sees there is no data. So it thinks the thread is not working when it was. - if (HasOutputFast() && HasOutput()) - return true; - - if (HasInputFast() && HasInput()) - return true; - - // Need to check is working again, in case the thread was between the first and second checks - workingThreadCountMutex.Lock(); - isWorking=numThreadsWorking!=0; - workingThreadCountMutex.Unlock(); - - return isWorking; -} - -template -int ThreadPool::NumThreadsWorking(void) -{ - return numThreadsWorking; -} - -template -bool ThreadPool::WasStarted(void) -{ - bool b; - runThreadsMutex.Lock(); - b = runThreads; - runThreadsMutex.Unlock(); - return b; -} -template -bool ThreadPool::Pause(void) -{ - if (WasStarted()==false) - return false; - - workingThreadCountMutex.Lock(); - while (numThreadsWorking>0) - { - RakSleep(30); - } - return true; -} -template -void ThreadPool::Resume(void) -{ - workingThreadCountMutex.Unlock(); -} - -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -#endif - +#pragma once + +#include "RakMemoryOverride.h" +#include "DS_Queue.h" +#include "SimpleMutex.h" +#include "Export.h" +#include "RakThread.h" +#include "SignaledEvent.h" + +#ifdef _MSC_VER +#pragma warning( push ) +#endif + +class ThreadDataInterface +{ +public: + ThreadDataInterface() {} + virtual ~ThreadDataInterface() {} + + virtual void* PerThreadFactory(void *context)=0; + virtual void PerThreadDestructor(void* factoryResult, void *context)=0; +}; +/// A simple class to create worker threads that processes a queue of functions with data. +/// This class does not allocate or deallocate memory. It is up to the user to handle memory management. +/// InputType and OutputType are stored directly in a queue. For large structures, if you plan to delete from the middle of the queue, +/// you might wish to store pointers rather than the structures themselves so the array can shift efficiently. +template +struct RAK_DLL_EXPORT ThreadPool +{ + ThreadPool(); + ~ThreadPool(); + + /// Start the specified number of threads. + /// \param[in] numThreads The number of threads to start + /// \param[in] stackSize 0 for default (except on consoles). + /// \param[in] _perThreadInit User callback to return data stored per thread. Pass 0 if not needed. + /// \param[in] _perThreadDeinit User callback to destroy data stored per thread, created by _perThreadInit. Pass 0 if not needed. + /// \return True on success, false on failure. + bool StartThreads(int numThreads, int stackSize, void* (*_perThreadInit)()=0, void (*_perThreadDeinit)(void*)=0); + + // Alternate form of _perThreadDataFactory, _perThreadDataDestructor + void SetThreadDataInterface(ThreadDataInterface *tdi, void *context); + + /// Stops all threads + void StopThreads(void); + + /// Adds a function to a queue with data to pass to that function. This function will be called from the thread + /// Memory management is your responsibility! This class does not allocate or deallocate memory. + /// The best way to deallocate \a inputData is in userCallback. If you call EndThreads such that callbacks were not called, you + /// can iterate through the inputQueue and deallocate all pending input data there + /// The best way to deallocate output is as it is returned to you from GetOutput. Similarly, if you end the threads such that + /// not all output was returned, you can iterate through outputQueue and deallocate it there. + /// \param[in] workerThreadCallback The function to call from the thread + /// \param[in] inputData The parameter to pass to \a userCallback + void AddInput(OutputType (*workerThreadCallback)(InputType, bool *returnOutput, void* perThreadData), InputType inputData); + + /// Adds to the output queue + /// Use it if you want to inject output into the same queue that the system uses. Normally you would not use this. Consider it a convenience function. + /// \param[in] outputData The output to inject + void AddOutput(OutputType outputData); + + /// Returns true if output from GetOutput is waiting. + /// \return true if output is waiting, false otherwise + bool HasOutput(void); + + /// Inaccurate but fast version of HasOutput. If this returns true, you should still check HasOutput for the real value. + /// \return true if output is probably waiting, false otherwise + bool HasOutputFast(void); + + /// Returns true if input from GetInput is waiting. + /// \return true if input is waiting, false otherwise + bool HasInput(void); + + /// Inaccurate but fast version of HasInput. If this returns true, you should still check HasInput for the real value. + /// \return true if input is probably waiting, false otherwise + bool HasInputFast(void); + + /// Gets the output of a call to \a userCallback + /// HasOutput must return true before you call this function. Otherwise it will assert. + /// \return The output of \a userCallback. If you have different output signatures, it is up to you to encode the data to indicate this + OutputType GetOutput(void); + + /// Clears internal buffers + void Clear(void); + + /// Lock the input buffer before calling the functions InputSize, InputAtIndex, and RemoveInputAtIndex + /// It is only necessary to lock the input or output while the threads are running + void LockInput(void); + + /// Unlock the input buffer after you are done with the functions InputSize, GetInputAtIndex, and RemoveInputAtIndex + void UnlockInput(void); + + /// Length of the input queue + unsigned InputSize(void); + + /// Get the input at a specified index + InputType GetInputAtIndex(unsigned index); + + /// Remove input from a specific index. This does NOT do memory deallocation - it only removes the item from the queue + void RemoveInputAtIndex(unsigned index); + + /// Lock the output buffer before calling the functions OutputSize, OutputAtIndex, and RemoveOutputAtIndex + /// It is only necessary to lock the input or output while the threads are running + void LockOutput(void); + + /// Unlock the output buffer after you are done with the functions OutputSize, GetOutputAtIndex, and RemoveOutputAtIndex + void UnlockOutput(void); + + /// Length of the output queue + unsigned OutputSize(void); + + /// Get the output at a specified index + OutputType GetOutputAtIndex(unsigned index); + + /// Remove output from a specific index. This does NOT do memory deallocation - it only removes the item from the queue + void RemoveOutputAtIndex(unsigned index); + + /// Removes all items from the input queue + void ClearInput(void); + + /// Removes all items from the output queue + void ClearOutput(void); + + /// Are any of the threads working, or is input or output available? + bool IsWorking(void); + + /// The number of currently active threads. + int NumThreadsWorking(void); + + /// Did we call Start? + bool WasStarted(void); + + // Block until all threads are stopped. + bool Pause(void); + + // Continue running + void Resume(void); + +protected: + // It is valid to cancel input before it is processed. To do so, lock the inputQueue with inputQueueMutex, + // Scan the list, and remove the item you don't want. + RakNet::SimpleMutex inputQueueMutex, outputQueueMutex, workingThreadCountMutex, runThreadsMutex; + + void* (*perThreadDataFactory)(); + void (*perThreadDataDestructor)(void*); + + // inputFunctionQueue & inputQueue are paired arrays so if you delete from one at a particular index you must delete from the other + // at the same index + DataStructures::Queue inputFunctionQueue; + DataStructures::Queue inputQueue; + DataStructures::Queue outputQueue; + + ThreadDataInterface *threadDataInterface; + void *tdiContext; + + + template + friend RAK_THREAD_DECLARATION(WorkerThread); + + /* +#ifdef _WIN32 + friend unsigned __stdcall WorkerThread( LPVOID arguments ); +#else + friend void* WorkerThread( void* arguments ); +#endif + */ + + /// \internal + bool runThreads; + /// \internal + int numThreadsRunning; + /// \internal + int numThreadsWorking; + /// \internal + RakNet::SimpleMutex numThreadsRunningMutex; + + RakNet::SignaledEvent quitAndIncomingDataEvents; + +// #if defined(SN_TARGET_PSP2) +// RakNet::RakThread::UltUlThreadRuntime *runtime; +// #endif +}; + +#include "ThreadPool.h" +#include "RakSleep.h" +#ifdef _WIN32 + +#else +#include +#endif + +#ifdef _MSC_VER +#pragma warning(disable:4127) +#pragma warning( disable : 4701 ) // potentially uninitialized local variable 'inputData' used +#endif + +template +RAK_THREAD_DECLARATION(WorkerThread) +/* +#ifdef _WIN32 +unsigned __stdcall WorkerThread( LPVOID arguments ) +#else +void* WorkerThread( void* arguments ) +#endif +*/ +{ + + + + ThreadPool *threadPool = (ThreadPool*) arguments; + + + bool returnOutput; + ThreadOutputType (*userCallback)(ThreadInputType, bool *, void*); + ThreadInputType inputData; + ThreadOutputType callbackOutput; + + userCallback=0; + + void *perThreadData; + if (threadPool->perThreadDataFactory) + perThreadData=threadPool->perThreadDataFactory(); + else if (threadPool->threadDataInterface) + perThreadData=threadPool->threadDataInterface->PerThreadFactory(threadPool->tdiContext); + else + perThreadData=0; + + // Increase numThreadsRunning + threadPool->numThreadsRunningMutex.Lock(); + ++threadPool->numThreadsRunning; + threadPool->numThreadsRunningMutex.Unlock(); + + while (1) + { +#ifdef _WIN32 + if (userCallback==0) + { + threadPool->quitAndIncomingDataEvents.WaitOnEvent(INFINITE); + } +#endif + + threadPool->runThreadsMutex.Lock(); + if (threadPool->runThreads==false) + { + threadPool->runThreadsMutex.Unlock(); + break; + } + threadPool->runThreadsMutex.Unlock(); + + threadPool->workingThreadCountMutex.Lock(); + ++threadPool->numThreadsWorking; + threadPool->workingThreadCountMutex.Unlock(); + + // Read input data + userCallback=0; + threadPool->inputQueueMutex.Lock(); + if (threadPool->inputFunctionQueue.Size()) + { + userCallback=threadPool->inputFunctionQueue.Pop(); + inputData=threadPool->inputQueue.Pop(); + } + threadPool->inputQueueMutex.Unlock(); + + if (userCallback) + { + callbackOutput=userCallback(inputData, &returnOutput,perThreadData); + if (returnOutput) + { + threadPool->outputQueueMutex.Lock(); + threadPool->outputQueue.Push(callbackOutput, _FILE_AND_LINE_ ); + threadPool->outputQueueMutex.Unlock(); + } + } + + threadPool->workingThreadCountMutex.Lock(); + --threadPool->numThreadsWorking; + threadPool->workingThreadCountMutex.Unlock(); + } + + // Decrease numThreadsRunning + threadPool->numThreadsRunningMutex.Lock(); + --threadPool->numThreadsRunning; + threadPool->numThreadsRunningMutex.Unlock(); + + if (threadPool->perThreadDataDestructor) + threadPool->perThreadDataDestructor(perThreadData); + else if (threadPool->threadDataInterface) + threadPool->threadDataInterface->PerThreadDestructor(perThreadData, threadPool->tdiContext); + + + + + return 0; + +} +template +ThreadPool::ThreadPool() +{ + runThreads=false; + numThreadsRunning=0; + threadDataInterface=0; + tdiContext=0; + numThreadsWorking=0; + +} +template +ThreadPool::~ThreadPool() +{ + StopThreads(); + Clear(); +} +template +bool ThreadPool::StartThreads(int numThreads, int stackSize, void* (*_perThreadDataFactory)(), void (*_perThreadDataDestructor)(void *)) +{ + (void) stackSize; + +// #if defined(SN_TARGET_PSP2) +// runtime = RakNet::RakThread::AllocRuntime(numThreads); +// #endif + + runThreadsMutex.Lock(); + if (runThreads==true) + { + // Already running + runThreadsMutex.Unlock(); + return false; + } + runThreadsMutex.Unlock(); + + quitAndIncomingDataEvents.InitEvent(); + + perThreadDataFactory=_perThreadDataFactory; + perThreadDataDestructor=_perThreadDataDestructor; + + runThreadsMutex.Lock(); + runThreads=true; + runThreadsMutex.Unlock(); + + numThreadsWorking=0; + unsigned threadId = 0; + (void) threadId; + int i; + for (i=0; i < numThreads; i++) + { + int errorCode; + + + + + errorCode = RakNet::RakThread::Create(WorkerThread, this); + + if (errorCode!=0) + { + StopThreads(); + return false; + } + } + // Wait for number of threads running to increase to numThreads + bool done=false; + while (done==false) + { + RakSleep(50); + numThreadsRunningMutex.Lock(); + if (numThreadsRunning==numThreads) + done=true; + numThreadsRunningMutex.Unlock(); + } + + return true; +} +template +void ThreadPool::SetThreadDataInterface(ThreadDataInterface *tdi, void *context) +{ + threadDataInterface=tdi; + tdiContext=context; +} +template +void ThreadPool::StopThreads(void) +{ + runThreadsMutex.Lock(); + if (runThreads==false) + { + runThreadsMutex.Unlock(); + return; + } + + runThreads=false; + runThreadsMutex.Unlock(); + + // Wait for number of threads running to decrease to 0 + bool done=false; + while (done==false) + { + quitAndIncomingDataEvents.SetEvent(); + + RakSleep(50); + numThreadsRunningMutex.Lock(); + if (numThreadsRunning==0) + done=true; + numThreadsRunningMutex.Unlock(); + } + + quitAndIncomingDataEvents.CloseEvent(); + +// #if defined(SN_TARGET_PSP2) +// RakNet::RakThread::DeallocRuntime(runtime); +// runtime=0; +// #endif + +} +template +void ThreadPool::AddInput(OutputType (*workerThreadCallback)(InputType, bool *returnOutput, void* perThreadData), InputType inputData) +{ + inputQueueMutex.Lock(); + inputQueue.Push(inputData, _FILE_AND_LINE_ ); + inputFunctionQueue.Push(workerThreadCallback, _FILE_AND_LINE_ ); + inputQueueMutex.Unlock(); + + quitAndIncomingDataEvents.SetEvent(); +} +template +void ThreadPool::AddOutput(OutputType outputData) +{ + outputQueueMutex.Lock(); + outputQueue.Push(outputData, _FILE_AND_LINE_ ); + outputQueueMutex.Unlock(); +} +template +bool ThreadPool::HasOutputFast(void) +{ + return outputQueue.IsEmpty()==false; +} +template +bool ThreadPool::HasOutput(void) +{ + bool res; + outputQueueMutex.Lock(); + res=outputQueue.IsEmpty()==false; + outputQueueMutex.Unlock(); + return res; +} +template +bool ThreadPool::HasInputFast(void) +{ + return inputQueue.IsEmpty()==false; +} +template +bool ThreadPool::HasInput(void) +{ + bool res; + inputQueueMutex.Lock(); + res=inputQueue.IsEmpty()==false; + inputQueueMutex.Unlock(); + return res; +} +template +OutputType ThreadPool::GetOutput(void) +{ + // Real output check + OutputType output; + outputQueueMutex.Lock(); + output=outputQueue.Pop(); + outputQueueMutex.Unlock(); + return output; +} +template +void ThreadPool::Clear(void) +{ + runThreadsMutex.Lock(); + if (runThreads) + { + runThreadsMutex.Unlock(); + inputQueueMutex.Lock(); + inputFunctionQueue.Clear(_FILE_AND_LINE_); + inputQueue.Clear(_FILE_AND_LINE_); + inputQueueMutex.Unlock(); + + outputQueueMutex.Lock(); + outputQueue.Clear(_FILE_AND_LINE_); + outputQueueMutex.Unlock(); + } + else + { + inputFunctionQueue.Clear(_FILE_AND_LINE_); + inputQueue.Clear(_FILE_AND_LINE_); + outputQueue.Clear(_FILE_AND_LINE_); + } +} +template +void ThreadPool::LockInput(void) +{ + inputQueueMutex.Lock(); +} +template +void ThreadPool::UnlockInput(void) +{ + inputQueueMutex.Unlock(); +} +template +unsigned ThreadPool::InputSize(void) +{ + return inputQueue.Size(); +} +template +InputType ThreadPool::GetInputAtIndex(unsigned index) +{ + return inputQueue[index]; +} +template +void ThreadPool::RemoveInputAtIndex(unsigned index) +{ + inputQueue.RemoveAtIndex(index); + inputFunctionQueue.RemoveAtIndex(index); +} +template +void ThreadPool::LockOutput(void) +{ + outputQueueMutex.Lock(); +} +template +void ThreadPool::UnlockOutput(void) +{ + outputQueueMutex.Unlock(); +} +template +unsigned ThreadPool::OutputSize(void) +{ + return outputQueue.Size(); +} +template +OutputType ThreadPool::GetOutputAtIndex(unsigned index) +{ + return outputQueue[index]; +} +template +void ThreadPool::RemoveOutputAtIndex(unsigned index) +{ + outputQueue.RemoveAtIndex(index); +} +template +void ThreadPool::ClearInput(void) +{ + inputQueue.Clear(_FILE_AND_LINE_); + inputFunctionQueue.Clear(_FILE_AND_LINE_); +} + +template +void ThreadPool::ClearOutput(void) +{ + outputQueue.Clear(_FILE_AND_LINE_); +} +template +bool ThreadPool::IsWorking(void) +{ + bool isWorking; +// workingThreadCountMutex.Lock(); +// isWorking=numThreadsWorking!=0; +// workingThreadCountMutex.Unlock(); + +// if (isWorking) +// return true; + + // Bug fix: Originally the order of these two was reversed. + // It's possible with the thread timing that working could have been false, then it picks up the data in the other thread, then it checks + // here and sees there is no data. So it thinks the thread is not working when it was. + if (HasOutputFast() && HasOutput()) + return true; + + if (HasInputFast() && HasInput()) + return true; + + // Need to check is working again, in case the thread was between the first and second checks + workingThreadCountMutex.Lock(); + isWorking=numThreadsWorking!=0; + workingThreadCountMutex.Unlock(); + + return isWorking; +} + +template +int ThreadPool::NumThreadsWorking(void) +{ + return numThreadsWorking; +} + +template +bool ThreadPool::WasStarted(void) +{ + bool b; + runThreadsMutex.Lock(); + b = runThreads; + runThreadsMutex.Unlock(); + return b; +} +template +bool ThreadPool::Pause(void) +{ + if (WasStarted()==false) + return false; + + workingThreadCountMutex.Lock(); + while (numThreadsWorking>0) + { + RakSleep(30); + } + return true; +} +template +void ThreadPool::Resume(void) +{ + workingThreadCountMutex.Unlock(); +} + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#endif + diff --git a/src/raknet/UDPProxyCommon.h b/src/raknet/UDPProxyCommon.h index 29699f3..1f8f182 100755 --- a/src/raknet/UDPProxyCommon.h +++ b/src/raknet/UDPProxyCommon.h @@ -1,57 +1,55 @@ -#ifndef __UDP_PROXY_COMMON_H -#define __UDP_PROXY_COMMON_H - -// System flow: -/* -UDPProxyClient: End user -UDPProxyServer: open server, to route messages from end users that can't connect to each other using UDPForwarder class. -UDPProxyCoordinator: Server somewhere, connected to by RakNet, to maintain a list of UDPProxyServer - -UDPProxyServer - On startup, log into UDPProxyCoordinator and register self - -UDPProxyClient - Wish to open route to X - Send message to UDPProxyCoordinator containing X, desired timeout - Wait for success or failure - -UDPProxyCoordinator: -* Get openRouteRequest - If no servers registered, return failure - Add entry to memory - chooseBestUDPProxyServer() (overridable, chooses at random by default) - Query this server to StartForwarding(). Return success or failure - If failure, choose another server from the remaining list. If none remaining, return failure. Else return success. -* Disconnect: - If disconnected system is pending client on openRouteRequest, delete that request - If disconnected system is UDPProxyServer, remove from list. For each pending client for this server, choose from remaining servers. -* Login: - Add to UDPProxyServer list, validating password if set -*/ - -// Stored in the second byte after ID_UDP_PROXY_GENERAL -// Otherwise MessageIdentifiers.h is too cluttered and will hit the limit on enumerations in a single byte -enum UDPProxyMessages -{ - ID_UDP_PROXY_FORWARDING_SUCCEEDED, - ID_UDP_PROXY_FORWARDING_NOTIFICATION, - ID_UDP_PROXY_NO_SERVERS_ONLINE, - ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR, - ID_UDP_PROXY_ALL_SERVERS_BUSY, - ID_UDP_PROXY_IN_PROGRESS, - ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR, - ID_UDP_PROXY_PING_SERVERS_FROM_COORDINATOR_TO_CLIENT, - ID_UDP_PROXY_PING_SERVERS_REPLY_FROM_CLIENT_TO_COORDINATOR, - ID_UDP_PROXY_FORWARDING_REQUEST_FROM_COORDINATOR_TO_SERVER, - ID_UDP_PROXY_FORWARDING_REPLY_FROM_SERVER_TO_COORDINATOR, - ID_UDP_PROXY_LOGIN_REQUEST_FROM_SERVER_TO_COORDINATOR, - ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER, - ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER, - ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER, - ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER -}; - - -#define UDP_FORWARDER_MAXIMUM_TIMEOUT (60000 * 10) - -#endif +#pragma once + +// System flow: +/* +UDPProxyClient: End user +UDPProxyServer: open server, to route messages from end users that can't connect to each other using UDPForwarder class. +UDPProxyCoordinator: Server somewhere, connected to by RakNet, to maintain a list of UDPProxyServer + +UDPProxyServer + On startup, log into UDPProxyCoordinator and register self + +UDPProxyClient + Wish to open route to X + Send message to UDPProxyCoordinator containing X, desired timeout + Wait for success or failure + +UDPProxyCoordinator: +* Get openRouteRequest + If no servers registered, return failure + Add entry to memory + chooseBestUDPProxyServer() (overridable, chooses at random by default) + Query this server to StartForwarding(). Return success or failure + If failure, choose another server from the remaining list. If none remaining, return failure. Else return success. +* Disconnect: + If disconnected system is pending client on openRouteRequest, delete that request + If disconnected system is UDPProxyServer, remove from list. For each pending client for this server, choose from remaining servers. +* Login: + Add to UDPProxyServer list, validating password if set +*/ + +// Stored in the second byte after ID_UDP_PROXY_GENERAL +// Otherwise MessageIdentifiers.h is too cluttered and will hit the limit on enumerations in a single byte +enum UDPProxyMessages +{ + ID_UDP_PROXY_FORWARDING_SUCCEEDED, + ID_UDP_PROXY_FORWARDING_NOTIFICATION, + ID_UDP_PROXY_NO_SERVERS_ONLINE, + ID_UDP_PROXY_RECIPIENT_GUID_NOT_CONNECTED_TO_COORDINATOR, + ID_UDP_PROXY_ALL_SERVERS_BUSY, + ID_UDP_PROXY_IN_PROGRESS, + ID_UDP_PROXY_FORWARDING_REQUEST_FROM_CLIENT_TO_COORDINATOR, + ID_UDP_PROXY_PING_SERVERS_FROM_COORDINATOR_TO_CLIENT, + ID_UDP_PROXY_PING_SERVERS_REPLY_FROM_CLIENT_TO_COORDINATOR, + ID_UDP_PROXY_FORWARDING_REQUEST_FROM_COORDINATOR_TO_SERVER, + ID_UDP_PROXY_FORWARDING_REPLY_FROM_SERVER_TO_COORDINATOR, + ID_UDP_PROXY_LOGIN_REQUEST_FROM_SERVER_TO_COORDINATOR, + ID_UDP_PROXY_LOGIN_SUCCESS_FROM_COORDINATOR_TO_SERVER, + ID_UDP_PROXY_ALREADY_LOGGED_IN_FROM_COORDINATOR_TO_SERVER, + ID_UDP_PROXY_NO_PASSWORD_SET_FROM_COORDINATOR_TO_SERVER, + ID_UDP_PROXY_WRONG_PASSWORD_FROM_COORDINATOR_TO_SERVER +}; + + +#define UDP_FORWARDER_MAXIMUM_TIMEOUT (60000 * 10) + diff --git a/src/raknet/VariableDeltaSerializer.h b/src/raknet/VariableDeltaSerializer.h index 257426d..2e3c2a7 100755 --- a/src/raknet/VariableDeltaSerializer.h +++ b/src/raknet/VariableDeltaSerializer.h @@ -1,257 +1,255 @@ -#ifndef __VARIABLE_DELTA_SERIALIZER_H -#define __VARIABLE_DELTA_SERIALIZER_H - -#include "VariableListDeltaTracker.h" -#include "DS_MemoryPool.h" -#include "NativeTypes.h" -#include "BitStream.h" -#include "PacketPriority.h" -#include "DS_OrderedList.h" - -namespace RakNet -{ - -/// \brief Class to compare memory values of variables in a current state to a prior state -/// Results of the comparisons will be written to a bitStream, such that only changed variables get written
-/// Can be used with ReplicaManager3 to Serialize a Replica3 per-variable, rather than comparing the entire object against itself
-/// Usage:
-///
-/// 1. Call BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize(). In the case of Replica3, this would be in the Serialize() call
-/// 2. For each variable of the type in step 1, call Serialize(). The same variables must be serialized every tick()
-/// 3. Call EndSerialize()
-/// 4. Repeat step 1 for each of the other categories of how to send varaibles -/// -/// On the receiver: -/// -/// 1. Call BeginDeserialize(). In the case of Replica3, this would be in the Deserialize() call -/// 2. Call DeserializeVariable() for each variable, in the same order as was Serialized() -/// 3. Call EndSerialize() -/// \sa The ReplicaManager3 sample -class VariableDeltaSerializer -{ -protected: - struct RemoteSystemVariableHistory; - struct ChangedVariablesList; - -public: - VariableDeltaSerializer(); - ~VariableDeltaSerializer(); - - struct SerializationContext - { - SerializationContext(); - ~SerializationContext(); - - RakNetGUID guid; - BitStream *bitStream; - uint32_t rakPeerSendReceipt; - RemoteSystemVariableHistory *variableHistory; - RemoteSystemVariableHistory *variableHistoryIdentical; - RemoteSystemVariableHistory *variableHistoryUnique; - ChangedVariablesList *changedVariables; - uint32_t sendReceipt; - PacketReliability serializationMode; - bool anyVariablesWritten; - bool newSystemSend; // Force send all, do not record - }; - - struct DeserializationContext - { - BitStream *bitStream; - }; - - /// \brief Call before doing one or more SerializeVariable calls when the data will be sent UNRELIABLE_WITH_ACK_RECEIPT - /// The last value of each variable will be saved per remote system. Additionally, a history of \a _sendReceipts is stored to determine what to resend on packetloss. - /// When variables are lost, they will be flagged dirty and always resent to the system that lost it - /// Disadvantages: Every variable for every remote system is copied internally, in addition to a history list of what variables changed for which \a _sendReceipt. Very memory and CPU intensive for multiple connections. - /// Advantages: When data needs to be resent by RakNet, RakNet can only resend the value it currently has. This allows the application to control the resend, sending the most recent value of the variable. The end result is that bandwidth is used more efficiently because old data is never sent. - /// \pre Upon getting ID_SND_RECEIPT_LOSS or ID_SND_RECEIPT_ACKED call OnMessageReceipt() - /// \pre AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() must be called for new and lost connections - /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. - /// \param[in] _guid Which system we are sending to - /// \param[in] _bitSteam Which bitStream to write to - /// \param[in] _sendReceipt Returned from RakPeer::IncrementNextSendReceipt() and passed to the Send() or SendLists() function. Identifies this update for ID_SND_RECEIPT_LOSS and ID_SND_RECEIPT_ACKED - void BeginUnreliableAckedSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream, uint32_t _sendReceipt); - - /// \brief Call before doing one or more SerializeVariable calls for data that may be sent differently to every remote system (such as an invisibility flag that only teammates can see) - /// The last value of each variable will be saved per remote system. - /// Unlike BeginUnreliableAckedSerialize(), send receipts are not necessary - /// Disadvantages: Every variable for every remote system is copied internally. Very memory and CPU intensive for multiple connections. - /// Advantages: When data is sent differently depending on the recipient, this system can make things easier to use and is as efficient as it can be. - /// \pre AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() must be called for new and lost connections - /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. - /// \param[in] _guid Which system we are sending to - /// \param[in] _bitSteam Which bitStream to write to - void BeginUniqueSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream); - - /// \brief Call before doing one or more SerializeVariable calls for data that is sent with the same value to every remote system (such as health, position, etc.) - /// This is the most common type of serialization, and also the most efficient - /// Disadvantages: A copy of every variable still needs to be held, although only once - /// Advantages: After the first serialization, the last serialized bitStream will be used for subsequent sends - /// \pre Call OnPreSerializeTick() before doing any calls to BeginIdenticalSerialize() for each of your objects, once per game tick - /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. - /// \param[in] _isFirstSerializeToThisSystem Pass true if this is the first time ever serializing to this system (the initial download). This way all variables will be written, rather than checking against prior sent values. - /// \param[in] _bitSteam Which bitStream to write to - void BeginIdenticalSerialize(SerializationContext *context, bool _isFirstSerializeToThisSystem, BitStream *_bitStream); - - /// \brief Call after BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize(), then after calling SerializeVariable() one or more times - /// \param[in] context Same context pointer passed to BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() - void EndSerialize(SerializationContext *context); - - /// \brief Call when you receive the BitStream written by SerializeVariable(), before calling DeserializeVariable() - /// \param[in] context Holds the context of this group of deserialize calls. This can be a stack object just passed to the function. - /// \param[in] _bitStream Pass the bitStream originally passed to and written to by serialize calls - void BeginDeserialize(DeserializationContext *context, BitStream *_bitStream); - - /// \param[in] context Same context pointer passed to BeginDeserialize() - void EndDeserialize(DeserializationContext *context); - - /// BeginUnreliableAckedSerialize() and BeginUniqueSerialize() require knowledge of when connections are added and dropped - /// Call AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() to notify the system of these events - /// \param[in] _guid Which system we are sending to - void AddRemoteSystemVariableHistory(RakNetGUID guid); - - /// BeginUnreliableAckedSerialize() and BeginUniqueSerialize() require knowledge of when connections are added and dropped - /// Call AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() to notify the system of these events - /// \param[in] _guid Which system we are sending to - void RemoveRemoteSystemVariableHistory(RakNetGUID guid); - - /// BeginIdenticalSerialize() requires knowledge of when serialization has started for an object across multiple systems - /// This way it can setup the flag to do new comparisons against the last sent values, rather than just resending the last sent bitStream - /// For Replica3, overload and call this from Replica3::OnUserReplicaPreSerializeTick() - void OnPreSerializeTick(void); - - /// Call when getting ID_SND_RECEIPT_LOSS or ID_SND_RECEIPT_ACKED for a particular system - /// Example: - /// - /// uint32_t msgNumber; - /// memcpy(&msgNumber, packet->data+1, 4); - /// DataStructures::List replicaListOut; - /// replicaManager.GetReplicasCreatedByMe(replicaListOut); - /// unsigned int idx; - /// for (idx=0; idx < replicaListOut.GetSize(); idx++) - /// { - /// ((SampleReplica*)replicaListOut[idx])->NotifyReplicaOfMessageDeliveryStatus(packet->guid,msgNumber, packet->data[0]==ID_SND_RECEIPT_ACKED); - /// } - /// - /// \param[in] guid Which system we are sending to - /// \param[in] receiptId Encoded in bytes 1-4 inclusive of ID_SND_RECEIPT_LOSS and ID_SND_RECEIPT_ACKED - /// \param[in] messageArrived True for ID_SND_RECEIPT_ACKED, false otherwise - void OnMessageReceipt(RakNetGUID guid, uint32_t receiptId, bool messageArrived); - - /// Call to Serialize a variable - /// Will write to the bitSteam passed to \a context true, variableValue if the variable has changed or has never been written. Otherwise will write false. - /// \pre You have called BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() - /// \pre Will also require calling OnPreSerializeTick() if using BeginIdenticalSerialize() - /// \note Be sure to call EndSerialize() after finishing all serializations - /// \param[in] context Same context pointer passed to BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() - /// \param[in] variable A variable to write to the bitStream passed to \a context - template - void SerializeVariable(SerializationContext *context, const VarType &variable) - { - if (context->newSystemSend) - { - if (context->variableHistory->variableListDeltaTracker.IsPastEndOfList()==false) - { - // previously sent data to another system - context->bitStream->Write(true); - context->bitStream->Write(variable); - context->anyVariablesWritten=true; - } - else - { - // never sent data to another system - context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); - context->anyVariablesWritten=true; - } - } - else if (context->serializationMode==UNRELIABLE_WITH_ACK_RECEIPT) - { - context->anyVariablesWritten|= - context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream, context->changedVariables->bitField, context->changedVariables->bitWriteIndex++); - } - else - { - if (context->variableHistoryIdentical) - { - // Identical serialization to a number of systems - if (didComparisonThisTick==false) - context->anyVariablesWritten|= - context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); - // Else bitstream is written to at the end - } - else - { - // Per-system serialization - context->anyVariablesWritten|= - context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); - } - } - } - - /// Call to deserialize into a variable - /// \pre You have called BeginDeserialize() - /// \note Be sure to call EndDeserialize() after finishing all deserializations - /// \param[in] context Same context pointer passed to BeginDeserialize() - /// \param[in] variable A variable to write to the bitStream passed to \a context - template - bool DeserializeVariable(DeserializationContext *context, VarType &variable) - { - return VariableListDeltaTracker::ReadVarFromBitstream(variable, context->bitStream); - } - - - -protected: - - // For a given send receipt from RakPeer::Send() track which variables we updated - // That way if that send does not arrive (ID_SND_RECEIPT_LOSS) we can mark those variables as dirty to resend them with current values - struct ChangedVariablesList - { - uint32_t sendReceipt; - unsigned short bitWriteIndex; - unsigned char bitField[56]; - }; - - // static int Replica2ObjectComp( const uint32_t &key, ChangedVariablesList* const &data ); - - static int UpdatedVariablesListPtrComp( const uint32_t &key, ChangedVariablesList* const &data ); - - // For each remote system, track the last values of variables we sent to them, and the history of what values changed per call to Send() - // Every serialize if a variable changes from its last value, send it out again - // Also if a send does not arrive (ID_SND_RECEIPT_LOSS) we use updatedVariablesHistory to mark those variables as dirty, to resend them unreliably with the current values - struct RemoteSystemVariableHistory - { - RakNetGUID guid; - VariableListDeltaTracker variableListDeltaTracker; - DataStructures::OrderedList updatedVariablesHistory; - }; - /// A list of RemoteSystemVariableHistory indexed by guid, one per connection that we serialize to - /// List is added to when SerializeConstruction is called, and removed from when SerializeDestruction is called, or when a given connection is dropped - DataStructures::List remoteSystemVariableHistoryList; - - // Because the ChangedVariablesList is created every serialize and destroyed every receipt I use a pool to avoid fragmentation - DataStructures::MemoryPool updatedVariablesMemoryPool; - - bool didComparisonThisTick; - RakNet::BitStream identicalSerializationBs; - - void FreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId); - void DirtyAndFreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId); - unsigned int GetVarsWrittenPerRemoteSystemListIndex(RakNetGUID guid); - void RemoveRemoteSystemVariableHistory(void); - - RemoteSystemVariableHistory* GetRemoteSystemVariableHistory(RakNetGUID guid); - - ChangedVariablesList *AllocChangedVariablesList(void); - void FreeChangedVariablesList(ChangedVariablesList *changedVariables); - void StoreChangedVariablesList(RemoteSystemVariableHistory *variableHistory, ChangedVariablesList *changedVariables, uint32_t sendReceipt); - - RemoteSystemVariableHistory *StartVariableHistoryWrite(RakNetGUID guid); - unsigned int GetRemoteSystemHistoryListIndex(RakNetGUID guid); - -}; - -} - -#endif +#pragma once + +#include "VariableListDeltaTracker.h" +#include "DS_MemoryPool.h" +#include "NativeTypes.h" +#include "BitStream.h" +#include "PacketPriority.h" +#include "DS_OrderedList.h" + +namespace RakNet +{ + +/// \brief Class to compare memory values of variables in a current state to a prior state +/// Results of the comparisons will be written to a bitStream, such that only changed variables get written
+/// Can be used with ReplicaManager3 to Serialize a Replica3 per-variable, rather than comparing the entire object against itself
+/// Usage:
+///
+/// 1. Call BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize(). In the case of Replica3, this would be in the Serialize() call
+/// 2. For each variable of the type in step 1, call Serialize(). The same variables must be serialized every tick()
+/// 3. Call EndSerialize()
+/// 4. Repeat step 1 for each of the other categories of how to send varaibles +/// +/// On the receiver: +/// +/// 1. Call BeginDeserialize(). In the case of Replica3, this would be in the Deserialize() call +/// 2. Call DeserializeVariable() for each variable, in the same order as was Serialized() +/// 3. Call EndSerialize() +/// \sa The ReplicaManager3 sample +class VariableDeltaSerializer +{ +protected: + struct RemoteSystemVariableHistory; + struct ChangedVariablesList; + +public: + VariableDeltaSerializer(); + ~VariableDeltaSerializer(); + + struct SerializationContext + { + SerializationContext(); + ~SerializationContext(); + + RakNetGUID guid; + BitStream *bitStream; + uint32_t rakPeerSendReceipt; + RemoteSystemVariableHistory *variableHistory; + RemoteSystemVariableHistory *variableHistoryIdentical; + RemoteSystemVariableHistory *variableHistoryUnique; + ChangedVariablesList *changedVariables; + uint32_t sendReceipt; + PacketReliability serializationMode; + bool anyVariablesWritten; + bool newSystemSend; // Force send all, do not record + }; + + struct DeserializationContext + { + BitStream *bitStream; + }; + + /// \brief Call before doing one or more SerializeVariable calls when the data will be sent UNRELIABLE_WITH_ACK_RECEIPT + /// The last value of each variable will be saved per remote system. Additionally, a history of \a _sendReceipts is stored to determine what to resend on packetloss. + /// When variables are lost, they will be flagged dirty and always resent to the system that lost it + /// Disadvantages: Every variable for every remote system is copied internally, in addition to a history list of what variables changed for which \a _sendReceipt. Very memory and CPU intensive for multiple connections. + /// Advantages: When data needs to be resent by RakNet, RakNet can only resend the value it currently has. This allows the application to control the resend, sending the most recent value of the variable. The end result is that bandwidth is used more efficiently because old data is never sent. + /// \pre Upon getting ID_SND_RECEIPT_LOSS or ID_SND_RECEIPT_ACKED call OnMessageReceipt() + /// \pre AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() must be called for new and lost connections + /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. + /// \param[in] _guid Which system we are sending to + /// \param[in] _bitSteam Which bitStream to write to + /// \param[in] _sendReceipt Returned from RakPeer::IncrementNextSendReceipt() and passed to the Send() or SendLists() function. Identifies this update for ID_SND_RECEIPT_LOSS and ID_SND_RECEIPT_ACKED + void BeginUnreliableAckedSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream, uint32_t _sendReceipt); + + /// \brief Call before doing one or more SerializeVariable calls for data that may be sent differently to every remote system (such as an invisibility flag that only teammates can see) + /// The last value of each variable will be saved per remote system. + /// Unlike BeginUnreliableAckedSerialize(), send receipts are not necessary + /// Disadvantages: Every variable for every remote system is copied internally. Very memory and CPU intensive for multiple connections. + /// Advantages: When data is sent differently depending on the recipient, this system can make things easier to use and is as efficient as it can be. + /// \pre AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() must be called for new and lost connections + /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. + /// \param[in] _guid Which system we are sending to + /// \param[in] _bitSteam Which bitStream to write to + void BeginUniqueSerialize(SerializationContext *context, RakNetGUID _guid, BitStream *_bitStream); + + /// \brief Call before doing one or more SerializeVariable calls for data that is sent with the same value to every remote system (such as health, position, etc.) + /// This is the most common type of serialization, and also the most efficient + /// Disadvantages: A copy of every variable still needs to be held, although only once + /// Advantages: After the first serialization, the last serialized bitStream will be used for subsequent sends + /// \pre Call OnPreSerializeTick() before doing any calls to BeginIdenticalSerialize() for each of your objects, once per game tick + /// \param[in] context Holds the context of this group of serialize calls. This can be a stack object just passed to the function. + /// \param[in] _isFirstSerializeToThisSystem Pass true if this is the first time ever serializing to this system (the initial download). This way all variables will be written, rather than checking against prior sent values. + /// \param[in] _bitSteam Which bitStream to write to + void BeginIdenticalSerialize(SerializationContext *context, bool _isFirstSerializeToThisSystem, BitStream *_bitStream); + + /// \brief Call after BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize(), then after calling SerializeVariable() one or more times + /// \param[in] context Same context pointer passed to BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() + void EndSerialize(SerializationContext *context); + + /// \brief Call when you receive the BitStream written by SerializeVariable(), before calling DeserializeVariable() + /// \param[in] context Holds the context of this group of deserialize calls. This can be a stack object just passed to the function. + /// \param[in] _bitStream Pass the bitStream originally passed to and written to by serialize calls + void BeginDeserialize(DeserializationContext *context, BitStream *_bitStream); + + /// \param[in] context Same context pointer passed to BeginDeserialize() + void EndDeserialize(DeserializationContext *context); + + /// BeginUnreliableAckedSerialize() and BeginUniqueSerialize() require knowledge of when connections are added and dropped + /// Call AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() to notify the system of these events + /// \param[in] _guid Which system we are sending to + void AddRemoteSystemVariableHistory(RakNetGUID guid); + + /// BeginUnreliableAckedSerialize() and BeginUniqueSerialize() require knowledge of when connections are added and dropped + /// Call AddRemoteSystemVariableHistory() and RemoveRemoteSystemVariableHistory() to notify the system of these events + /// \param[in] _guid Which system we are sending to + void RemoveRemoteSystemVariableHistory(RakNetGUID guid); + + /// BeginIdenticalSerialize() requires knowledge of when serialization has started for an object across multiple systems + /// This way it can setup the flag to do new comparisons against the last sent values, rather than just resending the last sent bitStream + /// For Replica3, overload and call this from Replica3::OnUserReplicaPreSerializeTick() + void OnPreSerializeTick(void); + + /// Call when getting ID_SND_RECEIPT_LOSS or ID_SND_RECEIPT_ACKED for a particular system + /// Example: + /// + /// uint32_t msgNumber; + /// memcpy(&msgNumber, packet->data+1, 4); + /// DataStructures::List replicaListOut; + /// replicaManager.GetReplicasCreatedByMe(replicaListOut); + /// unsigned int idx; + /// for (idx=0; idx < replicaListOut.GetSize(); idx++) + /// { + /// ((SampleReplica*)replicaListOut[idx])->NotifyReplicaOfMessageDeliveryStatus(packet->guid,msgNumber, packet->data[0]==ID_SND_RECEIPT_ACKED); + /// } + /// + /// \param[in] guid Which system we are sending to + /// \param[in] receiptId Encoded in bytes 1-4 inclusive of ID_SND_RECEIPT_LOSS and ID_SND_RECEIPT_ACKED + /// \param[in] messageArrived True for ID_SND_RECEIPT_ACKED, false otherwise + void OnMessageReceipt(RakNetGUID guid, uint32_t receiptId, bool messageArrived); + + /// Call to Serialize a variable + /// Will write to the bitSteam passed to \a context true, variableValue if the variable has changed or has never been written. Otherwise will write false. + /// \pre You have called BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() + /// \pre Will also require calling OnPreSerializeTick() if using BeginIdenticalSerialize() + /// \note Be sure to call EndSerialize() after finishing all serializations + /// \param[in] context Same context pointer passed to BeginUnreliableAckedSerialize(), BeginUniqueSerialize(), or BeginIdenticalSerialize() + /// \param[in] variable A variable to write to the bitStream passed to \a context + template + void SerializeVariable(SerializationContext *context, const VarType &variable) + { + if (context->newSystemSend) + { + if (context->variableHistory->variableListDeltaTracker.IsPastEndOfList()==false) + { + // previously sent data to another system + context->bitStream->Write(true); + context->bitStream->Write(variable); + context->anyVariablesWritten=true; + } + else + { + // never sent data to another system + context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); + context->anyVariablesWritten=true; + } + } + else if (context->serializationMode==UNRELIABLE_WITH_ACK_RECEIPT) + { + context->anyVariablesWritten|= + context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream, context->changedVariables->bitField, context->changedVariables->bitWriteIndex++); + } + else + { + if (context->variableHistoryIdentical) + { + // Identical serialization to a number of systems + if (didComparisonThisTick==false) + context->anyVariablesWritten|= + context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); + // Else bitstream is written to at the end + } + else + { + // Per-system serialization + context->anyVariablesWritten|= + context->variableHistory->variableListDeltaTracker.WriteVarToBitstream(variable, context->bitStream); + } + } + } + + /// Call to deserialize into a variable + /// \pre You have called BeginDeserialize() + /// \note Be sure to call EndDeserialize() after finishing all deserializations + /// \param[in] context Same context pointer passed to BeginDeserialize() + /// \param[in] variable A variable to write to the bitStream passed to \a context + template + bool DeserializeVariable(DeserializationContext *context, VarType &variable) + { + return VariableListDeltaTracker::ReadVarFromBitstream(variable, context->bitStream); + } + + + +protected: + + // For a given send receipt from RakPeer::Send() track which variables we updated + // That way if that send does not arrive (ID_SND_RECEIPT_LOSS) we can mark those variables as dirty to resend them with current values + struct ChangedVariablesList + { + uint32_t sendReceipt; + unsigned short bitWriteIndex; + unsigned char bitField[56]; + }; + + // static int Replica2ObjectComp( const uint32_t &key, ChangedVariablesList* const &data ); + + static int UpdatedVariablesListPtrComp( const uint32_t &key, ChangedVariablesList* const &data ); + + // For each remote system, track the last values of variables we sent to them, and the history of what values changed per call to Send() + // Every serialize if a variable changes from its last value, send it out again + // Also if a send does not arrive (ID_SND_RECEIPT_LOSS) we use updatedVariablesHistory to mark those variables as dirty, to resend them unreliably with the current values + struct RemoteSystemVariableHistory + { + RakNetGUID guid; + VariableListDeltaTracker variableListDeltaTracker; + DataStructures::OrderedList updatedVariablesHistory; + }; + /// A list of RemoteSystemVariableHistory indexed by guid, one per connection that we serialize to + /// List is added to when SerializeConstruction is called, and removed from when SerializeDestruction is called, or when a given connection is dropped + DataStructures::List remoteSystemVariableHistoryList; + + // Because the ChangedVariablesList is created every serialize and destroyed every receipt I use a pool to avoid fragmentation + DataStructures::MemoryPool updatedVariablesMemoryPool; + + bool didComparisonThisTick; + RakNet::BitStream identicalSerializationBs; + + void FreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId); + void DirtyAndFreeVarsAssociatedWithReceipt(RakNetGUID guid, uint32_t receiptId); + unsigned int GetVarsWrittenPerRemoteSystemListIndex(RakNetGUID guid); + void RemoveRemoteSystemVariableHistory(void); + + RemoteSystemVariableHistory* GetRemoteSystemVariableHistory(RakNetGUID guid); + + ChangedVariablesList *AllocChangedVariablesList(void); + void FreeChangedVariablesList(ChangedVariablesList *changedVariables); + void StoreChangedVariablesList(RemoteSystemVariableHistory *variableHistory, ChangedVariablesList *changedVariables, uint32_t sendReceipt); + + RemoteSystemVariableHistory *StartVariableHistoryWrite(RakNetGUID guid); + unsigned int GetRemoteSystemHistoryListIndex(RakNetGUID guid); + +}; + +} + diff --git a/src/raknet/VariadicSQLParser.h b/src/raknet/VariadicSQLParser.h index a176751..45a6071 100755 --- a/src/raknet/VariadicSQLParser.h +++ b/src/raknet/VariadicSQLParser.h @@ -1,24 +1,22 @@ -#ifndef __VARIADIC_SQL_PARSER_H -#define __VARIADIC_SQL_PARSER_H - -#include "DS_List.h" - -#include - -namespace VariadicSQLParser -{ - struct IndexAndType - { - unsigned int strIndex; - unsigned int typeMappingIndex; - }; - const char* GetTypeMappingAtIndex(int i); - void GetTypeMappingIndices( const char *format, DataStructures::List &indices ); - // Given an SQL string with variadic arguments, allocate argumentBinary and argumentLengths, and hold the parameters in binary format - // Last 2 parameters are out parameters - void ExtractArguments( va_list argptr, const DataStructures::List &indices, char ***argumentBinary, int **argumentLengths ); - void FreeArguments(const DataStructures::List &indices, char **argumentBinary, int *argumentLengths); -} - - -#endif +#pragma once + +#include "DS_List.h" + +#include + +namespace VariadicSQLParser +{ + struct IndexAndType + { + unsigned int strIndex; + unsigned int typeMappingIndex; + }; + const char* GetTypeMappingAtIndex(int i); + void GetTypeMappingIndices( const char *format, DataStructures::List &indices ); + // Given an SQL string with variadic arguments, allocate argumentBinary and argumentLengths, and hold the parameters in binary format + // Last 2 parameters are out parameters + void ExtractArguments( va_list argptr, const DataStructures::List &indices, char ***argumentBinary, int **argumentLengths ); + void FreeArguments(const DataStructures::List &indices, char **argumentBinary, int *argumentLengths); +} + + diff --git a/src/raknet/WSAStartupSingleton.h b/src/raknet/WSAStartupSingleton.h index d2930fe..237ff71 100755 --- a/src/raknet/WSAStartupSingleton.h +++ b/src/raknet/WSAStartupSingleton.h @@ -1,16 +1,14 @@ -#ifndef __WSA_STARTUP_SINGLETON_H -#define __WSA_STARTUP_SINGLETON_H - -class WSAStartupSingleton -{ -public: - WSAStartupSingleton(); - ~WSAStartupSingleton(); - static void AddRef(void); - static void Deref(void); - -protected: - static int refCount; -}; - -#endif +#pragma once + +class WSAStartupSingleton +{ +public: + WSAStartupSingleton(); + ~WSAStartupSingleton(); + static void AddRef(void); + static void Deref(void); + +protected: + static int refCount; +}; + diff --git a/src/raknet/gettimeofday.h b/src/raknet/gettimeofday.h index 52c4207..66aa861 100755 --- a/src/raknet/gettimeofday.h +++ b/src/raknet/gettimeofday.h @@ -1,56 +1,54 @@ -#ifndef __GET_TIME_OF_DAY_H -#define __GET_TIME_OF_DAY_H - -#if defined(_WIN32) && !defined(__GNUC__) &&!defined(__GCCXML__) -#include < time.h > -struct timezone -{ - int tz_minuteswest; /* minutes W of Greenwich */ - int tz_dsttime; /* type of dst correction */ -}; -int gettimeofday(struct timeval *tv, struct timezone *tz); - - -#else - - - - -#include - -#include - -// Uncomment this if you need to -/* -// http://www.halcode.com/archives/2008/08/26/retrieving-system-time-gettimeofday/ -struct timezone -{ - int tz_minuteswest; - int tz_dsttime; -}; - -#ifdef __cplusplus - -void GetSystemTimeAsFileTime(FILETIME*); - -inline int gettimeofday(struct timeval* p, void* tz ) -{ - union { - long long ns100; // time since 1 Jan 1601 in 100ns units - FILETIME ft; - } now; - - GetSystemTimeAsFileTime( &(now.ft) ); - p->tv_usec=(long)((now.ns100 / 10LL) % 1000000LL ); - p->tv_sec= (long)((now.ns100-(116444736000000000LL))/10000000LL); - return 0; -} - -#else - int gettimeofday(struct timeval* p, void* tz ); -#endif -*/ - -#endif - -#endif +#pragma once + +#if defined(_WIN32) && !defined(__GNUC__) &&!defined(__GCCXML__) +#include < time.h > +struct timezone +{ + int tz_minuteswest; /* minutes W of Greenwich */ + int tz_dsttime; /* type of dst correction */ +}; +int gettimeofday(struct timeval *tv, struct timezone *tz); + + +#else + + + + +#include + +#include + +// Uncomment this if you need to +/* +// http://www.halcode.com/archives/2008/08/26/retrieving-system-time-gettimeofday/ +struct timezone +{ + int tz_minuteswest; + int tz_dsttime; +}; + +#ifdef __cplusplus + +void GetSystemTimeAsFileTime(FILETIME*); + +inline int gettimeofday(struct timeval* p, void* tz ) +{ + union { + long long ns100; // time since 1 Jan 1601 in 100ns units + FILETIME ft; + } now; + + GetSystemTimeAsFileTime( &(now.ft) ); + p->tv_usec=(long)((now.ns100 / 10LL) % 1000000LL ); + p->tv_sec= (long)((now.ns100-(116444736000000000LL))/10000000LL); + return 0; +} + +#else + int gettimeofday(struct timeval* p, void* tz ); +#endif +*/ + +#endif + diff --git a/src/rename.py b/src/rename.py new file mode 100644 index 0000000..ad7cc5c --- /dev/null +++ b/src/rename.py @@ -0,0 +1,22 @@ +import os + +for root, _, files in os.walk("."): + for f in files: + if f.endswith(".h"): + path = os.path.join(root, f) + with open(path, "r") as file: + lines = file.readlines() + + if len(lines) < 3: + continue + + if lines[0].startswith("#ifndef") and lines[1].startswith("#define"): + # убираем первые 2 строки и последний #endif + lines = lines[2:] + if lines[-1].strip().startswith("#endif"): + lines = lines[:-1] + + lines.insert(0, "#pragma once\n") + + with open(path, "w") as file: + file.writelines(lines) \ No newline at end of file diff --git a/src/server/ArgumentsSettings.h b/src/server/ArgumentsSettings.h index 0dcd781..cb13550 100755 --- a/src/server/ArgumentsSettings.h +++ b/src/server/ArgumentsSettings.h @@ -1,5 +1,4 @@ -#ifndef NET_MINECRAFT_WORLD_LEVEL__ArgumentsSettings_H__ -#define NET_MINECRAFT_WORLD_LEVEL__ArgumentsSettings_H__ +#pragma once #include class ArgumentsSettings { public: @@ -21,4 +20,3 @@ private: int port; }; -#endif diff --git a/src/server/CreatorLevel.h b/src/server/CreatorLevel.h index e375d18..d35935c 100755 --- a/src/server/CreatorLevel.h +++ b/src/server/CreatorLevel.h @@ -1,15 +1,13 @@ -#ifndef NET_MINECRAFT_WORLD_LEVEL__CreatorLevel_H__ -#define NET_MINECRAFT_WORLD_LEVEL__CreatorLevel_H__ - -#include "../world/level/Level.h" - -class CreatorLevel: public Level -{ - typedef Level super; -public: - CreatorLevel(LevelStorage* levelStorage, const std::string& levelName, const LevelSettings& settings, int generatorVersion, Dimension* fixedDimension = NULL); - - void tick(); -}; - -#endif /* NET_MINECRAFT_WORLD_LEVEL__CreatorLevel_H__ */ +#pragma once + +#include "../world/level/Level.h" + +class CreatorLevel: public Level +{ + typedef Level super; +public: + CreatorLevel(LevelStorage* levelStorage, const std::string& levelName, const LevelSettings& settings, int generatorVersion, Dimension* fixedDimension = NULL); + + void tick(); +}; + diff --git a/src/server/ServerLevel.h b/src/server/ServerLevel.h index 688c40d..6aee26f 100755 --- a/src/server/ServerLevel.h +++ b/src/server/ServerLevel.h @@ -1,20 +1,18 @@ -#ifndef NET_MINECRAFT_WORLD_LEVEL__ServerLevel_H__ -#define NET_MINECRAFT_WORLD_LEVEL__ServerLevel_H__ - -#include "../world/level/Level.h" - -class ServerLevel: public Level -{ - typedef Level super; -public: - ServerLevel(LevelStorage* levelStorage, const std::string& levelName, const LevelSettings& settings, int generatorVersion, Dimension* fixedDimension = NULL); - - void updateSleepingPlayerList(); - void awakenAllPlayers(); - bool allPlayersSleeping(); - void tick(); -protected: - bool allPlayersAreSleeping; -}; - -#endif /* NET_MINECRAFT_WORLD_LEVEL__ServerLevel_H__ */ +#pragma once + +#include "../world/level/Level.h" + +class ServerLevel: public Level +{ + typedef Level super; +public: + ServerLevel(LevelStorage* levelStorage, const std::string& levelName, const LevelSettings& settings, int generatorVersion, Dimension* fixedDimension = NULL); + + void updateSleepingPlayerList(); + void awakenAllPlayers(); + bool allPlayersSleeping(); + void tick(); +protected: + bool allPlayersAreSleeping; +}; + diff --git a/src/server/ServerPlayer.h b/src/server/ServerPlayer.h index de20661..9435043 100755 --- a/src/server/ServerPlayer.h +++ b/src/server/ServerPlayer.h @@ -1,55 +1,53 @@ -#ifndef ServerPlayer_H__ -#define ServerPlayer_H__ - -#include "../world/entity/player/Player.h" -#include "../world/inventory/BaseContainerMenu.h" - -class Minecraft; -class FurnaceTileEntity; -class ItemInstance; -class FillingContainer; -class ChestTileEntity; - -class ServerPlayer: public Player, - public IContainerListener -{ - typedef Player super; -public: - ServerPlayer(Minecraft* minecraft, Level* level); - - ~ServerPlayer(); - - void aiStep(); - void tick(); - void take(Entity* e, int orgCount); - - void hurtArmor(int dmg); - - void displayClientMessage(const std::string& messageId); - - void openContainer(ChestTileEntity* furnace); - void openFurnace(FurnaceTileEntity* furnace); - void closeContainer(); - void doCloseContainer(); - - bool hasResource( int id ); - // - // IContainerListener - // - void setContainerData(BaseContainerMenu* menu, int id, int value); - void slotChanged(BaseContainerMenu* menu, int slot, const ItemInstance& item, bool isResultSlot); - void refreshContainer(BaseContainerMenu* menu, const std::vector& items); - - virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint); - - void completeUsingItem(); -private: - void nextContainerCounter(); - void setContainerMenu( BaseContainerMenu* menu ); - - Minecraft* _mc; - int _prevHealth; - int _containerCounter; -}; - -#endif /*ServerPlayer_H__*/ +#pragma once + +#include "../world/entity/player/Player.h" +#include "../world/inventory/BaseContainerMenu.h" + +class Minecraft; +class FurnaceTileEntity; +class ItemInstance; +class FillingContainer; +class ChestTileEntity; + +class ServerPlayer: public Player, + public IContainerListener +{ + typedef Player super; +public: + ServerPlayer(Minecraft* minecraft, Level* level); + + ~ServerPlayer(); + + void aiStep(); + void tick(); + void take(Entity* e, int orgCount); + + void hurtArmor(int dmg); + + void displayClientMessage(const std::string& messageId); + + void openContainer(ChestTileEntity* furnace); + void openFurnace(FurnaceTileEntity* furnace); + void closeContainer(); + void doCloseContainer(); + + bool hasResource( int id ); + // + // IContainerListener + // + void setContainerData(BaseContainerMenu* menu, int id, int value); + void slotChanged(BaseContainerMenu* menu, int slot, const ItemInstance& item, bool isResultSlot); + void refreshContainer(BaseContainerMenu* menu, const std::vector& items); + + virtual void stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint); + + void completeUsingItem(); +private: + void nextContainerCounter(); + void setContainerMenu( BaseContainerMenu* menu ); + + Minecraft* _mc; + int _prevHealth; + int _containerCounter; +}; + diff --git a/src/util/CollectionUtils.h b/src/util/CollectionUtils.h index db89e6f..0575f79 100755 --- a/src/util/CollectionUtils.h +++ b/src/util/CollectionUtils.h @@ -1,17 +1,15 @@ -#ifndef COLLECTIONUTILS_H__ -#define COLLECTIONUTILS_H__ - -struct PairKeyFunctor { - template - typename T::first_type operator()(T& pair) const { - return pair.first; - } -}; -struct PairValueFunctor { - template - typename T::second_type operator()(T& pair) const { - return pair.second; - } -}; - -#endif /*COLLECTIONUTILS_H__*/ +#pragma once + +struct PairKeyFunctor { + template + typename T::first_type operator()(T& pair) const { + return pair.first; + } +}; +struct PairValueFunctor { + template + typename T::second_type operator()(T& pair) const { + return pair.second; + } +}; + diff --git a/src/util/DataIO.h b/src/util/DataIO.h index 189013c..2d3339e 100755 --- a/src/util/DataIO.h +++ b/src/util/DataIO.h @@ -1,320 +1,318 @@ -#ifndef DATAIO_H__ -#define DATAIO_H__ - -#include -#include -#include - -#include "../platform/log.h" - -// Interface for writing primitives to a stream -class IDataOutput { -public: - virtual ~IDataOutput() {} - - // Write a "Pascal" string [Len(Short)][Characters, len={strlen()-1,s.length()}] - //virtual void writePStr(const char* v, int len = -1) = 0; - //virtual void writeCStr(const char* v, int len = -1) = 0; - virtual void writeString(const std::string& v) = 0; - virtual void writeFloat(float v) = 0; - virtual void writeDouble(double v) = 0; - - virtual void writeByte(char v) = 0; - virtual void writeShort(short v) = 0; - virtual void writeInt(int v) = 0; - virtual void writeLongLong(long long v) = 0; - - virtual void writeBytes(const void* data, int bytes) = 0; -}; - - -// Interface for reading primitives from a stream -class IDataInput { -public: - virtual ~IDataInput() {} - - virtual std::string readString() = 0; - //virtual void readPStr(char**) = 0; - //virtual void readCStr(char** s, int len = -1) = 0; - virtual float readFloat() = 0; - virtual double readDouble() = 0; - - virtual char readByte() = 0; - virtual short readShort() = 0; - virtual int readInt() = 0; - virtual long long readLongLong() = 0; - - virtual void readBytes(void* data, int bytes) = 0; -}; - -/** - * Redirects all calls to writeBytes - */ -class BytesDataOutput: public IDataOutput { -public: - //virtual void writePStr(const char* v, int len = -1); - //virtual void writeCStr(const char* v, int len = -1); - virtual void writeString(const std::string& v); - virtual void writeFloat(float v) { - writeBytes(&v, 4); - } - virtual void writeDouble(double v) { - writeBytes(&v, 8); - } - virtual void writeByte(char v) { - writeBytes(&v, 1); - } - virtual void writeShort(short v) { - writeBytes(&v, 2); - } - virtual void writeInt(int v) { - writeBytes(&v, 4); - } - virtual void writeLongLong(long long v) { - writeBytes(&v, 8); - } - virtual void writeBytes(const void* data, int bytes) = 0; -}; - -/** - * Redirects all calls to readBytes - */ -class BytesDataInput: public IDataInput { -public: - //virtual void readPStr(char** s); - //virtual void readCStr(char* s, int len = -1); - virtual std::string readString(); - virtual float readFloat() { - float o; - readBytes(&o, 4); - return o; - } - virtual double readDouble() { - double o; - readBytes(&o, 8); - return o; - } - virtual char readByte() { - char o; - readBytes(&o, 1); - return o; - } - virtual short readShort() { - short o; - readBytes(&o, 2); - return o; - } - virtual int readInt() { - int o; - readBytes(&o, 4); - return o; - } - virtual long long readLongLong() { - long long o; - readBytes(&o, 8); - return o; - } - virtual void readBytes(void* data, int bytes) = 0; - -private: - static const int MAX_STRING_LENGTH = SHRT_MAX; - static char _charBuffer[MAX_STRING_LENGTH]; -}; - -//class MemoryDataInput: public BytesDataInput { -//public: -// MemoryDataInput(const char* data, int size) -// : _buffer(data), -// _size(size), -// _index(0) -// {} -// MemoryDataInput(const unsigned char* data, int size) -// : _buffer((const char*)data), -// _size(size), -// _index(0) -// {} -// -// void readBytes(void* data, int bytes) { -// if (bytes <= 0) { -// if (bytes < 0) LOGE("Error: %d bytes NOT read @ MemoryDataInput::readBytes!\n", bytes); -// return; -// } -// int left = _size - _index; -// if (bytes > left) { -// LOGE("ERROR: Not enough bytes left in buffer @ MemoryDataInput::readBytes (%d/%d).\n", bytes, left); -// _index = _size; -// return; -// } -// memcpy((char*)data, &_buffer[_index], bytes); -// _index += bytes; -// } -// -//private: -// int _index; -// int _size; -// const char* _buffer; -//}; -// -// -//class MemoryDataOutput: public BytesDataOutput { -//public: -// MemoryDataOutput(char* data, int size) -// : _buffer(data), -// _size(size), -// _index(0) -// {} -// MemoryDataOutput(unsigned char* data, int size) -// : _buffer((char*)data), -// _size(size), -// _index(0) -// {} -// -// void writeBytes(const void* data, int bytes) { -// if (bytes <= 0) { -// LOGW("Warning: %d bytes read @ MemoryDataOutput::writeBytes!\n", bytes); -// return; -// } -// int left = _size - _index; -// if (bytes > left) { -// LOGE("ERROR: Not enough bytes left in buffer @ MemoryDataOutput::writeBytes (%d/%d).\n", bytes, left); -// _index = _size; -// return; -// } -// memcpy(&_buffer[_index], (const char*)data, bytes); -// _index += bytes; -// } -// -//private: -// int _index; -// int _size; -// char* _buffer; -//}; - - -class PrintStream { -public: - void print(const std::string& s) { - } - void println(const std::string& s) { - print(s); print("\n"); - } -}; - -class FileError { -public: - static const int NOT_OPENED = 1; - static const int NOT_FULLY_HANDLED = 2; -}; -// -//class FileIO { -//public: -// FileIO(const std::string& filePath, const char* mode) -// : _filePath(filePath), -// _opened(false), -// _errCode(0), -// _fp(0), -// _doClose(true) -// { -// if (mode) -// openWithMode(mode); -// } -// FileIO(FILE* fp) -// : _filePath(""), -// _opened(fp != NULL), -// _errCode(0), -// _fp(fp), -// _doClose(false) -// {} -// -// ~FileIO() { -// if (_doClose) -// close(); -// } -// -// bool isValid() { -// return _opened; -// } -// -// int getError() { -// int err = _errCode; -// _errCode = 0; -// return err; -// } -// -// bool close() { -// if (!_fp) -// return false; -// -// fclose(_fp); -// _fp = NULL; -// _opened = false; -// return true; -// } -// -//protected: -// void openWithMode(const char* mode) { -// if (_fp) return; -// _fp = fopen(_filePath.c_str(), mode); -// _opened = (_fp != NULL); -// } -// -// std::string _filePath; -// int _errCode; -// bool _opened; -// bool _doClose; -// -// FILE* _fp; -//}; -// -//class FileDataOutput: public BytesDataOutput, public FileIO -//{ -//public: -// FileDataOutput(const std::string& filePath) -// : FileIO(filePath, "wb"), -// bytesWritten(0) -// { -// } -// FileDataOutput(FILE* fp) -// : FileIO(fp), -// bytesWritten(0) -// {} -// -// virtual void writeBytes(const void* data, int bytes) { -// if (!_fp) { -// _errCode |= FileError::NOT_OPENED; -// return; -// } -// -// int bytesWritten = fwrite(data, 1, bytes, _fp); -// if (bytesWritten != bytes) -// _errCode |= FileError::NOT_FULLY_HANDLED; -// -// this->bytesWritten += bytesWritten; -// } -// -// int bytesWritten; -//}; -// -//class FileDataInput: public BytesDataInput, public FileIO -//{ -//public: -// FileDataInput(const std::string& filePath) -// : FileIO(filePath, "rb") -// { -// } -// FileDataInput(FILE* fp) -// : FileIO(fp) -// {} -// -// virtual void readBytes(void* data, int bytes) { -// if (!_fp) { -// _errCode |= FileError::NOT_OPENED; -// return; -// } -// -// if (fread(data, 1, bytes, _fp) != bytes) -// _errCode |= FileError::NOT_FULLY_HANDLED; -// } -//}; - -#endif /*DATAIO_H__*/ +#pragma once + +#include +#include +#include + +#include "../platform/log.h" + +// Interface for writing primitives to a stream +class IDataOutput { +public: + virtual ~IDataOutput() {} + + // Write a "Pascal" string [Len(Short)][Characters, len={strlen()-1,s.length()}] + //virtual void writePStr(const char* v, int len = -1) = 0; + //virtual void writeCStr(const char* v, int len = -1) = 0; + virtual void writeString(const std::string& v) = 0; + virtual void writeFloat(float v) = 0; + virtual void writeDouble(double v) = 0; + + virtual void writeByte(char v) = 0; + virtual void writeShort(short v) = 0; + virtual void writeInt(int v) = 0; + virtual void writeLongLong(long long v) = 0; + + virtual void writeBytes(const void* data, int bytes) = 0; +}; + + +// Interface for reading primitives from a stream +class IDataInput { +public: + virtual ~IDataInput() {} + + virtual std::string readString() = 0; + //virtual void readPStr(char**) = 0; + //virtual void readCStr(char** s, int len = -1) = 0; + virtual float readFloat() = 0; + virtual double readDouble() = 0; + + virtual char readByte() = 0; + virtual short readShort() = 0; + virtual int readInt() = 0; + virtual long long readLongLong() = 0; + + virtual void readBytes(void* data, int bytes) = 0; +}; + +/** + * Redirects all calls to writeBytes + */ +class BytesDataOutput: public IDataOutput { +public: + //virtual void writePStr(const char* v, int len = -1); + //virtual void writeCStr(const char* v, int len = -1); + virtual void writeString(const std::string& v); + virtual void writeFloat(float v) { + writeBytes(&v, 4); + } + virtual void writeDouble(double v) { + writeBytes(&v, 8); + } + virtual void writeByte(char v) { + writeBytes(&v, 1); + } + virtual void writeShort(short v) { + writeBytes(&v, 2); + } + virtual void writeInt(int v) { + writeBytes(&v, 4); + } + virtual void writeLongLong(long long v) { + writeBytes(&v, 8); + } + virtual void writeBytes(const void* data, int bytes) = 0; +}; + +/** + * Redirects all calls to readBytes + */ +class BytesDataInput: public IDataInput { +public: + //virtual void readPStr(char** s); + //virtual void readCStr(char* s, int len = -1); + virtual std::string readString(); + virtual float readFloat() { + float o; + readBytes(&o, 4); + return o; + } + virtual double readDouble() { + double o; + readBytes(&o, 8); + return o; + } + virtual char readByte() { + char o; + readBytes(&o, 1); + return o; + } + virtual short readShort() { + short o; + readBytes(&o, 2); + return o; + } + virtual int readInt() { + int o; + readBytes(&o, 4); + return o; + } + virtual long long readLongLong() { + long long o; + readBytes(&o, 8); + return o; + } + virtual void readBytes(void* data, int bytes) = 0; + +private: + static const int MAX_STRING_LENGTH = SHRT_MAX; + static char _charBuffer[MAX_STRING_LENGTH]; +}; + +//class MemoryDataInput: public BytesDataInput { +//public: +// MemoryDataInput(const char* data, int size) +// : _buffer(data), +// _size(size), +// _index(0) +// {} +// MemoryDataInput(const unsigned char* data, int size) +// : _buffer((const char*)data), +// _size(size), +// _index(0) +// {} +// +// void readBytes(void* data, int bytes) { +// if (bytes <= 0) { +// if (bytes < 0) LOGE("Error: %d bytes NOT read @ MemoryDataInput::readBytes!\n", bytes); +// return; +// } +// int left = _size - _index; +// if (bytes > left) { +// LOGE("ERROR: Not enough bytes left in buffer @ MemoryDataInput::readBytes (%d/%d).\n", bytes, left); +// _index = _size; +// return; +// } +// memcpy((char*)data, &_buffer[_index], bytes); +// _index += bytes; +// } +// +//private: +// int _index; +// int _size; +// const char* _buffer; +//}; +// +// +//class MemoryDataOutput: public BytesDataOutput { +//public: +// MemoryDataOutput(char* data, int size) +// : _buffer(data), +// _size(size), +// _index(0) +// {} +// MemoryDataOutput(unsigned char* data, int size) +// : _buffer((char*)data), +// _size(size), +// _index(0) +// {} +// +// void writeBytes(const void* data, int bytes) { +// if (bytes <= 0) { +// LOGW("Warning: %d bytes read @ MemoryDataOutput::writeBytes!\n", bytes); +// return; +// } +// int left = _size - _index; +// if (bytes > left) { +// LOGE("ERROR: Not enough bytes left in buffer @ MemoryDataOutput::writeBytes (%d/%d).\n", bytes, left); +// _index = _size; +// return; +// } +// memcpy(&_buffer[_index], (const char*)data, bytes); +// _index += bytes; +// } +// +//private: +// int _index; +// int _size; +// char* _buffer; +//}; + + +class PrintStream { +public: + void print(const std::string& s) { + } + void println(const std::string& s) { + print(s); print("\n"); + } +}; + +class FileError { +public: + static const int NOT_OPENED = 1; + static const int NOT_FULLY_HANDLED = 2; +}; +// +//class FileIO { +//public: +// FileIO(const std::string& filePath, const char* mode) +// : _filePath(filePath), +// _opened(false), +// _errCode(0), +// _fp(0), +// _doClose(true) +// { +// if (mode) +// openWithMode(mode); +// } +// FileIO(FILE* fp) +// : _filePath(""), +// _opened(fp != NULL), +// _errCode(0), +// _fp(fp), +// _doClose(false) +// {} +// +// ~FileIO() { +// if (_doClose) +// close(); +// } +// +// bool isValid() { +// return _opened; +// } +// +// int getError() { +// int err = _errCode; +// _errCode = 0; +// return err; +// } +// +// bool close() { +// if (!_fp) +// return false; +// +// fclose(_fp); +// _fp = NULL; +// _opened = false; +// return true; +// } +// +//protected: +// void openWithMode(const char* mode) { +// if (_fp) return; +// _fp = fopen(_filePath.c_str(), mode); +// _opened = (_fp != NULL); +// } +// +// std::string _filePath; +// int _errCode; +// bool _opened; +// bool _doClose; +// +// FILE* _fp; +//}; +// +//class FileDataOutput: public BytesDataOutput, public FileIO +//{ +//public: +// FileDataOutput(const std::string& filePath) +// : FileIO(filePath, "wb"), +// bytesWritten(0) +// { +// } +// FileDataOutput(FILE* fp) +// : FileIO(fp), +// bytesWritten(0) +// {} +// +// virtual void writeBytes(const void* data, int bytes) { +// if (!_fp) { +// _errCode |= FileError::NOT_OPENED; +// return; +// } +// +// int bytesWritten = fwrite(data, 1, bytes, _fp); +// if (bytesWritten != bytes) +// _errCode |= FileError::NOT_FULLY_HANDLED; +// +// this->bytesWritten += bytesWritten; +// } +// +// int bytesWritten; +//}; +// +//class FileDataInput: public BytesDataInput, public FileIO +//{ +//public: +// FileDataInput(const std::string& filePath) +// : FileIO(filePath, "rb") +// { +// } +// FileDataInput(FILE* fp) +// : FileIO(fp) +// {} +// +// virtual void readBytes(void* data, int bytes) { +// if (!_fp) { +// _errCode |= FileError::NOT_OPENED; +// return; +// } +// +// if (fread(data, 1, bytes, _fp) != bytes) +// _errCode |= FileError::NOT_FULLY_HANDLED; +// } +//}; + diff --git a/src/util/IntHashMap.h b/src/util/IntHashMap.h index f76d382..032ed59 100755 --- a/src/util/IntHashMap.h +++ b/src/util/IntHashMap.h @@ -1,226 +1,224 @@ -#ifndef UTIL__IntHashMap_H__ -#define UTIL__IntHashMap_H__ - -template -class IntHashMap -{ - static const int DEFAULT_INITIAL_CAPACITY = 16; - static const int MAXIMUM_CAPACITY = 1 << 30; - //static const float DEFAULT_LOAD_FACTOR = 0.75f; - - Entry** table; - int tableCapacity; - int size; - - int threshold; - const float loadFactor; - - volatile int modCount; - -public: - IntHashMap() - : loadFactor(0.75f) - { - threshold = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); - table = new Entry[DEFAULT_INITIAL_CAPACITY]; - } - - ~IntHashMap() { - delete[] table; - } - - /*public*/ int size() { - return size; - } - - /*public*/ bool isEmpty() { - return size == 0; - } - - /*public*/ V get(int key) { - int hash = hash(key); - for (Entry e = table[indexFor(hash, table.length)]; e != NULL; e = e.next) { - if (e.key == key) return e.value; - } - return NULL; - } - - /*public*/ bool containsKey(int key) { - return getEntry(key) != NULL; - } - - const Entry getEntry(int key) { - int hash = hash(key); - for (Entry e = table[indexFor(hash, table.length)]; e != NULL; e = e.next) { - if (e.key == key) return e; - } - return NULL; - } - - /*public*/ void put(int key, V value) { - int hash = hash(key); - int i = indexFor(hash, table.length); - for (Entry e = table[i]; e != NULL; e = e.next) { - if (e.key == key) { - e.value = value; - } - } - - modCount++; - addEntry(hash, key, value, i); - } - - //@SuppressWarnings("unchecked") - /*private*/ void resize(int newCapacity) { - Entry[] oldTable = table; - int oldCapacity = oldTable.length; - if (oldCapacity == MAXIMUM_CAPACITY) { - threshold = INT_MAX;//Integer.MAX_VALUE; - return; - } - - Entry[] newTable = /*new*/ Entry[newCapacity]; - transfer(newTable); - table = newTable; - threshold = (int) (newCapacity * loadFactor); - } - - /*private*/ void transfer(Entry[] newTable) { - Entry[] src = table; - int newCapacity = newTable.length; - for (int j = 0; j < src.length; j++) { - Entry e = src[j]; - if (e != NULL) { - src[j] = NULL; - do { - Entry next = e.next; - int i = indexFor(e.hash, newCapacity); - e.next = newTable[i]; - newTable[i] = e; - e = next; - } while (e != NULL); - } - } - } - - /*public*/ V remove(int key) { - Entry e = removeEntryForKey(key); - return (e == NULL ? NULL : e.value); - } - - const Entry removeEntryForKey(int key) { - int hash = hash(key); - int i = indexFor(hash, table.length); - Entry prev = table[i]; - Entry e = prev; - - while (e != NULL) { - Entry next = e.next; - if (e.key == key) { - modCount++; - size--; - if (prev == e) table[i] = next; - else prev.next = next; - return e; - } - prev = e; - e = next; - } - - return e; - } - - /*public*/ void clear() { - modCount++; - Entry[] tab = table; - for (int i = 0; i < tab.length; i++) - tab[i] = NULL; - size = 0; - } - - /** - * Returns true if this map maps one or more keys to the specified - * value. - * - * @param value value whose presence in this map is to be tested - * @return true if this map maps one or more keys to the specified - * value - */ - /*public*/ bool containsValue(Object value) { - if (value == NULL) return containsNullValue(); - - Entry[] tab = table; - for (int i = 0; i < tab.length; i++) - for (Entry e = tab[i]; e != NULL; e = e.next) - if (value.equals(e.value)) return true; - return false; - } - - /*private*/ bool containsNullValue() { - Entry[] tab = table; - for (int i = 0; i < tab.length; i++) - for (Entry e = tab[i]; e != NULL; e = e.next) - if (e.value == NULL) return true; - return false; - } - - /*private*/ - template - class Entry { - const int key; - V value; - Entry* next; - const int hash; - - /** - * Creates new entry. - */ - Entry(int h, int k, V v, Entry* n) - : value(v), - next(n), - key(k), - hash(h) - { - } - - const int getKey() { - return key; - } - - const V getValue() { - return value; - } - - //@SuppressWarnings("unchecked") - bool operator==(const Entry& rhs) { - return key == rhs.key && value == rhs.value; - } - - const int hashCode() { - return hash(key); - } - - const std::string toString() { - std::stringstream ss; - ss << getKey() << "=" << getValue(); - return ss.str(); - } - } -private: - static int hash(int h) { - h ^= (h >>> 20) ^ (h >>> 12); - return h ^ (h >>> 7) ^ (h >>> 4); - } - - static int indexFor(int h, int length) { - return h & (length - 1); - } - - void addEntry(int hash, int key, V value, int bucketIndex) { - Entry e = table[bucketIndex]; - table[bucketIndex] = /*new*/ Entry(hash, key, value, e); - if (size++ >= threshold) resize(2 * table.length); - } -}; - -#endif /*UTIL__IntHashMap_H__*/ +#pragma once + +template +class IntHashMap +{ + static const int DEFAULT_INITIAL_CAPACITY = 16; + static const int MAXIMUM_CAPACITY = 1 << 30; + //static const float DEFAULT_LOAD_FACTOR = 0.75f; + + Entry** table; + int tableCapacity; + int size; + + int threshold; + const float loadFactor; + + volatile int modCount; + +public: + IntHashMap() + : loadFactor(0.75f) + { + threshold = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); + table = new Entry[DEFAULT_INITIAL_CAPACITY]; + } + + ~IntHashMap() { + delete[] table; + } + + /*public*/ int size() { + return size; + } + + /*public*/ bool isEmpty() { + return size == 0; + } + + /*public*/ V get(int key) { + int hash = hash(key); + for (Entry e = table[indexFor(hash, table.length)]; e != NULL; e = e.next) { + if (e.key == key) return e.value; + } + return NULL; + } + + /*public*/ bool containsKey(int key) { + return getEntry(key) != NULL; + } + + const Entry getEntry(int key) { + int hash = hash(key); + for (Entry e = table[indexFor(hash, table.length)]; e != NULL; e = e.next) { + if (e.key == key) return e; + } + return NULL; + } + + /*public*/ void put(int key, V value) { + int hash = hash(key); + int i = indexFor(hash, table.length); + for (Entry e = table[i]; e != NULL; e = e.next) { + if (e.key == key) { + e.value = value; + } + } + + modCount++; + addEntry(hash, key, value, i); + } + + //@SuppressWarnings("unchecked") + /*private*/ void resize(int newCapacity) { + Entry[] oldTable = table; + int oldCapacity = oldTable.length; + if (oldCapacity == MAXIMUM_CAPACITY) { + threshold = INT_MAX;//Integer.MAX_VALUE; + return; + } + + Entry[] newTable = /*new*/ Entry[newCapacity]; + transfer(newTable); + table = newTable; + threshold = (int) (newCapacity * loadFactor); + } + + /*private*/ void transfer(Entry[] newTable) { + Entry[] src = table; + int newCapacity = newTable.length; + for (int j = 0; j < src.length; j++) { + Entry e = src[j]; + if (e != NULL) { + src[j] = NULL; + do { + Entry next = e.next; + int i = indexFor(e.hash, newCapacity); + e.next = newTable[i]; + newTable[i] = e; + e = next; + } while (e != NULL); + } + } + } + + /*public*/ V remove(int key) { + Entry e = removeEntryForKey(key); + return (e == NULL ? NULL : e.value); + } + + const Entry removeEntryForKey(int key) { + int hash = hash(key); + int i = indexFor(hash, table.length); + Entry prev = table[i]; + Entry e = prev; + + while (e != NULL) { + Entry next = e.next; + if (e.key == key) { + modCount++; + size--; + if (prev == e) table[i] = next; + else prev.next = next; + return e; + } + prev = e; + e = next; + } + + return e; + } + + /*public*/ void clear() { + modCount++; + Entry[] tab = table; + for (int i = 0; i < tab.length; i++) + tab[i] = NULL; + size = 0; + } + + /** + * Returns true if this map maps one or more keys to the specified + * value. + * + * @param value value whose presence in this map is to be tested + * @return true if this map maps one or more keys to the specified + * value + */ + /*public*/ bool containsValue(Object value) { + if (value == NULL) return containsNullValue(); + + Entry[] tab = table; + for (int i = 0; i < tab.length; i++) + for (Entry e = tab[i]; e != NULL; e = e.next) + if (value.equals(e.value)) return true; + return false; + } + + /*private*/ bool containsNullValue() { + Entry[] tab = table; + for (int i = 0; i < tab.length; i++) + for (Entry e = tab[i]; e != NULL; e = e.next) + if (e.value == NULL) return true; + return false; + } + + /*private*/ + template + class Entry { + const int key; + V value; + Entry* next; + const int hash; + + /** + * Creates new entry. + */ + Entry(int h, int k, V v, Entry* n) + : value(v), + next(n), + key(k), + hash(h) + { + } + + const int getKey() { + return key; + } + + const V getValue() { + return value; + } + + //@SuppressWarnings("unchecked") + bool operator==(const Entry& rhs) { + return key == rhs.key && value == rhs.value; + } + + const int hashCode() { + return hash(key); + } + + const std::string toString() { + std::stringstream ss; + ss << getKey() << "=" << getValue(); + return ss.str(); + } + } +private: + static int hash(int h) { + h ^= (h >>> 20) ^ (h >>> 12); + return h ^ (h >>> 7) ^ (h >>> 4); + } + + static int indexFor(int h, int length) { + return h & (length - 1); + } + + void addEntry(int hash, int key, V value, int bucketIndex) { + Entry e = table[bucketIndex]; + table[bucketIndex] = /*new*/ Entry(hash, key, value, e); + if (size++ >= threshold) resize(2 * table.length); + } +}; + diff --git a/src/util/MemUtils.h b/src/util/MemUtils.h index f38f288..062b66d 100755 --- a/src/util/MemUtils.h +++ b/src/util/MemUtils.h @@ -1,35 +1,33 @@ -#ifndef MEMUTILS_H__ -#define MEMUTILS_H__ - -template -class Ref { -public: - //~Ref() { //@todo: add this if the pointer is created externally - // dec(); - //} - void inc() { ++_count; } - void dec() { if (--_count == 0 && _obj) delete _obj; } - - inline short refCount() { return _count; } - inline bool isUnique() { return _count == 1; } - - inline T* obj() { return _obj; } - - T& operator->() { return *_obj; } - void operator++() { inc(); } - void operator--() { dec(); } - - static Ref* create(T* object) { return new Ref(object); } -private: - Ref(T* object) - : _obj(object), - _count(1) {} - - Ref(const Ref& rhs); - Ref& operator=(const Ref& rhs); - - T* _obj; - short _count; -}; - -#endif /*MEMUTILS_H__*/ +#pragma once + +template +class Ref { +public: + //~Ref() { //@todo: add this if the pointer is created externally + // dec(); + //} + void inc() { ++_count; } + void dec() { if (--_count == 0 && _obj) delete _obj; } + + inline short refCount() { return _count; } + inline bool isUnique() { return _count == 1; } + + inline T* obj() { return _obj; } + + T& operator->() { return *_obj; } + void operator++() { inc(); } + void operator--() { dec(); } + + static Ref* create(T* object) { return new Ref(object); } +private: + Ref(T* object) + : _obj(object), + _count(1) {} + + Ref(const Ref& rhs); + Ref& operator=(const Ref& rhs); + + T* _obj; + short _count; +}; + diff --git a/src/util/Mth.h b/src/util/Mth.h index 55ce7d6..4586fb9 100755 --- a/src/util/Mth.h +++ b/src/util/Mth.h @@ -1,97 +1,95 @@ -#ifndef MTH_H__ -#define MTH_H__ - -#include -#include -#include - -namespace Mth { - constexpr float PI = 3.1415926535897932384626433832795028841971f; // exactly! - constexpr float TWO_PI = 2.0f * PI; // exactly! - constexpr float DEGRAD = PI / 180.0f; - const float RADDEG = 180.0f / PI; - - void initMth(); - - float sqrt(float x); - float invSqrt(float x); - - int floor(float x); - - float sin(float x); - float cos(float x); - - float atan(float x); - float atan2(float dy, float dx); - - float random(); - int random(int n); - - float abs(float a); - float Min(float a, float b); - float Max(float a, float b); - int abs(int a); - int Min(int a, int b); - int Max(int a, int b); - - int clamp(int v, int low, int high); - float clamp(float v, float low, float high); - float lerp(float src, float dst, float alpha); - int lerp(int src, int dst, float alpha); - - ///@param value The original signed value - ///@param with The (possibly signed) value to "abs-decrease" with - ///@param min The minimum value - float absDecrease(float value, float with, float min); - //float absIncrease(float value, float with, float max); - - float absMax(float a, float b); - float absMaxSigned(float a, float b); - - int intFloorDiv(int a, int b); -}; - -namespace Util -{ - template - int removeAll(std::vector& superset, const std::vector& toRemove) { - int subSize = (int)toRemove.size(); - int removed = 0; - - for (int i = 0; i < subSize; ++i) { - T elem = toRemove[i]; - int size = (int)superset.size(); - for (int j = 0; j < size; ++j) { - if (elem == superset[j]) { - superset.erase( superset.begin() + j, superset.begin() + j + 1); - ++removed; - break; - } - } - } - return removed; - } - - template - bool remove(std::vector& list, const T& instance) { - typename std::vector::iterator it = std::find(list.begin(), list.end(), instance); - if (it == list.end()) - return false; - - list.erase(it); - return true; - } - - // Could perhaps do a template